language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__maven | compat/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionResult.java | {
"start": 1752,
"end": 10201
} | class ____ {
private static final String LS = System.lineSeparator();
private Artifact originatingArtifact;
private List<Artifact> missingArtifacts;
// Exceptions
private List<Exception> exceptions;
private List<Exception> versionRangeViolations;
private List<ArtifactResolutionException> metadataResolutionExceptions;
private List<CyclicDependencyException> circularDependencyExceptions;
private List<ArtifactResolutionException> errorArtifactExceptions;
// file system errors
private List<ArtifactRepository> repositories;
private Set<Artifact> artifacts;
private Set<ResolutionNode> resolutionNodes;
public Artifact getOriginatingArtifact() {
return originatingArtifact;
}
public ArtifactResolutionResult setOriginatingArtifact(final Artifact originatingArtifact) {
this.originatingArtifact = originatingArtifact;
return this;
}
public void addArtifact(Artifact artifact) {
if (artifacts == null) {
artifacts = new LinkedHashSet<>();
}
artifacts.add(artifact);
}
public Set<Artifact> getArtifacts() {
if (artifacts == null) {
artifacts = new LinkedHashSet<>();
}
return artifacts;
}
public void setArtifacts(Set<Artifact> artifacts) {
this.artifacts = artifacts;
}
public Set<ResolutionNode> getArtifactResolutionNodes() {
if (resolutionNodes == null) {
resolutionNodes = new LinkedHashSet<>();
}
return resolutionNodes;
}
public void setArtifactResolutionNodes(Set<ResolutionNode> resolutionNodes) {
this.resolutionNodes = resolutionNodes;
}
public boolean hasMissingArtifacts() {
return missingArtifacts != null && !missingArtifacts.isEmpty();
}
public List<Artifact> getMissingArtifacts() {
return missingArtifacts == null ? Collections.emptyList() : Collections.unmodifiableList(missingArtifacts);
}
public ArtifactResolutionResult addMissingArtifact(Artifact artifact) {
missingArtifacts = initList(missingArtifacts);
missingArtifacts.add(artifact);
return this;
}
public ArtifactResolutionResult setUnresolvedArtifacts(final List<Artifact> unresolvedArtifacts) {
this.missingArtifacts = unresolvedArtifacts;
return this;
}
public boolean isSuccess() {
return !(hasMissingArtifacts() || hasExceptions());
}
// ------------------------------------------------------------------------
// Exceptions
// ------------------------------------------------------------------------
public boolean hasExceptions() {
return exceptions != null && !exceptions.isEmpty();
}
public List<Exception> getExceptions() {
return exceptions == null ? Collections.emptyList() : Collections.unmodifiableList(exceptions);
}
// ------------------------------------------------------------------------
// Version Range Violations
// ------------------------------------------------------------------------
public boolean hasVersionRangeViolations() {
return versionRangeViolations != null;
}
/**
* TODO this needs to accept a {@link OverConstrainedVersionException} as returned by
* {@link #getVersionRangeViolation(int)} but it's not used like that in
* DefaultLegacyArtifactCollector
*
* @param e an exception
* @return {@code this}
*/
public ArtifactResolutionResult addVersionRangeViolation(Exception e) {
versionRangeViolations = initList(versionRangeViolations);
versionRangeViolations.add(e);
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public OverConstrainedVersionException getVersionRangeViolation(int i) {
return (OverConstrainedVersionException) versionRangeViolations.get(i);
}
public List<Exception> getVersionRangeViolations() {
return versionRangeViolations == null
? Collections.emptyList()
: Collections.unmodifiableList(versionRangeViolations);
}
// ------------------------------------------------------------------------
// Metadata Resolution Exceptions: ArtifactResolutionExceptions
// ------------------------------------------------------------------------
public boolean hasMetadataResolutionExceptions() {
return metadataResolutionExceptions != null;
}
public ArtifactResolutionResult addMetadataResolutionException(ArtifactResolutionException e) {
metadataResolutionExceptions = initList(metadataResolutionExceptions);
metadataResolutionExceptions.add(e);
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public ArtifactResolutionException getMetadataResolutionException(int i) {
return metadataResolutionExceptions.get(i);
}
public List<ArtifactResolutionException> getMetadataResolutionExceptions() {
return metadataResolutionExceptions == null
? Collections.emptyList()
: Collections.unmodifiableList(metadataResolutionExceptions);
}
// ------------------------------------------------------------------------
// ErrorArtifactExceptions: ArtifactResolutionExceptions
// ------------------------------------------------------------------------
public boolean hasErrorArtifactExceptions() {
return errorArtifactExceptions != null;
}
public ArtifactResolutionResult addErrorArtifactException(ArtifactResolutionException e) {
errorArtifactExceptions = initList(errorArtifactExceptions);
errorArtifactExceptions.add(e);
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public List<ArtifactResolutionException> getErrorArtifactExceptions() {
if (errorArtifactExceptions == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(errorArtifactExceptions);
}
// ------------------------------------------------------------------------
// Circular Dependency Exceptions
// ------------------------------------------------------------------------
public boolean hasCircularDependencyExceptions() {
return circularDependencyExceptions != null;
}
public ArtifactResolutionResult addCircularDependencyException(CyclicDependencyException e) {
circularDependencyExceptions = initList(circularDependencyExceptions);
circularDependencyExceptions.add(e);
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public CyclicDependencyException getCircularDependencyException(int i) {
return circularDependencyExceptions.get(i);
}
public List<CyclicDependencyException> getCircularDependencyExceptions() {
if (circularDependencyExceptions == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(circularDependencyExceptions);
}
// ------------------------------------------------------------------------
// Repositories
// ------------------------------------------------------------------------
public List<ArtifactRepository> getRepositories() {
if (repositories == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(repositories);
}
public ArtifactResolutionResult setRepositories(final List<ArtifactRepository> repositories) {
this.repositories = repositories;
return this;
}
//
// Internal
//
private <T> List<T> initList(final List<T> l) {
if (l == null) {
return new ArrayList<>();
}
return l;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (artifacts != null) {
int i = 1;
sb.append("---------").append(LS);
sb.append(artifacts.size()).append(LS);
for (Artifact a : artifacts) {
sb.append(i).append(' ').append(a).append(LS);
i++;
}
sb.append("---------");
}
return sb.toString();
}
}
| ArtifactResolutionResult |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java | {
"start": 11203,
"end": 11391
} | class ____ {
}
@Configuration(proxyBeanMethods = false)
@ImportAutoConfiguration(TestPropertyAutoConfiguration.class)
@Import(NumberHandler.class)
static | StringPropertyTypeConfiguration |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/javadoc/MalformedInlineTagTest.java | {
"start": 2953,
"end": 3196
} | class ____ {}
""")
.doTest(TEXT_MATCH);
}
@Test
public void negative() {
helper
.addInputLines(
"Test.java",
"""
/** A correct {@link Test} tag in text. */
| Test |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/JdkProxyControllerTests.java | {
"start": 3888,
"end": 4054
} | class ____ implements TypeLevel {
@Override
public void doIt(Writer writer) throws IOException {
writer.write("doIt");
}
}
@Controller
public | TypeLevelImpl |
java | spring-projects__spring-framework | spring-core-test/src/main/java/org/springframework/core/test/tools/Compiled.java | {
"start": 996,
"end": 3283
} | class ____ {
private final ClassLoader classLoader;
private final SourceFiles sourceFiles;
private final ResourceFiles resourceFiles;
private @Nullable List<Class<?>> compiledClasses;
Compiled(ClassLoader classLoader, SourceFiles sourceFiles, ResourceFiles resourceFiles) {
this.classLoader = classLoader;
this.sourceFiles = sourceFiles;
this.resourceFiles = resourceFiles;
}
/**
* Return the classloader containing the compiled content and access to the
* resources.
* @return the classLoader
*/
public ClassLoader getClassLoader() {
return this.classLoader;
}
/**
* Return the single source file that was compiled.
* @return the single source file
* @throws IllegalStateException if the compiler wasn't passed exactly one
* file
*/
public SourceFile getSourceFile() {
return this.sourceFiles.getSingle();
}
/**
* Return the single matching source file that was compiled.
* @param pattern the pattern used to find the file
* @return the single source file
* @throws IllegalStateException if the compiler wasn't passed exactly one
* file
*/
public SourceFile getSourceFile(String pattern) {
return this.sourceFiles.getSingle(pattern);
}
/**
* Return the single source file that was compiled in the given package.
* @param packageName the package name to check
* @return the single source file
* @throws IllegalStateException if the compiler wasn't passed exactly one
* file
*/
public SourceFile getSourceFileFromPackage(String packageName) {
return this.sourceFiles.getSingleFromPackage(packageName);
}
/**
* Return all source files that were compiled.
* @return the source files used by the compiler
*/
public SourceFiles getSourceFiles() {
return this.sourceFiles;
}
/**
* Return the single resource file that was used when compiled.
* @return the single resource file
* @throws IllegalStateException if the compiler wasn't passed exactly one
* file
*/
public ResourceFile getResourceFile() {
return this.resourceFiles.getSingle();
}
/**
* Return all resource files that were compiled.
* @return the resource files used by the compiler
*/
public ResourceFiles getResourceFiles() {
return this.resourceFiles;
}
/**
* Return a new instance of a compiled | Compiled |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonEncoderTests.java | {
"start": 11366,
"end": 11404
} | class ____ extends ParentClass {
}
}
| Bar |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/impl/TestNetworkBinding.java | {
"start": 1147,
"end": 1872
} | class ____ extends AbstractHadoopTestBase {
private static final String US_EAST_1 = "us-east-1";
private static final String US_WEST_2 = "us-west-2";
@Test
public void testUSEast() {
assertRegionFixup(US_EAST_1, US_EAST_1);
}
@Test
public void testUSWest() {
assertRegionFixup(US_WEST_2, US_WEST_2);
}
@Test
public void testRegionUStoUSEast() {
assertRegionFixup("US", US_EAST_1);
}
@Test
public void testRegionNullToUSEast() {
assertRegionFixup(null, US_EAST_1);
}
private static void assertRegionFixup(String region, String expected) {
assertThat(fixBucketRegion(region))
.describedAs("Fixup of %s", region)
.isEqualTo(expected);
}
}
| TestNetworkBinding |
java | junit-team__junit5 | junit-platform-engine/src/main/java/org/junit/platform/engine/discovery/DiscoverySelectors.java | {
"start": 38094,
"end": 38442
} | class ____ select; never {@code null} or blank
* @since 1.10
* @see NestedClassSelector
*/
@API(status = MAINTAINED, since = "1.13.3")
public static NestedClassSelector selectNestedClass(@Nullable ClassLoader classLoader,
List<String> enclosingClassNames, String nestedClassName) {
Preconditions.notEmpty(enclosingClassNames, "Enclosing | to |
java | quarkusio__quarkus | integration-tests/hibernate-orm-panache/src/main/java/io/quarkus/it/panache/defaultpu/AddressDao.java | {
"start": 182,
"end": 242
} | class ____ implements PanacheRepository<Address> {
}
| AddressDao |
java | spring-projects__spring-boot | module/spring-boot-web-server/src/testFixtures/java/org/springframework/boot/web/server/servlet/AbstractServletWebServerServletContextListenerTests.java | {
"start": 1455,
"end": 1618
} | class ____ tests for {@link WebServer}s driving {@link ServletContextListener}s
* correctly.
*
* @author Andy Wilkinson
*/
@DirtiesUrlFactories
public abstract | for |
java | quarkusio__quarkus | extensions/spring-web/core/runtime/src/main/java/io/quarkus/spring/web/runtime/SpringWebEndpointProvider.java | {
"start": 380,
"end": 2788
} | class ____ implements TestHttpEndpointProvider {
@Override
public Function<Class<?>, String> endpointProvider() {
return new Function<Class<?>, String>() {
@Override
public String apply(Class<?> aClass) {
String[] paths = getPath(aClass);
if (paths == null) {
return null;
}
String value;
if (paths.length == 0) {
value = "";
} else {
value = paths[0];
if (value.startsWith("/")) {
value = value.substring(1);
}
}
//TODO: there is not really any way to handle @ApplicationPath, we could do something for @QuarkusTest apps but we can't for
//native apps, so we just have to document the limitation
String path = "/";
Optional<String> appPath = ConfigProvider.getConfig().getOptionalValue("quarkus.resteasy.path", String.class);
if (appPath.isPresent()) {
path = appPath.get();
}
if (!path.endsWith("/")) {
path = path + "/";
}
value = path + value;
return value;
}
};
}
private String[] getPath(Class<?> aClass) {
String[] value = null;
for (Annotation annotation : aClass.getAnnotations()) {
if (annotation.annotationType().getName().equals(RequestMapping.class.getName())) {
try {
value = (String[]) annotation.annotationType().getMethod("value").invoke(annotation);
break;
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
if (value == null) {
for (Class<?> i : aClass.getInterfaces()) {
value = getPath(i);
if (value != null) {
break;
}
}
}
if (value == null) {
if (aClass.getSuperclass() != Object.class) {
value = getPath(aClass.getSuperclass());
}
}
return value;
}
}
| SpringWebEndpointProvider |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/mapper/LongFieldScriptTests.java | {
"start": 1331,
"end": 4873
} | class ____ extends FieldScriptTestCase<LongFieldScript.Factory> {
public static final LongFieldScript.Factory DUMMY = (fieldName, params, lookup, onScriptError) -> ctx -> new LongFieldScript(
fieldName,
params,
lookup,
OnScriptError.FAIL,
ctx
) {
@Override
public void execute() {
emit(1);
}
};
@Override
protected ScriptContext<LongFieldScript.Factory> context() {
return LongFieldScript.CONTEXT;
}
@Override
protected LongFieldScript.Factory dummyScript() {
return DUMMY;
}
@Override
protected LongFieldScript.Factory fromSource() {
return LongFieldScript.PARSE_FROM_SOURCE;
}
public void testTooManyValues() throws IOException {
try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) {
iw.addDocument(List.of(new StoredField("_source", new BytesRef("{}"))));
try (DirectoryReader reader = iw.getReader()) {
LongFieldScript script = new LongFieldScript(
"test",
Map.of(),
new SearchLookup(field -> null, (ft, lookup, fdt) -> null, (ctx, doc) -> null),
OnScriptError.FAIL,
reader.leaves().get(0)
) {
@Override
public void execute() {
for (int i = 0; i <= AbstractFieldScript.MAX_VALUES; i++) {
new Emit(this).emit(0);
}
}
};
Exception e = expectThrows(IllegalArgumentException.class, script::execute);
assertThat(
e.getMessage(),
equalTo("Runtime field [test] is emitting [101] values while the maximum number of values allowed is [100]")
);
}
}
}
public final void testFromSourceDoesNotEnforceValuesLimit() throws IOException {
try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) {
int numValues = AbstractFieldScript.MAX_VALUES + randomIntBetween(1, 100);
XContentBuilder builder = JsonXContent.contentBuilder();
builder.startObject();
builder.startArray("field");
for (int i = 0; i < numValues; i++) {
builder.value(i);
}
builder.endArray();
builder.endObject();
iw.addDocument(List.of(new StoredField("_source", new BytesRef(Strings.toString(builder)))));
try (DirectoryReader reader = iw.getReader()) {
LongFieldScript.LeafFactory leafFactory = fromSource().newFactory(
"field",
Collections.emptyMap(),
new SearchLookup(
field -> null,
(ft, lookup, fdt) -> null,
SourceProvider.fromLookup(MappingLookup.EMPTY, null, SourceFieldMetrics.NOOP)
),
OnScriptError.FAIL
);
LongFieldScript longFieldScript = leafFactory.newInstance(reader.leaves().get(0));
List<Long> results = new ArrayList<>();
longFieldScript.runForDoc(0, results::add);
assertEquals(numValues, results.size());
}
}
}
}
| LongFieldScriptTests |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Issue87.java | {
"start": 588,
"end": 907
} | class ____ {
private Set<String> set = new HashSet<String>(0);
public Set<String> getSet() {
return set;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void add(String str) {
set.add(str);
}
}
}
| TestObject |
java | apache__camel | catalog/camel-report-maven-plugin/src/main/java/org/apache/camel/maven/htmlxlsx/model/Components.java | {
"start": 1295,
"end": 2908
} | class ____ {
private Map<String, List<EipAttribute>> attributeMap = new HashMap<>();
@JsonIgnore
private final ObjectMapper objectMapper = new ObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
@JsonAnySetter
public void setAttribute(String key, Object value) throws JsonProcessingException {
List<EipAttribute> listValue;
if (value instanceof String) {
EipAttribute eipAttribute
= objectMapper.readValue(String.format("{\"%s\":\"%s\"}", key, value), EipAttribute.class);
listValue = Collections.singletonList(eipAttribute);
} else if (!(value instanceof List)) {
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(value);
EipAttribute eipAttribute = objectMapper.readValue(json, EipAttribute.class);
listValue = Collections.singletonList(eipAttribute);
} else {
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(value);
listValue = objectMapper.readValue(json, new TypeReference<List<EipAttribute>>() {
});
}
attributeMap.put(key, listValue);
}
public Map<String, List<EipAttribute>> getAttributeMap() {
return attributeMap;
}
public void setAttributeMap(Map<String, List<EipAttribute>> attributeMap) {
this.attributeMap = attributeMap;
}
@Override
public String toString() {
return "Components{" +
"attributeMap=" + attributeMap +
'}';
}
}
| Components |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/impl/prefetch/SingleFilePerBlockCache.java | {
"start": 3895,
"end": 4093
} | class ____ {
private final int blockNumber;
private final Path path;
private final int size;
private final long checksum;
private final ReentrantReadWriteLock lock;
private | Entry |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/EntityGraph.java | {
"start": 2445,
"end": 3687
} | enum ____ {
/**
* When the jakarta.persistence.loadgraph property is used to specify an entity graph, attributes that are specified
* by attribute nodes of the entity graph are treated as FetchType.EAGER and attributes that are not specified are
* treated according to their specified or default FetchType.
*
* @see <a href="https://jakarta.ee/specifications/persistence/3.1/jakarta-persistence-spec-3.1#load-graph-semantics">Jakarta
* Persistence Specification: Load Graph Semantics</a>
*/
LOAD("jakarta.persistence.loadgraph"),
/**
* When the jakarta.persistence.fetchgraph property is used to specify an entity graph, attributes that are specified
* by attribute nodes of the entity graph are treated as FetchType.EAGER and attributes that are not specified are
* treated as FetchType.LAZY
*
* @see <a href="https://jakarta.ee/specifications/persistence/3.1/jakarta-persistence-spec-3.1#fetch-graph-semantics">Jakarta
* Persistence Specification: Fetch Graph Semantics</a>
*/
FETCH("jakarta.persistence.fetchgraph");
private final String key;
private EntityGraphType(String value) {
this.key = value;
}
public String getKey() {
return key;
}
}
}
| EntityGraphType |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrunkenIndexCheckStepInfoTests.java | {
"start": 564,
"end": 1624
} | class ____ extends AbstractXContentTestCase<ShrunkenIndexCheckStep.Info> {
@Override
protected Info createTestInstance() {
return new Info(randomAlphaOfLengthBetween(10, 20));
}
@Override
protected Info doParseInstance(XContentParser parser) throws IOException {
return Info.PARSER.apply(parser, null);
}
@Override
protected boolean supportsUnknownFields() {
return false;
}
public final void testEqualsAndHashcode() {
for (int runs = 0; runs < NUMBER_OF_TEST_RUNS; runs++) {
EqualsHashCodeTestUtils.checkEqualsAndHashCode(createTestInstance(), this::copyInstance, this::mutateInstance);
}
}
protected final Info copyInstance(Info instance) throws IOException {
return new Info(instance.getOriginalIndexName());
}
protected Info mutateInstance(Info instance) throws IOException {
return new Info(randomValueOtherThan(instance.getOriginalIndexName(), () -> randomAlphaOfLengthBetween(10, 20)));
}
}
| ShrunkenIndexCheckStepInfoTests |
java | google__guava | android/guava/src/com/google/common/hash/Murmur3_32HashFunction.java | {
"start": 1942,
"end": 7812
} | class ____ extends AbstractHashFunction implements Serializable {
static final HashFunction MURMUR3_32 =
new Murmur3_32HashFunction(0, /* supplementaryPlaneFix= */ false);
static final HashFunction MURMUR3_32_FIXED =
new Murmur3_32HashFunction(0, /* supplementaryPlaneFix= */ true);
// We can include the non-BMP fix here because Hashing.goodFastHash stresses that the hash is a
// temporary-use one. Therefore it shouldn't be persisted.
static final HashFunction GOOD_FAST_HASH_32 =
new Murmur3_32HashFunction(Hashing.GOOD_FAST_HASH_SEED, /* supplementaryPlaneFix= */ true);
private static final int CHUNK_SIZE = 4;
private static final int C1 = 0xcc9e2d51;
private static final int C2 = 0x1b873593;
private final int seed;
private final boolean supplementaryPlaneFix;
Murmur3_32HashFunction(int seed, boolean supplementaryPlaneFix) {
this.seed = seed;
this.supplementaryPlaneFix = supplementaryPlaneFix;
}
@Override
public int bits() {
return 32;
}
@Override
public Hasher newHasher() {
return new Murmur3_32Hasher(seed);
}
@Override
public String toString() {
return "Hashing.murmur3_32(" + seed + ")";
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof Murmur3_32HashFunction) {
Murmur3_32HashFunction other = (Murmur3_32HashFunction) object;
return seed == other.seed && supplementaryPlaneFix == other.supplementaryPlaneFix;
}
return false;
}
@Override
public int hashCode() {
return getClass().hashCode() ^ seed;
}
@Override
public HashCode hashInt(int input) {
int k1 = mixK1(input);
int h1 = mixH1(seed, k1);
return fmix(h1, Ints.BYTES);
}
@Override
public HashCode hashLong(long input) {
int low = (int) input;
int high = (int) (input >>> 32);
int k1 = mixK1(low);
int h1 = mixH1(seed, k1);
k1 = mixK1(high);
h1 = mixH1(h1, k1);
return fmix(h1, Longs.BYTES);
}
@Override
public HashCode hashUnencodedChars(CharSequence input) {
int h1 = seed;
// step through the CharSequence 2 chars at a time
for (int i = 1; i < input.length(); i += 2) {
int k1 = input.charAt(i - 1) | (input.charAt(i) << 16);
k1 = mixK1(k1);
h1 = mixH1(h1, k1);
}
// deal with any remaining characters
if ((input.length() & 1) == 1) {
int k1 = input.charAt(input.length() - 1);
k1 = mixK1(k1);
h1 ^= k1;
}
return fmix(h1, Chars.BYTES * input.length());
}
@Override
public HashCode hashString(CharSequence input, Charset charset) {
if (charset.equals(UTF_8)) {
int utf16Length = input.length();
int h1 = seed;
int i = 0;
int len = 0;
// This loop optimizes for pure ASCII.
while (i + 4 <= utf16Length) {
char c0 = input.charAt(i);
char c1 = input.charAt(i + 1);
char c2 = input.charAt(i + 2);
char c3 = input.charAt(i + 3);
if (c0 < 0x80 && c1 < 0x80 && c2 < 0x80 && c3 < 0x80) {
int k1 = c0 | (c1 << 8) | (c2 << 16) | (c3 << 24);
k1 = mixK1(k1);
h1 = mixH1(h1, k1);
i += 4;
len += 4;
} else {
break;
}
}
long buffer = 0;
int shift = 0;
for (; i < utf16Length; i++) {
char c = input.charAt(i);
if (c < 0x80) {
buffer |= (long) c << shift;
shift += 8;
len++;
} else if (c < 0x800) {
buffer |= charToTwoUtf8Bytes(c) << shift;
shift += 16;
len += 2;
} else if (c < Character.MIN_SURROGATE || c > Character.MAX_SURROGATE) {
buffer |= charToThreeUtf8Bytes(c) << shift;
shift += 24;
len += 3;
} else {
int codePoint = Character.codePointAt(input, i);
if (codePoint == c) {
// not a valid code point; let the JDK handle invalid Unicode
return hashBytes(input.toString().getBytes(charset));
}
i++;
buffer |= codePointToFourUtf8Bytes(codePoint) << shift;
if (supplementaryPlaneFix) { // bug compatibility: earlier versions did not have this add
shift += 32;
}
len += 4;
}
if (shift >= 32) {
int k1 = mixK1((int) buffer);
h1 = mixH1(h1, k1);
buffer = buffer >>> 32;
shift -= 32;
}
}
int k1 = mixK1((int) buffer);
h1 ^= k1;
return fmix(h1, len);
} else {
return hashBytes(input.toString().getBytes(charset));
}
}
@Override
public HashCode hashBytes(byte[] input, int off, int len) {
checkPositionIndexes(off, off + len, input.length);
int h1 = seed;
int i;
for (i = 0; i + CHUNK_SIZE <= len; i += CHUNK_SIZE) {
int k1 = mixK1(getIntLittleEndian(input, off + i));
h1 = mixH1(h1, k1);
}
int k1 = 0;
for (int shift = 0; i < len; i++, shift += 8) {
k1 ^= toUnsignedInt(input[off + i]) << shift;
}
h1 ^= mixK1(k1);
return fmix(h1, len);
}
private static int getIntLittleEndian(byte[] input, int offset) {
return Ints.fromBytes(input[offset + 3], input[offset + 2], input[offset + 1], input[offset]);
}
private static int mixK1(int k1) {
k1 *= C1;
k1 = Integer.rotateLeft(k1, 15);
k1 *= C2;
return k1;
}
private static int mixH1(int h1, int k1) {
h1 ^= k1;
h1 = Integer.rotateLeft(h1, 13);
h1 = h1 * 5 + 0xe6546b64;
return h1;
}
// Finalization mix - force all bits of a hash block to avalanche
private static HashCode fmix(int h1, int length) {
h1 ^= length;
h1 ^= h1 >>> 16;
h1 *= 0x85ebca6b;
h1 ^= h1 >>> 13;
h1 *= 0xc2b2ae35;
h1 ^= h1 >>> 16;
return HashCode.fromInt(h1);
}
private static final | Murmur3_32HashFunction |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/main/java/org/apache/camel/spring/xml/KeyManagersParametersFactoryBean.java | {
"start": 1315,
"end": 2170
} | class ____ extends AbstractKeyManagersParametersFactoryBean
implements FactoryBean<KeyManagersParameters>, ApplicationContextAware {
KeyStoreParametersFactoryBean keyStore;
@XmlTransient
private ApplicationContext applicationContext;
@Override
public KeyStoreParametersFactoryBean getKeyStore() {
return this.keyStore;
}
public void setKeyStore(KeyStoreParametersFactoryBean keyStore) {
this.keyStore = keyStore;
}
@Override
protected CamelContext getCamelContextWithId(String camelContextId) {
return CamelContextResolverHelper.getCamelContextWithId(applicationContext, camelContextId);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
| KeyManagersParametersFactoryBean |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/resilience/ConcurrencyLimitTests.java | {
"start": 8645,
"end": 9112
} | class ____ {
final AtomicInteger current = new AtomicInteger();
@ConcurrencyLimit(limitString = "${test.concurrency.limit}")
public void concurrentOperation() {
if (current.incrementAndGet() > 3) { // Assumes test.concurrency.limit=3
throw new IllegalStateException();
}
try {
Thread.sleep(10);
}
catch (InterruptedException ex) {
throw new IllegalStateException(ex);
}
current.decrementAndGet();
}
}
static | PlaceholderBean |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/job/JobVertexTaskManagersHandler.java | {
"start": 3469,
"end": 13540
} | class ____
extends AbstractAccessExecutionGraphHandler<
JobVertexTaskManagersInfo, JobVertexMessageParameters>
implements OnlyExecutionGraphJsonArchivist {
private MetricFetcher metricFetcher;
public JobVertexTaskManagersHandler(
GatewayRetriever<? extends RestfulGateway> leaderRetriever,
Duration timeout,
Map<String, String> responseHeaders,
MessageHeaders<EmptyRequestBody, JobVertexTaskManagersInfo, JobVertexMessageParameters>
messageHeaders,
ExecutionGraphCache executionGraphCache,
Executor executor,
MetricFetcher metricFetcher) {
super(
leaderRetriever,
timeout,
responseHeaders,
messageHeaders,
executionGraphCache,
executor);
this.metricFetcher = Preconditions.checkNotNull(metricFetcher);
}
@Override
protected JobVertexTaskManagersInfo handleRequest(
HandlerRequest<EmptyRequestBody> request, AccessExecutionGraph executionGraph)
throws RestHandlerException {
JobID jobID = request.getPathParameter(JobIDPathParameter.class);
JobVertexID jobVertexID = request.getPathParameter(JobVertexIdPathParameter.class);
AccessExecutionJobVertex jobVertex = executionGraph.getJobVertex(jobVertexID);
if (jobVertex == null) {
throw new NotFoundException(String.format("JobVertex %s not found", jobVertexID));
}
metricFetcher.update();
return createJobVertexTaskManagersInfo(
jobVertex, jobID, metricFetcher.getMetricStore().getJobs());
}
@Override
public Collection<ArchivedJson> archiveJsonWithPath(AccessExecutionGraph graph)
throws IOException {
Collection<? extends AccessExecutionJobVertex> vertices = graph.getAllVertices().values();
List<ArchivedJson> archive = new ArrayList<>(vertices.size());
for (AccessExecutionJobVertex task : vertices) {
ResponseBody json = createJobVertexTaskManagersInfo(task, graph.getJobID(), null);
String path =
getMessageHeaders()
.getTargetRestEndpointURL()
.replace(':' + JobIDPathParameter.KEY, graph.getJobID().toString())
.replace(
':' + JobVertexIdPathParameter.KEY,
task.getJobVertexId().toString());
archive.add(new ArchivedJson(path, json));
}
return archive;
}
private static JobVertexTaskManagersInfo createJobVertexTaskManagersInfo(
AccessExecutionJobVertex jobVertex,
JobID jobID,
@Nullable MetricStore.JobMetricStoreSnapshot jobMetrics) {
// Build a map that groups task executions by TaskManager
Map<TaskManagerLocation, List<AccessExecution>> taskManagerExecutions = new HashMap<>();
Set<AccessExecution> representativeExecutions = new HashSet<>();
for (AccessExecutionVertex vertex : jobVertex.getTaskVertices()) {
AccessExecution representativeAttempt = vertex.getCurrentExecutionAttempt();
representativeExecutions.add(representativeAttempt);
for (AccessExecution execution : vertex.getCurrentExecutions()) {
TaskManagerLocation location = execution.getAssignedResourceLocation();
List<AccessExecution> executions =
taskManagerExecutions.computeIfAbsent(
location, ignored -> new ArrayList<>());
executions.add(execution);
}
}
final long now = System.currentTimeMillis();
List<JobVertexTaskManagersInfo.TaskManagersInfo> taskManagersInfoList = new ArrayList<>(4);
for (Map.Entry<TaskManagerLocation, List<AccessExecution>> entry :
taskManagerExecutions.entrySet()) {
TaskManagerLocation location = entry.getKey();
// Port information is included in the host field for backward-compatibility
String host =
location == null
? "(unassigned)"
: location.getHostname() + ':' + location.dataPort();
String endpoint = location == null ? "(unassigned)" : location.getEndpoint();
String taskmanagerId =
location == null ? "(unassigned)" : location.getResourceID().toString();
List<AccessExecution> executions = entry.getValue();
List<IOMetricsInfo> ioMetricsInfos = new ArrayList<>();
List<Map<ExecutionState, Long>> status =
executions.stream()
.map(StatusDurationUtils::getExecutionStateDuration)
.collect(Collectors.toList());
// executionsPerState counts attempts of a subtask separately
int[] executionsPerState = new int[ExecutionState.values().length];
// tasksPerState counts only the representative attempts, and is used to aggregate the
// task manager state
int[] tasksPerState = new int[ExecutionState.values().length];
long startTime = Long.MAX_VALUE;
long endTime = 0;
boolean allFinished = true;
MutableIOMetrics counts = new MutableIOMetrics();
int representativeAttemptsCount = 0;
for (AccessExecution execution : executions) {
final ExecutionState state = execution.getState();
executionsPerState[state.ordinal()]++;
if (representativeExecutions.contains(execution)) {
tasksPerState[state.ordinal()]++;
representativeAttemptsCount++;
}
// take the earliest start time
long started = execution.getStateTimestamp(ExecutionState.DEPLOYING);
if (started > 0) {
startTime = Math.min(startTime, started);
}
allFinished &= state.isTerminal();
endTime = Math.max(endTime, execution.getStateTimestamp(state));
counts.addIOMetrics(
execution,
jobMetrics,
jobID.toString(),
jobVertex.getJobVertexId().toString());
MutableIOMetrics current = new MutableIOMetrics();
current.addIOMetrics(
execution,
jobMetrics,
jobID.toString(),
jobVertex.getJobVertexId().toString());
ioMetricsInfos.add(
new IOMetricsInfo(
current.getNumBytesIn(),
current.isNumBytesInComplete(),
current.getNumBytesOut(),
current.isNumBytesOutComplete(),
current.getNumRecordsIn(),
current.isNumRecordsInComplete(),
current.getNumRecordsOut(),
current.isNumRecordsOutComplete(),
current.getAccumulateBackPressuredTime(),
current.getAccumulateIdleTime(),
current.getAccumulateBusyTime()));
}
long duration;
if (startTime < Long.MAX_VALUE) {
if (allFinished) {
duration = endTime - startTime;
} else {
endTime = -1L;
duration = now - startTime;
}
} else {
startTime = -1L;
endTime = -1L;
duration = -1L;
}
// Safe when tasksPerState are all zero and representativeAttemptsCount is zero
ExecutionState jobVertexState =
ExecutionJobVertex.getAggregateJobVertexState(
tasksPerState, representativeAttemptsCount);
final IOMetricsInfo jobVertexMetrics =
new IOMetricsInfo(
counts.getNumBytesIn(),
counts.isNumBytesInComplete(),
counts.getNumBytesOut(),
counts.isNumBytesOutComplete(),
counts.getNumRecordsIn(),
counts.isNumRecordsInComplete(),
counts.getNumRecordsOut(),
counts.isNumRecordsOutComplete(),
counts.getAccumulateBackPressuredTime(),
counts.getAccumulateIdleTime(),
counts.getAccumulateBusyTime());
Map<ExecutionState, Integer> statusCounts =
CollectionUtil.newHashMapWithExpectedSize(ExecutionState.values().length);
for (ExecutionState state : ExecutionState.values()) {
statusCounts.put(state, executionsPerState[state.ordinal()]);
}
taskManagersInfoList.add(
new JobVertexTaskManagersInfo.TaskManagersInfo(
endpoint,
jobVertexState,
startTime,
endTime,
duration,
jobVertexMetrics,
statusCounts,
taskmanagerId,
AggregatedTaskDetailsInfo.create(ioMetricsInfos, status)));
}
return new JobVertexTaskManagersInfo(
jobVertex.getJobVertexId(), jobVertex.getName(), now, taskManagersInfoList);
}
}
| JobVertexTaskManagersHandler |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/jdk8/OptionalInt_Test.java | {
"start": 169,
"end": 590
} | class ____ extends TestCase {
public void test_optional() throws Exception {
Model model = new Model();
model.value = OptionalInt.empty();
String text = JSON.toJSONString(model);
Assert.assertEquals("{\"value\":null}", text);
Model model2 = JSON.parseObject(text, Model.class);
Assert.assertEquals(model2.value, model.value);
}
public static | OptionalInt_Test |
java | apache__flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/util/retryable/AsyncRetryStrategies.java | {
"start": 4308,
"end": 5748
} | class ____<OUT> {
private int maxAttempts;
private long backoffTimeMillis;
private Predicate<Collection<OUT>> resultPredicate;
private Predicate<Throwable> exceptionPredicate;
public FixedDelayRetryStrategyBuilder(int maxAttempts, long backoffTimeMillis) {
Preconditions.checkArgument(
maxAttempts > 0, "maxAttempts should be greater than zero.");
Preconditions.checkArgument(
backoffTimeMillis > 0, "backoffTimeMillis should be greater than zero.");
this.maxAttempts = maxAttempts;
this.backoffTimeMillis = backoffTimeMillis;
}
public FixedDelayRetryStrategyBuilder<OUT> ifResult(
@Nonnull Predicate<Collection<OUT>> resultRetryPredicate) {
this.resultPredicate = resultRetryPredicate;
return this;
}
public FixedDelayRetryStrategyBuilder<OUT> ifException(
@Nonnull Predicate<Throwable> exceptionRetryPredicate) {
this.exceptionPredicate = exceptionRetryPredicate;
return this;
}
public FixedDelayRetryStrategy<OUT> build() {
return new FixedDelayRetryStrategy<OUT>(
maxAttempts, backoffTimeMillis, resultPredicate, exceptionPredicate);
}
}
/** ExponentialBackoffDelayRetryStrategy. */
public static | FixedDelayRetryStrategyBuilder |
java | quarkusio__quarkus | core/deployment/src/test/java/io/quarkus/deployment/runnerjar/ApplicationManifestMutableJarTest.java | {
"start": 267,
"end": 5761
} | class ____ extends ApplicationManifestTestBase {
@Override
protected TsArtifact composeApplication() {
var acmeTransitive = TsArtifact.jar("acme-transitive");
var acmeCommon = TsArtifact.jar("acme-common")
.addDependency(acmeTransitive);
var acmeLib = TsArtifact.jar("acme-lib")
.addDependency(acmeCommon);
var otherLib = TsArtifact.jar("other-lib");
otherLib.addDependency(acmeCommon);
var myLib = TsArtifact.jar("my-lib");
myLib.addDependency(acmeCommon);
var myExt = new TsQuarkusExt("my-ext");
myExt.getRuntime().addDependency(myLib);
myExt.getDeployment().addDependency(otherLib);
return TsArtifact.jar("app")
.addManagedDependency(platformDescriptor())
.addManagedDependency(platformProperties())
.addDependency(acmeLib)
.addDependency(otherLib)
.addDependency(myExt);
}
@Override
protected Properties buildSystemProperties() {
var props = new Properties();
props.setProperty("quarkus.package.jar.type", "mutable-jar");
return props;
}
@BeforeEach
public void initExpectedComponents() {
expectMavenComponent(artifactCoords("app"), comp -> {
assertDistributionPath(comp, "app/quarkus-application.jar");
assertDependencies(comp,
artifactCoords("acme-lib"),
artifactCoords("other-lib"),
artifactCoords("my-ext"),
artifactCoords("my-ext-deployment"));
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectMavenComponent(artifactCoords("acme-lib"), comp -> {
assertDistributionPath(comp, "lib/main/io.quarkus.bootstrap.test.acme-lib-1.jar");
assertDependencies(comp, artifactCoords("acme-common"));
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectMavenComponent(artifactCoords("acme-common"), comp -> {
assertDistributionPath(comp, "lib/main/io.quarkus.bootstrap.test.acme-common-1.jar");
assertDependencies(comp, artifactCoords("acme-transitive"));
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectMavenComponent(artifactCoords("acme-transitive"), comp -> {
assertDistributionPath(comp, "lib/main/io.quarkus.bootstrap.test.acme-transitive-1.jar");
assertDependencies(comp);
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectMavenComponent(artifactCoords("other-lib"), comp -> {
assertDistributionPath(comp, "lib/main/io.quarkus.bootstrap.test.other-lib-1.jar");
assertDependencies(comp, artifactCoords("acme-common"));
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectMavenComponent(artifactCoords("my-lib"), comp -> {
assertDistributionPath(comp, "lib/main/io.quarkus.bootstrap.test.my-lib-1.jar");
assertDependencies(comp, artifactCoords("acme-common"));
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectMavenComponent(artifactCoords("my-ext"), comp -> {
assertDistributionPath(comp, "lib/main/io.quarkus.bootstrap.test.my-ext-1.jar");
assertDependencies(comp, artifactCoords("my-lib"));
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectFileComponent("quarkus-run.jar", comp -> {
assertDependencies(comp, artifactCoords("app"));
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectFileComponent("quarkus/generated-bytecode.jar", comp -> {
assertDependencies(comp);
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectFileComponent("quarkus/quarkus-application.dat", comp -> {
assertDependencies(comp);
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectFileComponent("quarkus-app-dependencies.txt", comp -> {
assertDependencies(comp);
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectFileComponent("quarkus/build-system.properties", comp -> {
assertDependencies(comp);
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectMavenComponent(artifactCoords("my-ext-deployment"), comp -> {
assertDistributionPath(comp, "lib/deployment/io.quarkus.bootstrap.test.my-ext-deployment-1.jar");
assertDependencyScope(comp, ApplicationComponent.SCOPE_DEVELOPMENT);
assertDependencies(comp,
artifactCoords("my-ext"),
artifactCoords("other-lib"));
});
expectFileComponent("lib/deployment/appmodel.dat", comp -> {
assertDependencies(comp);
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
expectFileComponent("lib/deployment/deployment-class-path.dat", comp -> {
assertDependencies(comp);
assertDependencyScope(comp, ApplicationComponent.SCOPE_RUNTIME);
});
}
}
| ApplicationManifestMutableJarTest |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/TestTrustedIdentityProvider.java | {
"start": 749,
"end": 1776
} | class ____ implements IdentityProvider<TrustedAuthenticationRequest> {
@Override
public Class<TrustedAuthenticationRequest> getRequestType() {
return TrustedAuthenticationRequest.class;
}
@Override
public Uni<SecurityIdentity> authenticate(TrustedAuthenticationRequest request,
AuthenticationRequestContext context) {
if (HttpSecurityUtils.getRoutingContextAttribute(request) == null) {
return Uni.createFrom().failure(new AuthenticationFailedException());
}
TestIdentityController.TestIdentity ident = TestIdentityController.identities.get(request.getPrincipal());
if (ident == null) {
return Uni.createFrom().optional(Optional.empty());
}
return Uni.createFrom().completionStage(CompletableFuture
.completedFuture(QuarkusSecurityIdentity.builder().setPrincipal(new QuarkusPrincipal(request.getPrincipal()))
.addRoles(ident.roles).build()));
}
}
| TestTrustedIdentityProvider |
java | spring-projects__spring-framework | spring-messaging/src/main/java/org/springframework/messaging/tcp/TcpConnection.java | {
"start": 990,
"end": 1832
} | interface ____<P> extends Closeable {
/**
* Send the given message.
* @param message the message
* @return a CompletableFuture that can be used to determine when and if the
* message was successfully sent
* @since 6.0
*/
CompletableFuture<Void> sendAsync(Message<P> message);
/**
* Register a task to invoke after a period of read inactivity.
* @param runnable the task to invoke
* @param duration the amount of inactive time in milliseconds
*/
void onReadInactivity(Runnable runnable, long duration);
/**
* Register a task to invoke after a period of write inactivity.
* @param runnable the task to invoke
* @param duration the amount of inactive time in milliseconds
*/
void onWriteInactivity(Runnable runnable, long duration);
/**
* Close the connection.
*/
@Override
void close();
}
| TcpConnection |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/LogsPurgeable.java | {
"start": 1019,
"end": 2179
} | interface ____ {
/**
* Remove all edit logs with transaction IDs lower than the given transaction
* ID.
*
* @param minTxIdToKeep the lowest transaction ID that should be retained
* @throws IOException in the event of error
*/
public void purgeLogsOlderThan(long minTxIdToKeep) throws IOException;
/**
* Get a list of edit log input streams. The list will start with the
* stream that contains fromTxnId, and continue until the end of the journal
* being managed.
*
* @param fromTxId the first transaction id we want to read
* @param inProgressOk whether or not in-progress streams should be returned
* @param onlyDurableTxns whether or not streams should be bounded by durable
* TxId. A durable TxId is the committed txid in QJM
* or the largest txid written into file in FJM
* @throws IOException if the underlying storage has an error or is otherwise
* inaccessible
*/
void selectInputStreams(Collection<EditLogInputStream> streams,
long fromTxId, boolean inProgressOk, boolean onlyDurableTxns)
throws IOException;
}
| LogsPurgeable |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/single/SingleSubscribeOnTest.java | {
"start": 1140,
"end": 2079
} | class ____ extends RxJavaTest {
@Test
public void normal() {
List<Throwable> list = TestHelper.trackPluginErrors();
try {
TestScheduler scheduler = new TestScheduler();
TestObserver<Integer> to = Single.just(1)
.subscribeOn(scheduler)
.test();
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
to.assertResult(1);
assertTrue(list.toString(), list.isEmpty());
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void dispose() {
TestHelper.checkDisposed(PublishSubject.create().singleOrError().subscribeOn(new TestScheduler()));
}
@Test
public void error() {
Single.error(new TestException())
.subscribeOn(Schedulers.single())
.test()
.awaitDone(5, TimeUnit.SECONDS)
.assertFailure(TestException.class);
}
}
| SingleSubscribeOnTest |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/common/operators/OrderingTest.java | {
"start": 950,
"end": 1859
} | class ____ {
@Test
void testNewOrdering() {
Ordering ordering = new Ordering();
// add a field
ordering.appendOrdering(3, Integer.class, Order.ASCENDING);
assertThat(ordering.getNumberOfFields()).isOne();
// add a second field
ordering.appendOrdering(1, Long.class, Order.DESCENDING);
assertThat(ordering.getNumberOfFields()).isEqualTo(2);
// duplicate field index does not change Ordering
ordering.appendOrdering(1, String.class, Order.ASCENDING);
assertThat(ordering.getNumberOfFields()).isEqualTo(2);
// verify field positions, types, and orderings
assertThat(ordering.getFieldPositions()).containsExactly(3, 1);
assertThat(ordering.getTypes()).containsExactly(Integer.class, Long.class);
assertThat(ordering.getFieldSortDirections()).containsExactly(true, false);
}
}
| OrderingTest |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/util/LoaderUtil.java | {
"start": 1914,
"end": 5255
} | class ____ problem where LoaderUtil
// wants to use PropertiesUtil, but then PropertiesUtil wants to use LoaderUtil.
private static Boolean ignoreTCCL;
static final RuntimePermission GET_CLASS_LOADER = new RuntimePermission("getClassLoader");
static final LazyBoolean GET_CLASS_LOADER_DISABLED = new LazyBoolean(() -> {
if (System.getSecurityManager() == null) {
return false;
}
try {
AccessController.checkPermission(GET_CLASS_LOADER);
// seems like we'll be ok
return false;
} catch (final SecurityException ignored) {
try {
// let's see if we can obtain that permission
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
AccessController.checkPermission(GET_CLASS_LOADER);
return null;
});
return false;
} catch (final SecurityException ignore) {
// no chance
return true;
}
}
});
private static final PrivilegedAction<ClassLoader> TCCL_GETTER = new ThreadContextClassLoaderGetter();
private LoaderUtil() {}
/**
* Returns the ClassLoader to use.
*
* @return the ClassLoader.
* @since 2.22.0
*/
public static ClassLoader getClassLoader() {
return getClassLoader(LoaderUtil.class, null);
}
/**
* @since 2.22.0
*/
// TODO: this method could use some explanation
public static ClassLoader getClassLoader(final Class<?> class1, final Class<?> class2) {
PrivilegedAction<ClassLoader> action = () -> {
final ClassLoader loader1 = class1 == null ? null : class1.getClassLoader();
final ClassLoader loader2 = class2 == null ? null : class2.getClassLoader();
final ClassLoader referenceLoader = GET_CLASS_LOADER_DISABLED.getAsBoolean()
? getThisClassLoader()
: Thread.currentThread().getContextClassLoader();
if (isChild(referenceLoader, loader1)) {
return isChild(referenceLoader, loader2) ? referenceLoader : loader2;
}
return isChild(loader1, loader2) ? loader1 : loader2;
};
return runPrivileged(action);
}
/**
* Determines if one ClassLoader is a child of another ClassLoader. Note that a {@code null} ClassLoader is
* interpreted as the system ClassLoader as per convention.
*
* @param loader1 the ClassLoader to check for childhood.
* @param loader2 the ClassLoader to check for parenthood.
* @return {@code true} if the first ClassLoader is a strict descendant of the second ClassLoader.
*/
private static boolean isChild(final ClassLoader loader1, final ClassLoader loader2) {
if (loader1 != null && loader2 != null) {
ClassLoader parent = loader1.getParent();
while (parent != null && parent != loader2) {
parent = parent.getParent();
}
// once parent is null, we're at the system CL, which would indicate they have separate ancestry
return parent != null;
}
return loader1 != null;
}
/**
* Looks up the ClassLoader for this current thread. If this | loading |
java | apache__camel | components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpProducerQueryParamTest.java | {
"start": 1121,
"end": 4031
} | class ____ extends BaseNettyTest {
private final String url = "netty-http:http://localhost:" + getPort() + "/cheese?urlDecodeHeaders=true";
@Test
public void testQueryParameters() {
Exchange exchange = template.request(url + ""e=Camel%20rocks", null);
assertNotNull(exchange);
String body = exchange.getMessage().getBody(String.class);
Map<?, ?> headers = exchange.getMessage().getHeaders();
assertEquals("Bye World", body);
assertEquals("Carlsberg", headers.get("beer"));
}
@Test
public void testQueryParametersWithHeader() {
Exchange exchange
= template.request(url, exchange1 -> exchange1.getIn().setHeader(Exchange.HTTP_QUERY, "quote=Camel rocks"));
assertNotNull(exchange);
String body = exchange.getMessage().getBody(String.class);
Map<?, ?> headers = exchange.getMessage().getHeaders();
assertEquals("Bye World", body);
assertEquals("Carlsberg", headers.get("beer"));
}
@Test
public void testQueryParametersWithDynamicPath() {
// remove "/cheese" from the endpoint URL and place it in the Exchange.HTTP_PATH header
Exchange exchange = template.request(url.replace("/cheese", ""), exchange1 -> {
exchange1.getIn().setHeader(Exchange.HTTP_PATH, "/cheese");
exchange1.getIn().setHeader(Exchange.HTTP_QUERY, "quote=Camel rocks");
});
assertNotNull(exchange);
String body = exchange.getMessage().getBody(String.class);
Map<?, ?> headers = exchange.getMessage().getHeaders();
assertEquals("Bye World", body);
assertEquals("Carlsberg", headers.get("beer"));
}
@Test
public void testQueryParametersInUriWithDynamicPath() {
// remove "/cheese" from the endpoint URL and place it in the Exchange.HTTP_PATH header
Exchange exchange = template.request((url + ""e=Camel%20rocks").replace("/cheese", ""),
exchange1 -> exchange1.getIn().setHeader(Exchange.HTTP_PATH, "/cheese"));
assertNotNull(exchange);
String body = exchange.getMessage().getBody(String.class);
Map<?, ?> headers = exchange.getMessage().getHeaders();
assertEquals("Bye World", body);
assertEquals("Carlsberg", headers.get("beer"));
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from(url).process(exchange -> {
String quote = exchange.getIn().getHeader("quote", String.class);
assertEquals("Camel rocks", quote);
exchange.getMessage().setBody("Bye World");
exchange.getMessage().setHeader("beer", "Carlsberg");
});
}
};
}
}
| NettyHttpProducerQueryParamTest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jToolsEndpointBuilderFactory.java | {
"start": 4867,
"end": 13209
} | interface ____
extends
EndpointConsumerBuilder {
default LangChain4jToolsEndpointConsumerBuilder basic() {
return (LangChain4jToolsEndpointConsumerBuilder) this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jToolsEndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jToolsEndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Tool's Camel Parameters, programmatically define Tool description and
* parameters.
*
* The option is a:
* <code>org.apache.camel.component.langchain4j.tools.spec.CamelSimpleToolParameter</code> type.
*
* Group: consumer (advanced)
*
* @param camelToolParameter the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jToolsEndpointConsumerBuilder camelToolParameter(org.apache.camel.component.langchain4j.tools.spec.CamelSimpleToolParameter camelToolParameter) {
doSetProperty("camelToolParameter", camelToolParameter);
return this;
}
/**
* Tool's Camel Parameters, programmatically define Tool description and
* parameters.
*
* The option will be converted to a
* <code>org.apache.camel.component.langchain4j.tools.spec.CamelSimpleToolParameter</code> type.
*
* Group: consumer (advanced)
*
* @param camelToolParameter the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jToolsEndpointConsumerBuilder camelToolParameter(String camelToolParameter) {
doSetProperty("camelToolParameter", camelToolParameter);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jToolsEndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jToolsEndpointConsumerBuilder exceptionHandler(String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jToolsEndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jToolsEndpointConsumerBuilder exchangePattern(String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Chat Model of type dev.langchain4j.model.chat.ChatModel.
*
* The option is a: <code>dev.langchain4j.model.chat.ChatModel</code>
* type.
*
* Group: advanced
*
* @param chatModel the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jToolsEndpointConsumerBuilder chatModel(dev.langchain4j.model.chat.ChatModel chatModel) {
doSetProperty("chatModel", chatModel);
return this;
}
/**
* Chat Model of type dev.langchain4j.model.chat.ChatModel.
*
* The option will be converted to a
* <code>dev.langchain4j.model.chat.ChatModel</code> type.
*
* Group: advanced
*
* @param chatModel the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jToolsEndpointConsumerBuilder chatModel(String chatModel) {
doSetProperty("chatModel", chatModel);
return this;
}
}
/**
* Builder for endpoint producers for the LangChain4j Tools component.
*/
public | AdvancedLangChain4jToolsEndpointConsumerBuilder |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/predicate/operator/comparison/EqualsNanosMillisEvaluator.java | {
"start": 1197,
"end": 5015
} | class ____ implements EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(EqualsNanosMillisEvaluator.class);
private final Source source;
private final EvalOperator.ExpressionEvaluator lhs;
private final EvalOperator.ExpressionEvaluator rhs;
private final DriverContext driverContext;
private Warnings warnings;
public EqualsNanosMillisEvaluator(Source source, EvalOperator.ExpressionEvaluator lhs,
EvalOperator.ExpressionEvaluator rhs, DriverContext driverContext) {
this.source = source;
this.lhs = lhs;
this.rhs = rhs;
this.driverContext = driverContext;
}
@Override
public Block eval(Page page) {
try (LongBlock lhsBlock = (LongBlock) lhs.eval(page)) {
try (LongBlock rhsBlock = (LongBlock) rhs.eval(page)) {
LongVector lhsVector = lhsBlock.asVector();
if (lhsVector == null) {
return eval(page.getPositionCount(), lhsBlock, rhsBlock);
}
LongVector rhsVector = rhsBlock.asVector();
if (rhsVector == null) {
return eval(page.getPositionCount(), lhsBlock, rhsBlock);
}
return eval(page.getPositionCount(), lhsVector, rhsVector).asBlock();
}
}
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += lhs.baseRamBytesUsed();
baseRamBytesUsed += rhs.baseRamBytesUsed();
return baseRamBytesUsed;
}
public BooleanBlock eval(int positionCount, LongBlock lhsBlock, LongBlock rhsBlock) {
try(BooleanBlock.Builder result = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
switch (lhsBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
switch (rhsBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
long lhs = lhsBlock.getLong(lhsBlock.getFirstValueIndex(p));
long rhs = rhsBlock.getLong(rhsBlock.getFirstValueIndex(p));
result.appendBoolean(Equals.processNanosMillis(lhs, rhs));
}
return result.build();
}
}
public BooleanVector eval(int positionCount, LongVector lhsVector, LongVector rhsVector) {
try(BooleanVector.FixedBuilder result = driverContext.blockFactory().newBooleanVectorFixedBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
long lhs = lhsVector.getLong(p);
long rhs = rhsVector.getLong(p);
result.appendBoolean(p, Equals.processNanosMillis(lhs, rhs));
}
return result.build();
}
}
@Override
public String toString() {
return "EqualsNanosMillisEvaluator[" + "lhs=" + lhs + ", rhs=" + rhs + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(lhs, rhs);
}
private Warnings warnings() {
if (warnings == null) {
this.warnings = Warnings.createWarnings(
driverContext.warningsMode(),
source.source().getLineNumber(),
source.source().getColumnNumber(),
source.text()
);
}
return warnings;
}
static | EqualsNanosMillisEvaluator |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/query/support/NestedScope.java | {
"start": 773,
"end": 1599
} | class ____ {
private final Deque<NestedObjectMapper> levelStack = new LinkedList<>();
/**
* @return For the current nested level returns the object mapper that belongs to that
*/
public NestedObjectMapper getObjectMapper() {
return levelStack.peek();
}
/**
* Sets the new current nested level and pushes old current nested level down the stack returns that level.
*/
public NestedObjectMapper nextLevel(NestedObjectMapper level) {
NestedObjectMapper previous = levelStack.peek();
levelStack.push(level);
return previous;
}
/**
* Sets the previous nested level as current nested level and removes and returns the current nested level.
*/
public ObjectMapper previousLevel() {
return levelStack.pop();
}
}
| NestedScope |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/eventbus/impl/DeliveryContextImpl.java | {
"start": 681,
"end": 2276
} | class ____<T> implements DeliveryContext<T> {
private static final AtomicIntegerFieldUpdater<DeliveryContextImpl> UPDATER = AtomicIntegerFieldUpdater.newUpdater(DeliveryContextImpl.class, "interceptorIdx");
private final MessageImpl<?, T> message;
private final ContextInternal context;
private final Object body;
private final Runnable dispatch;
private final Handler<DeliveryContext<?>>[] interceptors;
private volatile int interceptorIdx;
protected DeliveryContextImpl(MessageImpl<?, T> message, Handler<DeliveryContext<?>>[] interceptors,
ContextInternal context, Object body, Runnable dispatch) {
this.message = message;
this.interceptors = interceptors;
this.context = context;
this.interceptorIdx = 0;
this.body = body;
this.dispatch = dispatch;
}
@Override
public Message<T> message() {
return message;
}
@Override
public boolean send() {
return message.isSend();
}
@Override
public Object body() {
return body;
}
@Override
public void next() {
int idx = UPDATER.getAndIncrement(this);
if (idx < interceptors.length) {
Handler<DeliveryContext<?>> interceptor = interceptors[idx];
if (context.inThread()) {
context.dispatch(this, interceptor);
} else {
try {
interceptor.handle(this);
} catch (Throwable t) {
context.reportException(t);
}
}
} else if (idx == interceptors.length) {
dispatch.run();
} else {
throw new IllegalStateException();
}
}
}
| DeliveryContextImpl |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/UnusedTypeStrategy.java | {
"start": 1691,
"end": 2073
} | class ____ implements TypeStrategy {
@Override
public Optional<DataType> inferType(CallContext callContext) {
return Optional.empty();
}
@Override
public boolean equals(Object o) {
return o instanceof UnusedTypeStrategy;
}
@Override
public int hashCode() {
return UnusedTypeStrategy.class.hashCode();
}
}
| UnusedTypeStrategy |
java | quarkusio__quarkus | extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/formatmapper/FormatMapperBehaviorTest.java | {
"start": 409,
"end": 1427
} | class ____ {
@RegisterExtension
static QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(MyJsonEntity.class, MyXmlEntity.class)
.addClasses(SchemaUtil.class, SmokeTestUtils.class))
.withConfigurationResource("application.properties")
.overrideConfigKey("quarkus.hibernate-orm.mapping.format.global", "ignore");
@Inject
SessionFactory sessionFactory;
@Test
void smoke() {
// We really just care ot see if the SF is built successfully here or not;
assertThat(SchemaUtil.getColumnNames(sessionFactory, MyJsonEntity.class))
.contains("properties", "amount1", "amount2")
.doesNotContain("amountDifference");
assertThat(SchemaUtil.getColumnNames(sessionFactory, MyXmlEntity.class))
.contains("properties", "amount1", "amount2")
.doesNotContain("amountDifference");
}
}
| FormatMapperBehaviorTest |
java | apache__spark | examples/src/main/java/org/apache/spark/examples/mllib/JavaCorrelationsExample.java | {
"start": 1270,
"end": 2715
} | class ____ {
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaCorrelationsExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
// $example on$
JavaDoubleRDD seriesX = jsc.parallelizeDoubles(
Arrays.asList(1.0, 2.0, 3.0, 3.0, 5.0)); // a series
// must have the same number of partitions and cardinality as seriesX
JavaDoubleRDD seriesY = jsc.parallelizeDoubles(
Arrays.asList(11.0, 22.0, 33.0, 33.0, 555.0));
// compute the correlation using Pearson's method. Enter "spearman" for Spearman's method.
// If a method is not specified, Pearson's method will be used by default.
double correlation = Statistics.corr(seriesX.srdd(), seriesY.srdd(), "pearson");
System.out.println("Correlation is: " + correlation);
// note that each Vector is a row and not a column
JavaRDD<Vector> data = jsc.parallelize(
Arrays.asList(
Vectors.dense(1.0, 10.0, 100.0),
Vectors.dense(2.0, 20.0, 200.0),
Vectors.dense(5.0, 33.0, 366.0)
)
);
// calculate the correlation matrix using Pearson's method.
// Use "spearman" for Spearman's method.
// If a method is not specified, Pearson's method will be used by default.
Matrix correlMatrix = Statistics.corr(data.rdd(), "pearson");
System.out.println(correlMatrix.toString());
// $example off$
jsc.stop();
}
}
| JavaCorrelationsExample |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/ExecutionSlotAssignment.java | {
"start": 1199,
"end": 1837
} | class ____ {
private final ExecutionAttemptID executionAttemptId;
private final CompletableFuture<LogicalSlot> logicalSlotFuture;
ExecutionSlotAssignment(
ExecutionAttemptID executionAttemptId,
CompletableFuture<LogicalSlot> logicalSlotFuture) {
this.executionAttemptId = checkNotNull(executionAttemptId);
this.logicalSlotFuture = checkNotNull(logicalSlotFuture);
}
ExecutionAttemptID getExecutionAttemptId() {
return executionAttemptId;
}
CompletableFuture<LogicalSlot> getLogicalSlotFuture() {
return logicalSlotFuture;
}
}
| ExecutionSlotAssignment |
java | google__guice | extensions/assistedinject/test/com/google/inject/assistedinject/FactoryProvider2Test.java | {
"start": 30717,
"end": 31479
} | class ____ implements Car {
@Inject
@Assisted("paint")
Color paint;
@Inject
@Assisted("fabric")
Color fabric;
}
@Test
public void testDistinctKeys() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(TwoToneCarFactory.class)
.toProvider(FactoryProvider.newFactory(TwoToneCarFactory.class, Maxima.class));
}
});
TwoToneCarFactory factory = injector.getInstance(TwoToneCarFactory.class);
Maxima maxima = (Maxima) factory.create(Color.BLACK, Color.GRAY);
assertSame(Color.BLACK, maxima.paint);
assertSame(Color.GRAY, maxima.fabric);
}
| Maxima |
java | google__dagger | hilt-android/main/java/dagger/hilt/android/EarlyEntryPoints.java | {
"start": 1421,
"end": 1534
} | interface ____ is given.
*
* @param applicationContext The application context.
* @param entryPoint The | that |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/placement/TestPlacementFactory.java | {
"start": 1637,
"end": 2165
} | class ____.
* Relies on the {@link DefaultPlacementRule} of the FS.
*/
@Test
public void testGetExistRuleText() {
final String exists = DefaultPlacementRule.class.getCanonicalName();
PlacementRule rule = null;
try {
rule = PlacementFactory.getPlacementRule(exists, null);
} catch (ClassNotFoundException cnfe) {
fail("Class should have been found");
}
assertNotNull(rule, "Rule object is null");
assertEquals(rule.getName(), exists, "Names not equal");
}
/**
* Existing | name |
java | quarkusio__quarkus | devtools/cli-common/src/main/java/io/quarkus/cli/common/build/GradleRunner.java | {
"start": 1331,
"end": 11605
} | class ____ implements BuildSystemRunner {
public static final String[] windowsWrapper = { "gradlew.cmd", "gradlew.bat" };
public static final String otherWrapper = "gradlew";
final OutputOptionMixin output;
final RegistryClientMixin registryClient;
final Path projectRoot;
final BuildTool buildTool;
final PropertiesOptions propertiesOptions;
public GradleRunner(OutputOptionMixin output, PropertiesOptions propertiesOptions, RegistryClientMixin registryClient,
Path projectRoot, BuildTool buildTool) {
this.output = output;
this.projectRoot = projectRoot;
this.buildTool = buildTool;
this.propertiesOptions = propertiesOptions;
this.registryClient = registryClient;
verifyBuildFile();
}
@Override
public File getWrapper() {
return ExecuteUtil.findWrapper(projectRoot, windowsWrapper, otherWrapper);
}
@Override
public File getExecutable() {
return ExecuteUtil.findExecutable("gradle",
"Unable to find the gradle executable, is it in your path?",
output);
}
@Override
public Path getProjectRoot() {
return projectRoot;
}
@Override
public OutputOptionMixin getOutput() {
return output;
}
@Override
public BuildTool getBuildTool() {
return buildTool;
}
@Override
public Integer listExtensionCategories(RunModeOption runMode, CategoryListFormatOptions format) {
ArrayDeque<String> args = new ArrayDeque<>();
setGradleProperties(args, runMode.isBatchMode());
args.add("listCategories");
args.add("--fromCli");
args.add("--format=" + format.getFormatString());
return run(prependExecutable(args));
}
@Override
public Integer listExtensions(RunModeOption runMode, ListFormatOptions format, boolean installable, String searchPattern,
String category) {
ArrayDeque<String> args = new ArrayDeque<>();
setGradleProperties(args, runMode.isBatchMode());
args.add("listExtensions");
args.add("--fromCli");
args.add("--format=" + format.getFormatString());
if (category != null && !category.isBlank()) {
args.add("--category=" + category);
}
if (!installable) {
args.add("--installed");
}
if (searchPattern != null) {
args.add("--searchPattern=" + searchPattern);
}
return run(prependExecutable(args));
}
@Override
public Integer addExtension(RunModeOption runMode, Set<String> extensions) {
ArrayDeque<String> args = new ArrayDeque<>();
setGradleProperties(args, runMode.isBatchMode());
args.add("addExtension");
String param = "--extensions=" + String.join(",", extensions);
args.add(param);
return run(prependExecutable(args));
}
@Override
public Integer removeExtension(RunModeOption runMode, Set<String> extensions) {
ArrayDeque<String> args = new ArrayDeque<>();
setGradleProperties(args, runMode.isBatchMode());
args.add("removeExtension");
String param = "--extensions=" + String.join(",", extensions);
args.add(param);
return run(prependExecutable(args));
}
@Override
public Integer projectInfo(boolean perModule) {
ArrayDeque<String> args = new ArrayDeque<>();
args.add("quarkusInfo");
if (perModule) {
args.add("--per-module");
}
return run(prependExecutable(args));
}
@Override
public Integer updateProject(TargetQuarkusVersionGroup targetQuarkusVersion, RewriteGroup rewrite)
throws Exception {
final ExtensionCatalog extensionCatalog = ToolsUtils.resolvePlatformDescriptorDirectly(
ToolsConstants.QUARKUS_CORE_GROUP_ID, null,
VersionHelper.clientVersion(),
QuarkusProjectHelper.artifactResolver(), MessageWriter.info());
final Properties props = ToolsUtils.readQuarkusProperties(extensionCatalog);
ArrayDeque<String> args = new ArrayDeque<>();
args.add("-PquarkusPluginVersion=" + ToolsUtils.getGradlePluginVersion(props));
args.add("--console");
args.add("plain");
args.add("--no-daemon");
args.add("--stacktrace");
args.add("quarkusUpdate");
if (!StringUtil.isNullOrEmpty(targetQuarkusVersion.platformVersion)) {
args.add("--platformVersion");
args.add(targetQuarkusVersion.platformVersion);
}
if (!StringUtil.isNullOrEmpty(targetQuarkusVersion.streamId)) {
args.add("--stream");
args.add(targetQuarkusVersion.streamId);
}
if (rewrite.pluginVersion != null) {
args.add("--rewritePluginVersion=" + rewrite.pluginVersion);
}
if (rewrite.quarkusUpdateRecipes != null) {
args.add("--quarkusUpdateRecipes=" + rewrite.quarkusUpdateRecipes);
}
if (rewrite.additionalUpdateRecipes != null) {
args.add("--additionalUpdateRecipes=" + rewrite.additionalUpdateRecipes);
}
if (rewrite.run != null) {
if (rewrite.run.yes) {
args.add("--rewrite");
}
if (rewrite.run.no) {
args.add("--rewrite=false");
}
if (rewrite.run.dryRun) {
args.add("--rewriteDryRun");
}
}
return run(prependExecutable(args));
}
@Override
public BuildCommandArgs prepareBuild(BuildOptions buildOptions, RunModeOption runMode, List<String> params) {
return prepareAction("build", buildOptions, runMode, params);
}
@Override
public BuildCommandArgs prepareAction(String action, BuildOptions buildOptions, RunModeOption runMode,
List<String> params) {
ArrayDeque<String> args = new ArrayDeque<>();
setGradleProperties(args, runMode.isBatchMode());
if (buildOptions.clean) {
args.add("clean");
}
args.add(action);
if (buildOptions.buildNative) {
args.add("-Dquarkus.native.enabled=true");
args.add("-Dquarkus.package.jar.enabled=false");
}
if (buildOptions.skipTests()) {
setSkipTests(args);
}
if (buildOptions.offline) {
args.add("--offline");
}
// Add any other unmatched arguments
args.addAll(params);
return prependExecutable(args);
}
@Override
public BuildCommandArgs prepareTest(BuildOptions buildOptions, RunModeOption runMode, List<String> params, String filter) {
if (filter != null) {
params.add("--tests " + filter);
}
return prepareAction("test", buildOptions, runMode, params);
}
@Override
public List<Supplier<BuildCommandArgs>> prepareDevTestMode(boolean devMode, DevOptions commonOptions,
DebugOptions debugOptions, List<String> params) {
ArrayDeque<String> args = new ArrayDeque<>();
List<String> jvmArgs = new ArrayList<>();
setGradleProperties(args, commonOptions.isBatchMode());
if (commonOptions.clean) {
args.add("clean");
}
args.add(devMode ? "quarkusDev" : "quarkusTest");
if (commonOptions.offline) {
args.add("--offline");
}
debugOptions.addDebugArguments(args, jvmArgs);
propertiesOptions.flattenJvmArgs(jvmArgs, args);
// Add any other unmatched arguments using quarkus.args
paramsToQuarkusArgs(params, args);
try {
Path outputFile = Files.createTempFile("quarkus-dev", ".txt");
if (devMode) {
args.add("-Dio.quarkus.devmode-args=" + outputFile.toAbsolutePath());
}
BuildCommandArgs buildCommandArgs = prependExecutable(args);
return Arrays.asList(() -> buildCommandArgs, () -> {
try {
BuildCommandArgs cmd = new BuildCommandArgs();
cmd.arguments = Files.readAllLines(outputFile).stream().filter(s -> !s.isBlank()).toArray(String[]::new);
cmd.targetDirectory = buildCommandArgs.targetDirectory;
return cmd;
} catch (IOException e) {
throw new RuntimeException(e);
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
void setSkipTests(ArrayDeque<String> args) {
args.add("-x");
args.add("test");
}
void setGradleProperties(ArrayDeque<String> args, boolean batchMode) {
if (output.isShowErrors()) {
args.add("--full-stacktrace");
}
// batch mode typically disables ansi/color output
if (batchMode) {
args.add("--console=plain");
} else if (output.isAnsiEnabled()) {
args.add("--console=rich");
}
if (output.isCliTest()) {
// Make sure we stay where we should
args.add("--project-dir=" + projectRoot.toAbsolutePath());
}
args.add(registryClient.getRegistryClientProperty());
final String configFile = registryClient.getConfigArg() == null
? System.getProperty(RegistriesConfigLocator.CONFIG_FILE_PATH_PROPERTY)
: registryClient.getConfigArg();
if (configFile != null) {
args.add("-D" + RegistriesConfigLocator.CONFIG_FILE_PATH_PROPERTY + "=" + configFile);
}
// add any other discovered properties
args.addAll(flattenMappedProperties(propertiesOptions.properties));
}
void verifyBuildFile() {
for (String buildFileName : buildTool.getBuildFiles()) {
File buildFile = projectRoot.resolve(buildFileName).toFile();
if (buildFile.exists()) {
return;
}
}
throw new IllegalStateException("Was not able to find a build file in: " + projectRoot
+ " based on the following list: " + String.join(",", buildTool.getBuildFiles()));
}
}
| GradleRunner |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/cglib/core/VisibilityPredicate.java | {
"start": 823,
"end": 2106
} | class ____ implements Predicate {
private boolean protectedOk;
private String pkg;
private boolean samePackageOk;
public VisibilityPredicate(Class source, boolean protectedOk) {
this.protectedOk = protectedOk;
// same package is not ok for the bootstrap loaded classes. In all other cases we are
// generating classes in the same classloader
this.samePackageOk = source.getClassLoader() != null;
pkg = TypeUtils.getPackageName(Type.getType(source));
}
@Override
public boolean evaluate(Object arg) {
Member member = (Member)arg;
int mod = member.getModifiers();
if (Modifier.isPrivate(mod)) {
return false;
} else if (Modifier.isPublic(mod)) {
return true;
} else if (Modifier.isProtected(mod) && protectedOk) {
// protected is fine if 'protectedOk' is true (for subclasses)
return true;
} else {
// protected/package private if the member is in the same package as the source class
// and we are generating into the same classloader.
return samePackageOk
&& pkg.equals(TypeUtils.getPackageName(Type.getType(member.getDeclaringClass())));
}
}
}
| VisibilityPredicate |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_rendong.java | {
"start": 250,
"end": 925
} | class ____ extends TestCase {
public void test_0() throws Exception {
String text = "{\"BX-20110613-1739\":{\"repairNum\":\"BX-20110613-1739\",\"set\":[{\"employNum\":\"a1027\",\"isConfirm\":false,\"isReceive\":false,\"state\":11}]},\"BX-20110613-1749\":{\"repairNum\":\"BX-20110613-1749\",\"set\":[{\"employNum\":\"a1027\",\"isConfirm\":false,\"isReceive\":true,\"state\":1}]}}";
Map<String, TaskMobileStatusBean> map = JSON.parseObject(text,
new TypeReference<Map<String, TaskMobileStatusBean>>() {
});
Assert.assertEquals(2, map.size());
// System.out.println(JSON.toJSONString(map,
// SerializerFeature.PrettyFormat));
}
public static | Bug_for_rendong |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/Hamlet.java | {
"start": 193576,
"end": 204661
} | class ____<T extends __> extends EImp<T> implements HamletSpec.DT {
public DT(String name, T parent, EnumSet<EOpt> opts) {
super(name, parent, opts);
}
@Override
public DT<T> $id(String value) {
addAttr("id", value);
return this;
}
@Override
public DT<T> $class(String value) {
addAttr("class", value);
return this;
}
@Override
public DT<T> $title(String value) {
addAttr("title", value);
return this;
}
@Override
public DT<T> $style(String value) {
addAttr("style", value);
return this;
}
@Override
public DT<T> $lang(String value) {
addAttr("lang", value);
return this;
}
@Override
public DT<T> $dir(Dir value) {
addAttr("dir", value);
return this;
}
@Override
public DT<T> $onclick(String value) {
addAttr("onclick", value);
return this;
}
@Override
public DT<T> $ondblclick(String value) {
addAttr("ondblclick", value);
return this;
}
@Override
public DT<T> $onmousedown(String value) {
addAttr("onmousedown", value);
return this;
}
@Override
public DT<T> $onmouseup(String value) {
addAttr("onmouseup", value);
return this;
}
@Override
public DT<T> $onmouseover(String value) {
addAttr("onmouseover", value);
return this;
}
@Override
public DT<T> $onmousemove(String value) {
addAttr("onmousemove", value);
return this;
}
@Override
public DT<T> $onmouseout(String value) {
addAttr("onmouseout", value);
return this;
}
@Override
public DT<T> $onkeypress(String value) {
addAttr("onkeypress", value);
return this;
}
@Override
public DT<T> $onkeydown(String value) {
addAttr("onkeydown", value);
return this;
}
@Override
public DT<T> $onkeyup(String value) {
addAttr("onkeyup", value);
return this;
}
@Override
public DT<T> __(Object... lines) {
_p(true, lines);
return this;
}
@Override
public DT<T> _r(Object... lines) {
_p(false, lines);
return this;
}
@Override
public B<DT<T>> b() {
closeAttrs();
return b_(this, true);
}
@Override
public DT<T> b(String cdata) {
return b().__(cdata).__();
}
@Override
public DT<T> b(String selector, String cdata) {
return setSelector(b(), selector).__(cdata).__();
}
@Override
public I<DT<T>> i() {
closeAttrs();
return i_(this, true);
}
@Override
public DT<T> i(String cdata) {
return i().__(cdata).__();
}
@Override
public DT<T> i(String selector, String cdata) {
return setSelector(i(), selector).__(cdata).__();
}
@Override
public SMALL<DT<T>> small() {
closeAttrs();
return small_(this, true);
}
@Override
public DT<T> small(String cdata) {
return small().__(cdata).__();
}
@Override
public DT<T> small(String selector, String cdata) {
return setSelector(small(), selector).__(cdata).__();
}
@Override
public DT<T> em(String cdata) {
return em().__(cdata).__();
}
@Override
public EM<DT<T>> em() {
closeAttrs();
return em_(this, true);
}
@Override
public DT<T> em(String selector, String cdata) {
return setSelector(em(), selector).__(cdata).__();
}
@Override
public STRONG<DT<T>> strong() {
closeAttrs();
return strong_(this, true);
}
@Override
public DT<T> strong(String cdata) {
return strong().__(cdata).__();
}
@Override
public DT<T> strong(String selector, String cdata) {
return setSelector(strong(), selector).__(cdata).__();
}
@Override
public DFN<DT<T>> dfn() {
closeAttrs();
return dfn_(this, true);
}
@Override
public DT<T> dfn(String cdata) {
return dfn().__(cdata).__();
}
@Override
public DT<T> dfn(String selector, String cdata) {
return setSelector(dfn(), selector).__(cdata).__();
}
@Override
public CODE<DT<T>> code() {
closeAttrs();
return code_(this, true);
}
@Override
public DT<T> code(String cdata) {
return code().__(cdata).__();
}
@Override
public DT<T> code(String selector, String cdata) {
return setSelector(code(), selector).__(cdata).__();
}
@Override
public DT<T> samp(String cdata) {
return samp().__(cdata).__();
}
@Override
public SAMP<DT<T>> samp() {
closeAttrs();
return samp_(this, true);
}
@Override
public DT<T> samp(String selector, String cdata) {
return setSelector(samp(), selector).__(cdata).__();
}
@Override
public KBD<DT<T>> kbd() {
closeAttrs();
return kbd_(this, true);
}
@Override
public DT<T> kbd(String cdata) {
return kbd().__(cdata).__();
}
@Override
public DT<T> kbd(String selector, String cdata) {
return setSelector(kbd(), selector).__(cdata).__();
}
@Override
public VAR<DT<T>> var() {
closeAttrs();
return var_(this, true);
}
@Override
public DT<T> var(String cdata) {
return var().__(cdata).__();
}
@Override
public DT<T> var(String selector, String cdata) {
return setSelector(var(), selector).__(cdata).__();
}
@Override
public CITE<DT<T>> cite() {
closeAttrs();
return cite_(this, true);
}
@Override
public DT<T> cite(String cdata) {
return cite().__(cdata).__();
}
@Override
public DT<T> cite(String selector, String cdata) {
return setSelector(cite(), selector).__(cdata).__();
}
@Override
public ABBR<DT<T>> abbr() {
closeAttrs();
return abbr_(this, true);
}
@Override
public DT<T> abbr(String cdata) {
return abbr().__(cdata).__();
}
@Override
public DT<T> abbr(String selector, String cdata) {
return setSelector(abbr(), selector).__(cdata).__();
}
@Override
public A<DT<T>> a() {
closeAttrs();
return a_(this, true);
}
@Override
public A<DT<T>> a(String selector) {
return setSelector(a(), selector);
}
@Override
public DT<T> a(String href, String anchorText) {
return a().$href(href).__(anchorText).__();
}
@Override
public DT<T> a(String selector, String href, String anchorText) {
return setSelector(a(), selector).$href(href).__(anchorText).__();
}
@Override
public IMG<DT<T>> img() {
closeAttrs();
return img_(this, true);
}
@Override
public DT<T> img(String src) {
return img().$src(src).__();
}
@Override
public OBJECT<DT<T>> object() {
closeAttrs();
return object_(this, true);
}
@Override
public OBJECT<DT<T>> object(String selector) {
return setSelector(object(), selector);
}
@Override
public SUB<DT<T>> sub() {
closeAttrs();
return sub_(this, true);
}
@Override
public DT<T> sub(String cdata) {
return sub().__(cdata).__();
}
@Override
public DT<T> sub(String selector, String cdata) {
return setSelector(sub(), selector).__(cdata).__();
}
@Override
public SUP<DT<T>> sup() {
closeAttrs();
return sup_(this, true);
}
@Override
public DT<T> sup(String cdata) {
return sup().__(cdata).__();
}
@Override
public DT<T> sup(String selector, String cdata) {
return setSelector(sup(), selector).__(cdata).__();
}
@Override
public MAP<DT<T>> map() {
closeAttrs();
return map_(this, true);
}
@Override
public MAP<DT<T>> map(String selector) {
return setSelector(map(), selector);
}
@Override
public DT<T> q(String cdata) {
return q().__(cdata).__();
}
@Override
public DT<T> q(String selector, String cdata) {
return setSelector(q(), selector).__(cdata).__();
}
@Override
public Q<DT<T>> q() {
closeAttrs();
return q_(this, true);
}
@Override
public BR<DT<T>> br() {
closeAttrs();
return br_(this, true);
}
@Override
public DT<T> br(String selector) {
return setSelector(br(), selector).__();
}
@Override
public BDO<DT<T>> bdo() {
closeAttrs();
return bdo_(this, true);
}
@Override
public DT<T> bdo(Dir dir, String cdata) {
return bdo().$dir(dir).__(cdata).__();
}
@Override
public SPAN<DT<T>> span() {
closeAttrs();
return span_(this, true);
}
@Override
public DT<T> span(String cdata) {
return span().__(cdata).__();
}
@Override
public DT<T> span(String selector, String cdata) {
return setSelector(span(), selector).__(cdata).__();
}
@Override
public SCRIPT<DT<T>> script() {
closeAttrs();
return script_(this, true);
}
@Override
public DT<T> script(String src) {
return setScriptSrc(script(), src).__();
}
@Override
public INS<DT<T>> ins() {
closeAttrs();
return ins_(this, true);
}
@Override
public DT<T> ins(String cdata) {
return ins().__(cdata).__();
}
@Override
public DEL<DT<T>> del() {
closeAttrs();
return del_(this, true);
}
@Override
public DT<T> del(String cdata) {
return del().__(cdata).__();
}
@Override
public LABEL<DT<T>> label() {
closeAttrs();
return label_(this, true);
}
@Override
public DT<T> label(String forId, String cdata) {
return label().$for(forId).__(cdata).__();
}
@Override
public INPUT<DT<T>> input(String selector) {
return setSelector(input(), selector);
}
@Override
public INPUT<DT<T>> input() {
closeAttrs();
return input_(this, true);
}
@Override
public SELECT<DT<T>> select() {
closeAttrs();
return select_(this, true);
}
@Override
public SELECT<DT<T>> select(String selector) {
return setSelector(select(), selector);
}
@Override
public TEXTAREA<DT<T>> textarea(String selector) {
return setSelector(textarea(), selector);
}
@Override
public TEXTAREA<DT<T>> textarea() {
closeAttrs();
return textarea_(this, true);
}
@Override
public DT<T> textarea(String selector, String cdata) {
return setSelector(textarea(), selector).__(cdata).__();
}
@Override
public BUTTON<DT<T>> button() {
closeAttrs();
return button_(this, true);
}
@Override
public BUTTON<DT<T>> button(String selector) {
return setSelector(button(), selector);
}
@Override
public DT<T> button(String selector, String cdata) {
return setSelector(button(), selector).__(cdata).__();
}
}
public | DT |
java | apache__flink | flink-table/flink-table-code-splitter/src/test/resources/function/expected/TestSplitFunction.java | {
"start": 7,
"end": 945
} | class ____ {
boolean myFunHasReturned$0;
public void myFun(int[] a, int[] b) throws RuntimeException {
myFunHasReturned$0 = false;
myFun_split1(a, b);
if (myFunHasReturned$0) { return; }
myFun_split2(a, b);
myFun_split3(a, b);
if (myFunHasReturned$0) { return; }
myFun_split4(a, b);
}
void myFun_split1(int[] a, int[] b) throws RuntimeException {
if (a[0] != 0) {
a[0] += b[0];
b[0] += a[1];
{ myFunHasReturned$0 = true; return; }
}
}
void myFun_split2(int[] a, int[] b) throws RuntimeException {
a[1] += b[1];
b[1] += a[2];
}
void myFun_split3(int[] a, int[] b) throws RuntimeException {
if (a[2] != 0) {
a[2] += b[2];
b[2] += a[3];
{ myFunHasReturned$0 = true; return; }
}
}
void myFun_split4(int[] a, int[] b) throws RuntimeException {
a[3] += b[3];
b[3] += a[4];
}
}
| TestSplitFunction |
java | quarkusio__quarkus | extensions/smallrye-health/deployment/src/main/java/io/quarkus/smallrye/health/deployment/SmallRyeHealthUIConfig.java | {
"start": 159,
"end": 738
} | interface ____ {
/**
* The path where Health UI is available.
* The value `/` is not allowed as it blocks the application from serving anything else.
* By default, this value will be resolved as a path relative to `${quarkus.http.non-application-root-path}`.
*/
@WithDefault("health-ui")
String rootPath();
/**
* Always include the UI. By default, this will only be included in dev and test.
* Setting this to true will also include the UI in Prod
*/
@WithDefault("false")
boolean alwaysInclude();
}
| SmallRyeHealthUIConfig |
java | quarkusio__quarkus | extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/SslClientCertAttribute.java | {
"start": 308,
"end": 1876
} | class ____ implements ExchangeAttribute {
public static final SslClientCertAttribute INSTANCE = new SslClientCertAttribute();
public static final java.lang.String BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
public static final java.lang.String END_CERT = "-----END CERTIFICATE-----";
public static String toPem(final X509Certificate certificate) throws CertificateEncodingException {
final StringBuilder builder = new StringBuilder();
builder.append(BEGIN_CERT);
builder.append('\n');
builder.append(Base64.getEncoder().encodeToString(certificate.getEncoded()));
builder.append('\n');
builder.append(END_CERT);
return builder.toString();
}
@Override
public String readAttribute(RoutingContext exchange) {
SSLSession ssl = exchange.request().sslSession();
if (ssl == null) {
return null;
}
X509Certificate[] certificates;
try {
certificates = ssl.getPeerCertificateChain();
if (certificates.length > 0) {
return toPem(certificates[0]);
}
return null;
} catch (SSLPeerUnverifiedException e) {
return null;
} catch (CertificateEncodingException e) {
return null;
}
}
@Override
public void writeAttribute(RoutingContext exchange, String newValue) throws ReadOnlyAttributeException {
throw new ReadOnlyAttributeException("SSL Client Cert", newValue);
}
public static final | SslClientCertAttribute |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/string/LengthSerializationTests.java | {
"start": 539,
"end": 753
} | class ____ extends AbstractUnaryScalarSerializationTests<Length> {
@Override
protected Length create(Source source, Expression child) {
return new Length(source, child);
}
}
| LengthSerializationTests |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/StateBackendLoader.java | {
"start": 12482,
"end": 16217
} | class ____ not found or could not be instantiated
* @throws IllegalConfigurationException May be thrown by the StateBackendFactory when creating
* / configuring the state backend in the factory
* @throws IOException May be thrown by the StateBackendFactory when instantiating the state
* backend
*/
public static StateBackend fromApplicationOrConfigOrDefault(
@Nullable StateBackend fromApplication,
Configuration jobConfig,
Configuration clusterConfig,
ClassLoader classLoader,
@Nullable Logger logger)
throws IllegalConfigurationException, DynamicCodeLoadingException, IOException {
StateBackend rootBackend =
loadFromApplicationOrConfigOrDefaultInternal(
fromApplication, jobConfig, clusterConfig, classLoader, logger);
boolean enableChangeLog =
jobConfig
.getOptional(StateChangelogOptions.ENABLE_STATE_CHANGE_LOG)
.orElse(clusterConfig.get(StateChangelogOptions.ENABLE_STATE_CHANGE_LOG));
StateBackend backend;
if (enableChangeLog) {
backend = wrapStateBackend(rootBackend, classLoader, CHANGELOG_STATE_BACKEND);
LOG.info(
"State backend loader loads {} to delegate {}",
backend.getClass().getSimpleName(),
rootBackend.getClass().getSimpleName());
} else {
backend = rootBackend;
LOG.info(
"State backend loader loads the state backend as {}",
backend.getClass().getSimpleName());
}
return backend;
}
/**
* Checks whether state backend uses managed memory, without having to deserialize or load the
* state backend.
*
* @param config configuration to load the state backend from.
* @param stateBackendFromApplicationUsesManagedMemory Whether the application-defined backend
* uses Flink's managed memory. Empty if application has not defined a backend.
* @param classLoader User code classloader.
* @return Whether the state backend uses managed memory.
*/
public static boolean stateBackendFromApplicationOrConfigOrDefaultUseManagedMemory(
Configuration config,
Optional<Boolean> stateBackendFromApplicationUsesManagedMemory,
ClassLoader classLoader) {
checkNotNull(config, "config");
// (1) the application defined state backend has precedence
if (stateBackendFromApplicationUsesManagedMemory.isPresent()) {
return stateBackendFromApplicationUsesManagedMemory.get();
}
// (2) check if the config defines a state backend
try {
final StateBackend fromConfig = loadStateBackendFromConfig(config, classLoader, LOG);
return fromConfig.useManagedMemory();
} catch (IllegalConfigurationException | DynamicCodeLoadingException | IOException e) {
LOG.warn(
"Cannot decide whether state backend uses managed memory. Will reserve managed memory by default.",
e);
return true;
}
}
/**
* Load state backend which may wrap the original state backend for recovery.
*
* @param originalStateBackend StateBackend loaded from application or config.
* @param classLoader User code classloader.
* @param keyedStateHandles The state handles for restore.
* @return Wrapped state backend for recovery.
* @throws DynamicCodeLoadingException Thrown if keyed state handles of wrapped state backend
* are found and the | was |
java | quarkusio__quarkus | independent-projects/qute/debug/src/test/java/io/quarkus/qute/debug/client/TracingMessageConsumer.java | {
"start": 9841,
"end": 9911
} | class ____ holding pending request metadata.
*/
public static | for |
java | elastic__elasticsearch | modules/reindex/src/test/java/org/elasticsearch/reindex/ReindexFromRemoteWithAuthTests.java | {
"start": 6542,
"end": 7504
} | class ____ extends Plugin implements ActionPlugin {
private final SetOnce<ReindexFromRemoteWithAuthTests.TestFilter> testFilter = new SetOnce<>();
@Override
public Collection<?> createComponents(PluginServices services) {
testFilter.set(new ReindexFromRemoteWithAuthTests.TestFilter(services.threadPool()));
return Collections.emptyList();
}
@Override
public List<ActionFilter> getActionFilters() {
return singletonList(testFilter.get());
}
@Override
public Collection<RestHeaderDefinition> getRestHeaders() {
return Arrays.asList(
new RestHeaderDefinition(TestFilter.AUTHORIZATION_HEADER, false),
new RestHeaderDefinition(TestFilter.EXAMPLE_HEADER, false)
);
}
}
/**
* Action filter that will reject the request if it isn't authenticated.
*/
public static | TestPlugin |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/custom/request/RerankParametersTests.java | {
"start": 541,
"end": 1286
} | class ____ extends ESTestCase {
public void testTaskTypeParameters() {
var queryAndDocsInputs = new QueryAndDocsInputs("query_value", List.of("doc1", "doc2"), true, 5, false);
var parameters = RerankParameters.of(queryAndDocsInputs);
assertThat(parameters.taskTypeParameters(), is(Map.of("query", "\"query_value\"", "top_n", "5", "return_documents", "true")));
}
public void testTaskTypeParameters_WithoutOptionalFields() {
var queryAndDocsInputs = new QueryAndDocsInputs("query_value", List.of("doc1", "doc2"));
var parameters = RerankParameters.of(queryAndDocsInputs);
assertThat(parameters.taskTypeParameters(), is(Map.of("query", "\"query_value\"")));
}
}
| RerankParametersTests |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authz/store/RoleReferenceTests.java | {
"start": 1050,
"end": 5999
} | class ____ extends ESTestCase {
public void testNamedRoleReference() {
final String[] roleNames = randomArray(0, 2, String[]::new, () -> randomAlphaOfLengthBetween(4, 8));
final RoleReference.NamedRoleReference namedRoleReference = new RoleReference.NamedRoleReference(roleNames);
if (roleNames.length == 0) {
assertThat(namedRoleReference.id(), is(RoleKey.ROLE_KEY_EMPTY));
} else {
final RoleKey roleKey = namedRoleReference.id();
assertThat(roleKey.getNames(), equalTo(Set.of(roleNames)));
assertThat(roleKey.getSource(), equalTo(RoleKey.ROLES_STORE_SOURCE));
}
}
public void testSuperuserRoleReference() {
final String[] roleNames = randomArray(1, 3, String[]::new, () -> randomAlphaOfLengthBetween(4, 12));
roleNames[randomIntBetween(0, roleNames.length - 1)] = "superuser";
final RoleReference.NamedRoleReference namedRoleReference = new RoleReference.NamedRoleReference(roleNames);
if (roleNames.length == 1) {
assertThat(namedRoleReference.id(), is(RoleKey.ROLE_KEY_SUPERUSER));
} else {
final RoleKey roleKey = namedRoleReference.id();
assertThat(roleKey.getNames(), equalTo(Set.of(roleNames)));
assertThat(roleKey.getSource(), equalTo(RoleKey.ROLES_STORE_SOURCE));
}
}
public void testApiKeyRoleReference() {
final String apiKeyId = randomAlphaOfLength(20);
final BytesArray roleDescriptorsBytes = new BytesArray(randomAlphaOfLength(50));
final RoleReference.ApiKeyRoleType apiKeyRoleType = randomFrom(RoleReference.ApiKeyRoleType.values());
final RoleReference.ApiKeyRoleReference apiKeyRoleReference = new RoleReference.ApiKeyRoleReference(
apiKeyId,
roleDescriptorsBytes,
apiKeyRoleType
);
final RoleKey roleKey = apiKeyRoleReference.id();
assertThat(
roleKey.getNames(),
hasItem("apikey:" + MessageDigests.toHexString(MessageDigests.digest(roleDescriptorsBytes, MessageDigests.sha256())))
);
assertThat(roleKey.getSource(), equalTo("apikey_" + apiKeyRoleType));
}
public void testCrossClusterApiKeyRoleReference() {
final String apiKeyId = randomAlphaOfLength(20);
final BytesArray roleDescriptorsBytes = new BytesArray(randomAlphaOfLength(50));
final RoleReference.CrossClusterApiKeyRoleReference apiKeyRoleReference = new RoleReference.CrossClusterApiKeyRoleReference(
apiKeyId,
roleDescriptorsBytes
);
final RoleKey roleKey = apiKeyRoleReference.id();
assertThat(
roleKey.getNames(),
hasItem("apikey:" + MessageDigests.toHexString(MessageDigests.digest(roleDescriptorsBytes, MessageDigests.sha256())))
);
assertThat(roleKey.getSource(), equalTo("apikey_" + RoleReference.ApiKeyRoleType.ASSIGNED));
}
public void testCrossClusterAccessRoleReference() {
final var roleDescriptorsBytes = new CrossClusterAccessSubjectInfo.RoleDescriptorsBytes(new BytesArray(randomAlphaOfLength(50)));
final var crossClusterAccessRoleReference = new RoleReference.CrossClusterAccessRoleReference("user", roleDescriptorsBytes);
final RoleKey roleKey = crossClusterAccessRoleReference.id();
assertThat(roleKey.getNames(), containsInAnyOrder("cross_cluster_access:" + roleDescriptorsBytes.digest()));
assertThat(roleKey.getSource(), equalTo("cross_cluster_access"));
}
public void testFixedRoleReference() throws ExecutionException, InterruptedException {
final RoleDescriptor roleDescriptor = RoleDescriptorTestHelper.randomRoleDescriptor();
final String source = "source";
final var fixedRoleReference = new RoleReference.FixedRoleReference(roleDescriptor, source);
final var future = new PlainActionFuture<RolesRetrievalResult>();
fixedRoleReference.resolve(mock(RoleReferenceResolver.class), future);
final var actualRetrievalResult = future.get();
assertThat(actualRetrievalResult.getRoleDescriptors(), equalTo(Set.of(roleDescriptor)));
final RoleKey roleKey = fixedRoleReference.id();
assertThat(roleKey.getNames(), containsInAnyOrder(roleDescriptor.getName()));
assertThat(roleKey.getSource(), equalTo(source));
}
public void testServiceAccountRoleReference() {
final String principal = randomAlphaOfLength(8) + "/" + randomAlphaOfLength(8);
final RoleReference.ServiceAccountRoleReference serviceAccountRoleReference = new RoleReference.ServiceAccountRoleReference(
principal
);
final RoleKey roleKey = serviceAccountRoleReference.id();
assertThat(roleKey.getNames(), hasItem(principal));
assertThat(roleKey.getSource(), equalTo("service_account"));
}
}
| RoleReferenceTests |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/support/component/ApiMethodPropertiesHelperTest.java | {
"start": 4903,
"end": 5420
} | class ____ extends TestComponentConfiguration {
private String property3;
private Boolean property4;
public String getProperty3() {
return property3;
}
public void setProperty3(String property3) {
this.property3 = property3;
}
public Boolean getProperty4() {
return property4;
}
public void setProperty4(Boolean property4) {
this.property4 = property4;
}
}
}
| TestEndpointConfiguration |
java | quarkusio__quarkus | extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/QuarkusFlywayResourceProvider.java | {
"start": 318,
"end": 472
} | class ____ very similar to {@link org.flywaydb.core.internal.scanner.Scanner}
* TODO: refactor upstream to move common methods to utility class
*/
public | is |
java | quarkusio__quarkus | extensions/redis-client/runtime/src/main/java/io/quarkus/redis/client/RedisHostsProvider.java | {
"start": 134,
"end": 401
} | interface ____ {
/**
* Returns the hosts for this provider.
* <p>
* The host provided uses the following schema `redis://[username:password@][host][:port][/database]`
*
* @return the hosts
*/
Set<URI> getHosts();
}
| RedisHostsProvider |
java | apache__camel | components/camel-servlet/src/test/java/org/apache/camel/component/servlet/rest/RestServletBindingModeOffWithContractTest.java | {
"start": 1452,
"end": 4077
} | class ____ extends ServletCamelRouterTestSupport {
@Test
public void testBindingModeOffWithContract() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:input");
mock.expectedMessageCount(1);
mock.message(0).body().isInstanceOf(UserPojoEx.class);
String body = "{\"id\": 123, \"name\": \"Donald Duck\"}";
WebRequest req = new PostMethodWebRequest(
contextUrl + "/services/users/new",
new ByteArrayInputStream(body.getBytes()), "application/json");
WebResponse response = query(req, false);
assertEquals(200, response.getResponseCode());
String answer = response.getText();
assertTrue(answer.contains("\"active\":true"), "Unexpected response: " + answer);
MockEndpoint.assertIsSatisfied(context);
Object obj = mock.getReceivedExchanges().get(0).getIn().getBody();
assertEquals(UserPojoEx.class, obj.getClass());
UserPojoEx user = (UserPojoEx) obj;
assertNotNull(user);
assertEquals(123, user.getId());
assertEquals("Donald Duck", user.getName());
assertEquals(true, user.isActive());
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
restConfiguration().component("servlet").bindingMode(RestBindingMode.off);
JsonDataFormat jsondf = new JsonDataFormat();
jsondf.setLibrary(JsonLibrary.Jackson);
jsondf.setAllowUnmarshallType(Boolean.toString(true));
jsondf.setUnmarshalType(UserPojoEx.class);
transformer()
.fromType("json")
.toType(UserPojoEx.class)
.withDataFormat(jsondf);
transformer()
.fromType(UserPojoEx.class)
.toType("json")
.withDataFormat(jsondf);
rest("/users/")
// REST binding does nothing
.post("new").to("direct:new");
from("direct:new")
// contract advice converts between JSON and UserPojoEx directly
.inputType(UserPojoEx.class)
.outputType("json")
.process(ex -> ex.getIn().getBody(UserPojoEx.class).setActive(true))
.to("mock:input");
}
};
}
}
| RestServletBindingModeOffWithContractTest |
java | resilience4j__resilience4j | resilience4j-spring/src/main/java/io/github/resilience4j/circuitbreaker/configure/IgnoreClassBindingExceptionConverter.java | {
"start": 2979,
"end": 3085
} | class ____ encountered
* and {@code ignoreUnknownExceptions} is set to true.
*/
public static | is |
java | spring-projects__spring-boot | configuration-metadata/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/specific/InvalidAccessorProperties.java | {
"start": 908,
"end": 1203
} | class ____ {
private String name;
private boolean flag;
public void set(String name) {
this.name = name;
}
public String get() {
return this.name;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public boolean is() {
return this.flag;
}
}
| InvalidAccessorProperties |
java | elastic__elasticsearch | x-pack/plugin/ml/qa/ml-inference-service-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/ModelIdUniquenessIT.java | {
"start": 515,
"end": 2170
} | class ____ extends InferenceBaseRestTest {
public void testPutInferenceModelFailsWhenTrainedModelWithIdAlreadyExists() throws Exception {
String modelId = "duplicate_model_id";
putPyTorchModelTrainedModels(modelId);
putPyTorchModelDefinitionTrainedModels(modelId);
putPyTorchModelVocabularyTrainedModels(List.of("these", "are", "my", "words"), modelId);
startDeploymentTrainedModels(modelId);
var e = expectThrows(ResponseException.class, () -> putInferenceServiceModel(modelId, TaskType.SPARSE_EMBEDDING));
assertThat(
e.getMessage(),
Matchers.containsString(
"Inference endpoint IDs must be unique. Requested inference endpoint ID ["
+ modelId
+ "] matches existing trained model ID(s) but must not."
)
);
}
public void testPutTrainedModelFailsWhenInferenceModelWithIdAlreadyExists() throws Exception {
String modelId = "duplicate_model_id";
putPyTorchModelTrainedModels(modelId);
putPyTorchModelDefinitionTrainedModels(modelId);
putPyTorchModelVocabularyTrainedModels(List.of("these", "are", "my", "words"), modelId);
putInferenceServiceModel(modelId, TaskType.SPARSE_EMBEDDING);
var e = expectThrows(ResponseException.class, () -> startDeploymentTrainedModels(modelId));
assertThat(
e.getMessage(),
Matchers.containsString(
"Model IDs must be unique. Requested model ID [" + modelId + "] matches existing model IDs but must not."
)
);
}
}
| ModelIdUniquenessIT |
java | elastic__elasticsearch | test/fixtures/ec2-imds-fixture/src/main/java/fixture/aws/imds/Ec2ImdsHttpFixture.java | {
"start": 1011,
"end": 4235
} | class ____ extends ExternalResource {
/**
* Name of the JVM system property that allows to override the IMDS endpoint address when using the AWS v2 SDK.
*/
public static final String ENDPOINT_OVERRIDE_SYSPROP_NAME_SDK2 = "aws.ec2MetadataServiceEndpoint";
private final Ec2ImdsServiceBuilder ec2ImdsServiceBuilder;
private HttpServer server;
public Ec2ImdsHttpFixture(Ec2ImdsServiceBuilder ec2ImdsServiceBuilder) {
this.ec2ImdsServiceBuilder = ec2ImdsServiceBuilder;
}
public String getAddress() {
return "http://" + server.getAddress().getHostString() + ":" + server.getAddress().getPort();
}
public void stop(int delay) {
server.stop(delay);
}
protected void before() throws Throwable {
server = HttpServer.create(resolveAddress(), 0);
server.createContext("/", Objects.requireNonNull(ec2ImdsServiceBuilder.buildHandler()));
server.start();
}
@Override
protected void after() {
stop(0);
}
private static InetSocketAddress resolveAddress() {
try {
return new InetSocketAddress(InetAddress.getByName("localhost"), 0);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
/**
* Overrides the EC2 service endpoint for the lifetime of the method response. Resets back to the original endpoint property when
* closed.
*/
@SuppressForbidden(reason = "deliberately adjusting system property for endpoint override for use in internal-cluster tests")
public static Releasable withEc2MetadataServiceEndpointOverride(String endpointOverride) {
final PrivilegedAction<String> resetProperty = System.getProperty(
ENDPOINT_OVERRIDE_SYSPROP_NAME_SDK2
) instanceof String originalValue
? () -> System.setProperty(ENDPOINT_OVERRIDE_SYSPROP_NAME_SDK2, originalValue)
: () -> System.clearProperty(ENDPOINT_OVERRIDE_SYSPROP_NAME_SDK2);
doPrivileged(() -> System.setProperty(ENDPOINT_OVERRIDE_SYSPROP_NAME_SDK2, endpointOverride));
return () -> doPrivileged(resetProperty);
}
private static void doPrivileged(PrivilegedAction<?> privilegedAction) {
AccessController.doPrivileged(privilegedAction);
}
/**
* Adapter to allow running a {@link Ec2ImdsHttpFixture} directly rather than via a {@code @ClassRule}. Creates an HTTP handler (see
* {@link Ec2ImdsHttpHandler}) from the given builder, and provides the handler to the action, and then cleans up the handler.
*/
public static void runWithFixture(Ec2ImdsServiceBuilder ec2ImdsServiceBuilder, CheckedConsumer<Ec2ImdsHttpFixture, Exception> action) {
final var imdsFixture = new Ec2ImdsHttpFixture(ec2ImdsServiceBuilder);
try {
imdsFixture.apply(new Statement() {
@Override
public void evaluate() throws Exception {
action.accept(imdsFixture);
}
}, Description.EMPTY).evaluate();
} catch (Throwable e) {
throw new AssertionError(e);
} finally {
imdsFixture.stop(0);
}
}
}
| Ec2ImdsHttpFixture |
java | apache__flink | flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/utils/TableSemanticsMock.java | {
"start": 1165,
"end": 2443
} | class ____ implements TableSemantics {
private final DataType dataType;
private final int[] partitionByColumns;
private final int[] orderByColumns;
private final int timeColumn;
private final ChangelogMode changelogMode;
public TableSemanticsMock(DataType dataType) {
this(dataType, new int[0], new int[0], -1, null);
}
public TableSemanticsMock(
DataType dataType,
int[] partitionByColumns,
int[] orderByColumns,
int timeColumn,
@Nullable ChangelogMode changelogMode) {
this.dataType = dataType;
this.partitionByColumns = partitionByColumns;
this.orderByColumns = orderByColumns;
this.timeColumn = timeColumn;
this.changelogMode = changelogMode;
}
@Override
public DataType dataType() {
return dataType;
}
@Override
public int[] partitionByColumns() {
return partitionByColumns;
}
@Override
public int[] orderByColumns() {
return orderByColumns;
}
@Override
public int timeColumn() {
return timeColumn;
}
@Override
public Optional<ChangelogMode> changelogMode() {
return Optional.ofNullable(changelogMode);
}
}
| TableSemanticsMock |
java | google__auto | value/src/test/java/com/google/auto/value/processor/AutoAnnotationCompilationTest.java | {
"start": 1875,
"end": 2338
} | enum ____ {",
" ONE",
"}");
JavaFileObject annotationFactoryJavaFile =
JavaFileObjects.forSourceLines(
"com.example.factories.AnnotationFactory",
"package com.example.factories;",
"",
"import com.google.auto.value.AutoAnnotation;",
"import com.example.annotations.MyAnnotation;",
"import com.example.enums.MyEnum;",
"",
"public | MyEnum |
java | elastic__elasticsearch | benchmarks/src/main/java/org/elasticsearch/benchmark/vector/scorer/BenchmarkUtils.java | {
"start": 1338,
"end": 4371
} | class ____ {
// Unsigned int7 byte vectors have values in the range of 0 to 127 (inclusive).
static final byte MIN_INT7_VALUE = 0;
static final byte MAX_INT7_VALUE = 127;
static void randomInt7BytesBetween(byte[] bytes) {
var random = ThreadLocalRandom.current();
for (int i = 0, len = bytes.length; i < len;) {
bytes[i++] = (byte) random.nextInt(MIN_INT7_VALUE, MAX_INT7_VALUE + 1);
}
}
static void createRandomInt7VectorData(ThreadLocalRandom random, Directory dir, int dims, int numVectors) throws IOException {
try (IndexOutput out = dir.createOutput("vector.data", IOContext.DEFAULT)) {
var vec = new byte[dims];
for (int v = 0; v < numVectors; v++) {
randomInt7BytesBetween(vec);
var vecOffset = random.nextFloat();
out.writeBytes(vec, 0, vec.length);
out.writeInt(Float.floatToIntBits(vecOffset));
}
}
}
static VectorScorerFactory getScorerFactoryOrDie() {
var optionalVectorScorerFactory = VectorScorerFactory.instance();
if (optionalVectorScorerFactory.isEmpty()) {
String msg = "JDK=["
+ Runtime.version()
+ "], os.name=["
+ System.getProperty("os.name")
+ "], os.arch=["
+ System.getProperty("os.arch")
+ "]";
throw new AssertionError("Vector scorer factory not present. Cannot run the benchmark. " + msg);
}
return optionalVectorScorerFactory.get();
}
static boolean supportsHeapSegments() {
return Runtime.version().feature() >= 22;
}
static QuantizedByteVectorValues vectorValues(int dims, int size, IndexInput in, VectorSimilarityFunction sim) throws IOException {
var sq = new ScalarQuantizer(0.1f, 0.9f, (byte) 7);
var slice = in.slice("values", 0, in.length());
return new OffHeapQuantizedByteVectorValues.DenseOffHeapVectorValues(dims, size, sq, false, sim, null, slice);
}
static RandomVectorScorerSupplier luceneScoreSupplier(QuantizedByteVectorValues values, VectorSimilarityFunction sim)
throws IOException {
return new Lucene99ScalarQuantizedVectorScorer(null).getRandomVectorScorerSupplier(sim, values);
}
static RandomVectorScorer luceneScorer(QuantizedByteVectorValues values, VectorSimilarityFunction sim, float[] queryVec)
throws IOException {
return new Lucene99ScalarQuantizedVectorScorer(null).getRandomVectorScorer(sim, values, queryVec);
}
static float readNodeCorrectionConstant(QuantizedByteVectorValues values, int targetOrd) throws IOException {
var vectorByteSize = values.getVectorByteLength();
var input = (MemorySegmentAccessInput) values.getSlice();
long byteOffset = (long) targetOrd * (vectorByteSize + Float.BYTES);
return Float.intBitsToFloat(input.readInt(byteOffset + vectorByteSize));
}
}
| BenchmarkUtils |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/json/JobVertexIDKeySerializer.java | {
"start": 1296,
"end": 1712
} | class ____ extends StdSerializer<JobVertexID> {
private static final long serialVersionUID = 2970050507628933522L;
public JobVertexIDKeySerializer() {
super(JobVertexID.class);
}
@Override
public void serialize(JobVertexID value, JsonGenerator gen, SerializerProvider provider)
throws IOException {
gen.writeFieldName(value.toString());
}
}
| JobVertexIDKeySerializer |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_3732/Issue3732Mapper.java | {
"start": 665,
"end": 888
} | class ____ {
private LocalDate value;
public LocalDate getValue() {
return value;
}
public void setValue(LocalDate value) {
this.value = value;
}
}
}
| Target |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/params/provider/EnumArgumentsProviderTests.java | {
"start": 6588,
"end": 6617
} | enum ____");
}
static | constant |
java | spring-projects__spring-security | access/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationCollectionFilteringProviderTests.java | {
"start": 1790,
"end": 4061
} | class ____ {
@Test
public void objectsAreRemovedIfPermissionDenied() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
given(acl.isGranted(any(), any(), anyBoolean())).willReturn(false);
given(service.readAclById(any(), any())).willReturn(acl);
AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider(
service, Arrays.asList(mock(Permission.class)));
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"),
new ArrayList(Arrays.asList(new Object(), new Object())));
assertThat(returned).isInstanceOf(List.class);
assertThat(((List) returned)).isEmpty();
returned = provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("UNSUPPORTED", "AFTER_ACL_COLLECTION_READ"),
new Object[] { new Object(), new Object() });
assertThat(returned instanceof Object[]).isTrue();
assertThat(((Object[]) returned).length == 0).isTrue();
}
@Test
public void accessIsGrantedIfNoAttributesDefined() {
AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider(
mock(AclService.class), Arrays.asList(mock(Permission.class)));
Object returned = new Object();
assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(),
Collections.<ConfigAttribute>emptyList(), returned));
}
@Test
public void nullReturnObjectIsIgnored() {
AclService service = mock(AclService.class);
AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider(
service, Arrays.asList(mock(Permission.class)));
assertThat(provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null))
.isNull();
verify(service, never()).readAclById(any(ObjectIdentity.class), any(List.class));
}
}
| AclEntryAfterInvocationCollectionFilteringProviderTests |
java | quarkusio__quarkus | integration-tests/spring-web/src/test/java/io/quarkus/it/spring/web/TestHTTPEndpointTest.java | {
"start": 319,
"end": 552
} | class ____ {
@Test
public void testJsonResult() {
RestAssured.when().get("/json/hello").then()
.contentType("application/json")
.body(containsString("hello"));
}
}
| TestHTTPEndpointTest |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/constructor/simpleinjection/B2.java | {
"start": 698,
"end": 935
} | class ____ {
private A a;
private A a2;
@Inject
public B2(A a, A a2) {
this.a = a;
this.a2 = a2;
}
public A getA() {
return this.a;
}
public A getA2() {
return a2;
}
}
| B2 |
java | netty__netty | handler-proxy/src/test/java/io/netty/handler/proxy/ProxyServer.java | {
"start": 8379,
"end": 9351
} | class ____ extends ChannelInboundHandlerAdapter {
private final ChannelHandlerContext frontend;
BackendHandler(ChannelHandlerContext frontend) {
this.frontend = frontend;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
frontend.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
frontend.flush();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
frontend.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
recordException(cause);
ctx.close();
}
}
}
protected abstract | BackendHandler |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/JmsComponentBuilderFactory.java | {
"start": 1812,
"end": 15125
} | interface ____ extends ComponentBuilder<JmsComponent> {
/**
* Sets the JMS client ID to use. Note that this value, if specified,
* must be unique and can only be used by a single JMS connection
* instance. It is typically only required for durable topic
* subscriptions with JMS 1.1.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param clientId the value to set
* @return the dsl builder
*/
default JmsComponentBuilder clientId(java.lang.String clientId) {
doSetProperty("clientId", clientId);
return this;
}
/**
* The connection factory to be use. A connection factory must be
* configured either on the component or endpoint.
*
* The option is a:
* <code>jakarta.jms.ConnectionFactory</code> type.
*
* Group: common
*
* @param connectionFactory the value to set
* @return the dsl builder
*/
default JmsComponentBuilder connectionFactory(jakarta.jms.ConnectionFactory connectionFactory) {
doSetProperty("connectionFactory", connectionFactory);
return this;
}
/**
* Specifies whether Camel ignores the JMSReplyTo header in messages. If
* true, Camel does not send a reply back to the destination specified
* in the JMSReplyTo header. You can use this option if you want Camel
* to consume from a route and you do not want Camel to automatically
* send back a reply message because another component in your code
* handles the reply message. You can also use this option if you want
* to use Camel as a proxy between different message brokers and you
* want to route message from one system to another.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param disableReplyTo the value to set
* @return the dsl builder
*/
default JmsComponentBuilder disableReplyTo(boolean disableReplyTo) {
doSetProperty("disableReplyTo", disableReplyTo);
return this;
}
/**
* The durable subscriber name for specifying durable topic
* subscriptions. The clientId option must be configured as well.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param durableSubscriptionName the value to set
* @return the dsl builder
*/
default JmsComponentBuilder durableSubscriptionName(java.lang.String durableSubscriptionName) {
doSetProperty("durableSubscriptionName", durableSubscriptionName);
return this;
}
/**
* Allows you to force the use of a specific jakarta.jms.Message
* implementation for sending JMS messages. Possible values are: Bytes,
* Map, Object, Stream, Text. By default, Camel would determine which
* JMS message type to use from the In body type. This option allows you
* to specify it.
*
* The option is a:
* <code>org.apache.camel.component.jms.JmsMessageType</code> type.
*
* Group: common
*
* @param jmsMessageType the value to set
* @return the dsl builder
*/
default JmsComponentBuilder jmsMessageType(org.apache.camel.component.jms.JmsMessageType jmsMessageType) {
doSetProperty("jmsMessageType", jmsMessageType);
return this;
}
/**
* Provides an explicit ReplyTo destination (overrides any incoming
* value of Message.getJMSReplyTo() in consumer).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param replyTo the value to set
* @return the dsl builder
*/
default JmsComponentBuilder replyTo(java.lang.String replyTo) {
doSetProperty("replyTo", replyTo);
return this;
}
/**
* Specifies whether to test the connection on startup. This ensures
* that when Camel starts that all the JMS consumers have a valid
* connection to the JMS broker. If a connection cannot be granted then
* Camel throws an exception on startup. This ensures that Camel is not
* started with failed connections. The JMS producers is tested as well.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param testConnectionOnStartup the value to set
* @return the dsl builder
*/
default JmsComponentBuilder testConnectionOnStartup(boolean testConnectionOnStartup) {
doSetProperty("testConnectionOnStartup", testConnectionOnStartup);
return this;
}
/**
* The JMS acknowledgement name, which is one of: SESSION_TRANSACTED,
* CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: AUTO_ACKNOWLEDGE
* Group: consumer
*
* @param acknowledgementModeName the value to set
* @return the dsl builder
*/
default JmsComponentBuilder acknowledgementModeName(java.lang.String acknowledgementModeName) {
doSetProperty("acknowledgementModeName", acknowledgementModeName);
return this;
}
/**
* Consumer priorities allow you to ensure that high priority consumers
* receive messages while they are active. Normally, active consumers
* connected to a queue receive messages from it in a round-robin
* fashion. When consumer priorities are in use, messages are delivered
* round-robin if multiple active consumers exist with the same high
* priority. Messages will only going to lower priority consumers when
* the high priority consumers do not have credit available to consume
* the message, or those high priority consumers have declined to accept
* the message (for instance because it does not meet the criteria of
* any selectors associated with the consumer).
*
* The option is a: <code>int</code> type.
*
* Group: consumer
*
* @param artemisConsumerPriority the value to set
* @return the dsl builder
*/
default JmsComponentBuilder artemisConsumerPriority(int artemisConsumerPriority) {
doSetProperty("artemisConsumerPriority", artemisConsumerPriority);
return this;
}
/**
* Whether the JmsConsumer processes the Exchange asynchronously. If
* enabled then the JmsConsumer may pickup the next message from the JMS
* queue, while the previous message is being processed asynchronously
* (by the Asynchronous Routing Engine). This means that messages may be
* processed not 100% strictly in order. If disabled (as default) then
* the Exchange is fully processed before the JmsConsumer will pickup
* the next message from the JMS queue. Note if transacted has been
* enabled, then asyncConsumer=true does not run asynchronously, as
* transaction must be executed synchronously.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param asyncConsumer the value to set
* @return the dsl builder
*/
default JmsComponentBuilder asyncConsumer(boolean asyncConsumer) {
doSetProperty("asyncConsumer", asyncConsumer);
return this;
}
/**
* Specifies whether the consumer container should auto-startup.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: consumer
*
* @param autoStartup the value to set
* @return the dsl builder
*/
default JmsComponentBuilder autoStartup(boolean autoStartup) {
doSetProperty("autoStartup", autoStartup);
return this;
}
/**
* Sets the cache level by ID for the underlying JMS resources. See
* cacheLevelName option for more details.
*
* The option is a: <code>int</code> type.
*
* Group: consumer
*
* @param cacheLevel the value to set
* @return the dsl builder
*/
default JmsComponentBuilder cacheLevel(int cacheLevel) {
doSetProperty("cacheLevel", cacheLevel);
return this;
}
/**
* Sets the cache level by name for the underlying JMS resources.
* Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER,
* CACHE_NONE, and CACHE_SESSION. The default setting is CACHE_AUTO. See
* the Spring documentation and Transactions Cache Levels for more
* information.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: CACHE_AUTO
* Group: consumer
*
* @param cacheLevelName the value to set
* @return the dsl builder
*/
default JmsComponentBuilder cacheLevelName(java.lang.String cacheLevelName) {
doSetProperty("cacheLevelName", cacheLevelName);
return this;
}
/**
* Specifies the default number of concurrent consumers when consuming
* from JMS (not for request/reply over JMS). See also the
* maxMessagesPerTask option to control dynamic scaling up/down of
* threads. When doing request/reply over JMS then the option
* replyToConcurrentConsumers is used to control number of concurrent
* consumers on the reply message listener.
*
* The option is a: <code>int</code> type.
*
* Default: 1
* Group: consumer
*
* @param concurrentConsumers the value to set
* @return the dsl builder
*/
default JmsComponentBuilder concurrentConsumers(int concurrentConsumers) {
doSetProperty("concurrentConsumers", concurrentConsumers);
return this;
}
/**
* Specifies the maximum number of concurrent consumers when consuming
* from JMS (not for request/reply over JMS). See also the
* maxMessagesPerTask option to control dynamic scaling up/down of
* threads. When doing request/reply over JMS then the option
* replyToMaxConcurrentConsumers is used to control number of concurrent
* consumers on the reply message listener.
*
* The option is a: <code>int</code> type.
*
* Group: consumer
*
* @param maxConcurrentConsumers the value to set
* @return the dsl builder
*/
default JmsComponentBuilder maxConcurrentConsumers(int maxConcurrentConsumers) {
doSetProperty("maxConcurrentConsumers", maxConcurrentConsumers);
return this;
}
/**
* Specifies whether to use persistent delivery by default for replies.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: consumer
*
* @param replyToDeliveryPersistent the value to set
* @return the dsl builder
*/
default JmsComponentBuilder replyToDeliveryPersistent(boolean replyToDeliveryPersistent) {
doSetProperty("replyToDeliveryPersistent", replyToDeliveryPersistent);
return this;
}
/**
* Sets the JMS selector to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param selector the value to set
* @return the dsl builder
*/
default JmsComponentBuilder selector(java.lang.String selector) {
doSetProperty("selector", selector);
return this;
}
/**
* Set whether to make the subscription durable. The durable
* subscription name to be used can be specified through the
* subscriptionName property. Default is false. Set this to true to
* register a durable subscription, typically in combination with a
* subscriptionName value (unless your message listener | JmsComponentBuilder |
java | apache__flink | flink-connectors/flink-hadoop-compatibility/src/main/java/org/apache/flink/hadoopcompatibility/HadoopInputs.java | {
"start": 1116,
"end": 1719
} | class ____ use Apache Hadoop InputFormats with Apache Flink.
*
* <p>It provides methods to create Flink InputFormat wrappers for Hadoop {@link
* org.apache.hadoop.mapred.InputFormat} and {@link org.apache.hadoop.mapreduce.InputFormat}.
*
* <p>Key value pairs produced by the Hadoop InputFormats are converted into Flink {@link
* org.apache.flink.api.java.tuple.Tuple2 Tuple2} objects where the first field ({@link
* org.apache.flink.api.java.tuple.Tuple2#f0 Tuple2.f0}) is the key and the second field ({@link
* org.apache.flink.api.java.tuple.Tuple2#f1 Tuple2.f1}) is the value.
*/
public final | to |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/indices/recovery/PeerRecoveryTargetService.java | {
"start": 34714,
"end": 36313
} | class ____ extends RecoveryRequestHandler<RecoveryFileChunkRequest> {
// How many bytes we've copied since we last called RateLimiter.pause
final AtomicLong bytesSinceLastPause = new AtomicLong();
@Override
protected void handleRequest(RecoveryFileChunkRequest request, RecoveryTarget target, ActionListener<Void> listener)
throws IOException {
final RecoveryState.Index indexState = target.state().getIndex();
if (request.sourceThrottleTimeInNanos() != RecoveryState.Index.UNKNOWN) {
indexState.addSourceThrottling(request.sourceThrottleTimeInNanos());
}
RateLimiter rateLimiter = recoverySettings.rateLimiter();
if (rateLimiter != null) {
long bytes = bytesSinceLastPause.addAndGet(request.content().length());
if (bytes > rateLimiter.getMinPauseCheckBytes()) {
// Time to pause
bytesSinceLastPause.addAndGet(-bytes);
long throttleTimeInNanos = rateLimiter.pause(bytes);
indexState.addTargetThrottling(throttleTimeInNanos);
target.indexShard().recoveryStats().addThrottleTime(throttleTimeInNanos);
}
}
target.writeFileChunk(
request.metadata(),
request.position(),
request.content(),
request.lastChunk(),
request.totalTranslogOps(),
listener
);
}
}
| FileChunkTransportRequestHandler |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/inotify/Event.java | {
"start": 2883,
"end": 2929
} | class ____ extends Event {
public | CreateEvent |
java | elastic__elasticsearch | x-pack/plugin/security/qa/security-trial/src/javaRestTest/java/org/elasticsearch/xpack/security/SecurityOnTrialLicenseRestTestCase.java | {
"start": 1763,
"end": 9411
} | class ____ extends ESRestTestCase {
private TestSecurityClient securityClient;
public static LocalClusterConfigProvider commonTrialSecurityClusterConfig = cluster -> cluster.nodes(2)
.distribution(DistributionType.DEFAULT)
.setting("xpack.ml.enabled", "false")
.setting("xpack.license.self_generated.type", "trial")
.setting("xpack.security.enabled", "true")
.setting("xpack.security.ssl.diagnose.trust", "true")
.setting("xpack.security.http.ssl.enabled", "false")
.setting("xpack.security.transport.ssl.enabled", "false")
.setting("xpack.security.authc.token.enabled", "true")
.setting("xpack.security.authc.api_key.enabled", "true")
.setting("xpack.security.remote_cluster_client.ssl.enabled", "false")
.keystore("cluster.remote.my_remote_cluster_a.credentials", "cluster_a_credentials")
.keystore("cluster.remote.my_remote_cluster_b.credentials", "cluster_b_credentials")
.keystore("cluster.remote.my_remote_cluster_a_1.credentials", "cluster_a_credentials")
.keystore("cluster.remote.my_remote_cluster_a_2.credentials", "cluster_a_credentials")
.rolesFile(Resource.fromClasspath("roles.yml"))
.user("admin_user", "admin-password", ROOT_USER_ROLE, true)
.user("security_test_user", "security-test-password", "security_test_role", false)
.user("x_pack_rest_user", "x-pack-test-password", ROOT_USER_ROLE, true)
.user("cat_test_user", "cat-test-password", "cat_test_role", false);
@ClassRule
public static ElasticsearchCluster cluster = ElasticsearchCluster.local().apply(commonTrialSecurityClusterConfig).build();
@Override
protected String getTestRestCluster() {
return cluster.getHttpAddresses();
}
@Override
protected Settings restAdminSettings() {
String token = basicAuthHeaderValue("admin_user", new SecureString("admin-password".toCharArray()));
return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build();
}
@Override
protected Settings restClientSettings() {
String token = basicAuthHeaderValue("security_test_user", new SecureString("security-test-password".toCharArray()));
return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build();
}
protected TestSecurityClient getSecurityClient() {
if (securityClient == null) {
securityClient = new TestSecurityClient(adminClient());
}
return securityClient;
}
protected void createUser(String username, SecureString password, List<String> roles) throws IOException {
getSecurityClient().putUser(new User(username, roles.toArray(String[]::new)), password);
}
protected void createRole(String name, Collection<String> clusterPrivileges) throws IOException {
final RoleDescriptor role = new RoleDescriptor(
name,
clusterPrivileges.toArray(String[]::new),
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
);
getSecurityClient().putRole(role);
}
/**
* @return A tuple of (access-token, refresh-token)
*/
protected Tuple<String, String> createOAuthToken(String username, SecureString password) throws IOException {
final TestSecurityClient securityClient = new TestSecurityClient(adminClient());
final TestSecurityClient.OAuth2Token token = securityClient.createToken(
new UsernamePasswordToken(username, new SecureString(password.getChars()))
);
return new Tuple<>(token.accessToken(), token.getRefreshToken());
}
protected void deleteUser(String username) throws IOException {
getSecurityClient().deleteUser(username);
}
protected void deleteRole(String name) throws IOException {
getSecurityClient().deleteRole(name);
}
protected void invalidateApiKeysForUser(String username) throws IOException {
getSecurityClient().invalidateApiKeysForUser(username);
}
protected ApiKey getApiKey(String id) throws IOException {
final TestSecurityClient client = getSecurityClient();
return client.getApiKey(id);
}
protected void upsertRole(String roleDescriptor, String roleName) throws IOException {
Request createRoleRequest = roleRequest(roleDescriptor, roleName);
Response createRoleResponse = adminClient().performRequest(createRoleRequest);
assertOK(createRoleResponse);
}
protected Request roleRequest(String roleDescriptor, String roleName) {
Request createRoleRequest;
if (randomBoolean()) {
createRoleRequest = new Request(randomFrom(HttpPut.METHOD_NAME, HttpPost.METHOD_NAME), "/_security/role/" + roleName);
createRoleRequest.setJsonEntity(roleDescriptor);
} else {
createRoleRequest = new Request(HttpPost.METHOD_NAME, "/_security/role");
createRoleRequest.setJsonEntity(Strings.format("""
{"roles": {"%s": %s}}
""", roleName, roleDescriptor));
}
return createRoleRequest;
}
@SuppressWarnings("unchecked")
protected void assertSendRequestThrowsError(Request request, String expectedError) throws IOException {
String errorMessage;
if (request.getEndpoint().endsWith("/role")) {
Map<String, Object> response = responseAsMap(adminClient().performRequest(request));
Map<String, Object> errors = (Map<String, Object>) response.get("errors");
Map<String, Object> failedItems = (Map<String, Object>) errors.get("details");
assertEquals(failedItems.size(), 1);
Map<String, Object> error = (Map<String, Object>) failedItems.values().stream().findFirst().orElseThrow();
errorMessage = (String) error.get("reason");
} else {
ResponseException e = expectThrows(ResponseException.class, () -> adminClient().performRequest(request));
assertEquals(400, e.getResponse().getStatusLine().getStatusCode());
errorMessage = e.getMessage();
}
assertThat(errorMessage, containsString(expectedError));
}
protected void fetchRoleAndAssertEqualsExpected(final String roleName, final RoleDescriptor expectedRoleDescriptor) throws IOException {
final Response getRoleResponse = adminClient().performRequest(new Request("GET", "/_security/role/" + roleName));
assertOK(getRoleResponse);
final Map<String, RoleDescriptor> actual = responseAsParser(getRoleResponse).map(
HashMap::new,
p -> RoleDescriptor.parserBuilder().allowDescription(true).build().parse(expectedRoleDescriptor.getName(), p)
);
assertThat(actual, equalTo(Map.of(expectedRoleDescriptor.getName(), expectedRoleDescriptor)));
}
protected Map<String, Object> upsertRoles(String roleDescriptorsByName) throws IOException {
Request request = rolesRequest(roleDescriptorsByName);
Response response = adminClient().performRequest(request);
assertOK(response);
return responseAsMap(response);
}
protected Request rolesRequest(String roleDescriptorsByName) {
Request rolesRequest;
rolesRequest = new Request(HttpPost.METHOD_NAME, "/_security/role");
rolesRequest.setJsonEntity(org.elasticsearch.core.Strings.format(roleDescriptorsByName));
return rolesRequest;
}
}
| SecurityOnTrialLicenseRestTestCase |
java | apache__camel | components/camel-smpp/src/test/java/org/apache/camel/component/smpp/SmppConsumerTest.java | {
"start": 2297,
"end": 2376
} | class ____ <code>org.apache.camel.component.smpp.SmppConsumer</code>
*/
public | for |
java | spring-projects__spring-boot | module/spring-boot-graphql/src/main/java/org/springframework/boot/graphql/autoconfigure/security/GraphQlWebMvcSecurityAutoConfiguration.java | {
"start": 2081,
"end": 2301
} | class ____ {
@Bean
@ConditionalOnMissingBean
SecurityDataFetcherExceptionResolver securityDataFetcherExceptionResolver() {
return new SecurityDataFetcherExceptionResolver();
}
}
| GraphQlWebMvcSecurityAutoConfiguration |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/GaloisField.java | {
"start": 1193,
"end": 17867
} | class ____ {
// Field size 256 is good for byte based system
private static final int DEFAULT_FIELD_SIZE = 256;
// primitive polynomial 1 + X^2 + X^3 + X^4 + X^8 (substitute 2)
private static final int DEFAULT_PRIMITIVE_POLYNOMIAL = 285;
static private final Map<Integer, GaloisField> instances =
new HashMap<Integer, GaloisField>();
private final int[] logTable;
private final int[] powTable;
private final int[][] mulTable;
private final int[][] divTable;
private final int fieldSize;
private final int primitivePeriod;
private final int primitivePolynomial;
private GaloisField(int fieldSize, int primitivePolynomial) {
assert fieldSize > 0;
assert primitivePolynomial > 0;
this.fieldSize = fieldSize;
this.primitivePeriod = fieldSize - 1;
this.primitivePolynomial = primitivePolynomial;
logTable = new int[fieldSize];
powTable = new int[fieldSize];
mulTable = new int[fieldSize][fieldSize];
divTable = new int[fieldSize][fieldSize];
int value = 1;
for (int pow = 0; pow < fieldSize - 1; pow++) {
powTable[pow] = value;
logTable[value] = pow;
value = value * 2;
if (value >= fieldSize) {
value = value ^ primitivePolynomial;
}
}
// building multiplication table
for (int i = 0; i < fieldSize; i++) {
for (int j = 0; j < fieldSize; j++) {
if (i == 0 || j == 0) {
mulTable[i][j] = 0;
continue;
}
int z = logTable[i] + logTable[j];
z = z >= primitivePeriod ? z - primitivePeriod : z;
z = powTable[z];
mulTable[i][j] = z;
}
}
// building division table
for (int i = 0; i < fieldSize; i++) {
for (int j = 1; j < fieldSize; j++) {
if (i == 0) {
divTable[i][j] = 0;
continue;
}
int z = logTable[i] - logTable[j];
z = z < 0 ? z + primitivePeriod : z;
z = powTable[z];
divTable[i][j] = z;
}
}
}
/**
* Get the object performs Galois field arithmetics.
*
* @param fieldSize size of the field
* @param primitivePolynomial a primitive polynomial corresponds to the size
* @return GaloisField.
*/
public static GaloisField getInstance(int fieldSize,
int primitivePolynomial) {
int key = ((fieldSize << 16) & 0xFFFF0000)
+ (primitivePolynomial & 0x0000FFFF);
GaloisField gf;
synchronized (instances) {
gf = instances.get(key);
if (gf == null) {
gf = new GaloisField(fieldSize, primitivePolynomial);
instances.put(key, gf);
}
}
return gf;
}
/**
* Get the object performs Galois field arithmetic with default setting.
* @return GaloisField.
*/
public static GaloisField getInstance() {
return getInstance(DEFAULT_FIELD_SIZE, DEFAULT_PRIMITIVE_POLYNOMIAL);
}
/**
* Return number of elements in the field
*
* @return number of elements in the field
*/
public int getFieldSize() {
return fieldSize;
}
/**
* Return the primitive polynomial in GF(2)
*
* @return primitive polynomial as a integer
*/
public int getPrimitivePolynomial() {
return primitivePolynomial;
}
/**
* Compute the sum of two fields
*
* @param x input field
* @param y input field
* @return result of addition
*/
public int add(int x, int y) {
assert (x >= 0 && x < getFieldSize() && y >= 0 && y < getFieldSize());
return x ^ y;
}
/**
* Compute the multiplication of two fields
*
* @param x input field
* @param y input field
* @return result of multiplication
*/
public int multiply(int x, int y) {
assert (x >= 0 && x < getFieldSize() && y >= 0 && y < getFieldSize());
return mulTable[x][y];
}
/**
* Compute the division of two fields
*
* @param x input field
* @param y input field
* @return x/y
*/
public int divide(int x, int y) {
assert (x >= 0 && x < getFieldSize() && y > 0 && y < getFieldSize());
return divTable[x][y];
}
/**
* Compute power n of a field
*
* @param x input field
* @param n power
* @return x^n
*/
public int power(int x, int n) {
assert (x >= 0 && x < getFieldSize());
if (n == 0) {
return 1;
}
if (x == 0) {
return 0;
}
x = logTable[x] * n;
if (x < primitivePeriod) {
return powTable[x];
}
x = x % primitivePeriod;
return powTable[x];
}
/**
* Given a Vandermonde matrix V[i][j]=x[j]^i and vector y, solve for z such
* that Vz=y. The output z will be placed in y.
*
* @param x the vector which describe the Vandermonde matrix
* @param y right-hand side of the Vandermonde system equation. will be
* replaced the output in this vector
*/
public void solveVandermondeSystem(int[] x, int[] y) {
solveVandermondeSystem(x, y, x.length);
}
/**
* Given a Vandermonde matrix V[i][j]=x[j]^i and vector y, solve for z such
* that Vz=y. The output z will be placed in y.
*
* @param x the vector which describe the Vandermonde matrix
* @param y right-hand side of the Vandermonde system equation. will be
* replaced the output in this vector
* @param len consider x and y only from 0...len-1
*/
public void solveVandermondeSystem(int[] x, int[] y, int len) {
assert (x.length <= len && y.length <= len);
for (int i = 0; i < len - 1; i++) {
for (int j = len - 1; j > i; j--) {
y[j] = y[j] ^ mulTable[x[i]][y[j - 1]];
}
}
for (int i = len - 1; i >= 0; i--) {
for (int j = i + 1; j < len; j++) {
y[j] = divTable[y[j]][x[j] ^ x[j - i - 1]];
}
for (int j = i; j < len - 1; j++) {
y[j] = y[j] ^ y[j + 1];
}
}
}
/**
* A "bulk" version to the solving of Vandermonde System.
*
* @param x input x.
* @param y input y.
* @param outputOffsets input outputOffsets.
* @param len input len.
* @param dataLen input dataLen.
*/
public void solveVandermondeSystem(int[] x, byte[][] y, int[] outputOffsets,
int len, int dataLen) {
int idx1, idx2;
for (int i = 0; i < len - 1; i++) {
for (int j = len - 1; j > i; j--) {
for (idx2 = outputOffsets[j-1], idx1 = outputOffsets[j];
idx1 < outputOffsets[j] + dataLen; idx1++, idx2++) {
y[j][idx1] = (byte) (y[j][idx1] ^ mulTable[x[i]][y[j - 1][idx2] &
0x000000FF]);
}
}
}
for (int i = len - 1; i >= 0; i--) {
for (int j = i + 1; j < len; j++) {
for (idx1 = outputOffsets[j];
idx1 < outputOffsets[j] + dataLen; idx1++) {
y[j][idx1] = (byte) (divTable[y[j][idx1] & 0x000000FF][x[j] ^
x[j - i - 1]]);
}
}
for (int j = i; j < len - 1; j++) {
for (idx2 = outputOffsets[j+1], idx1 = outputOffsets[j];
idx1 < outputOffsets[j] + dataLen; idx1++, idx2++) {
y[j][idx1] = (byte) (y[j][idx1] ^ y[j + 1][idx2]);
}
}
}
}
/**
* A "bulk" version of the solveVandermondeSystem, using ByteBuffer.
*
* @param x input x.
* @param y input y.
* @param len input len.
*/
public void solveVandermondeSystem(int[] x, ByteBuffer[] y, int len) {
ByteBuffer p;
int idx1, idx2;
for (int i = 0; i < len - 1; i++) {
for (int j = len - 1; j > i; j--) {
p = y[j];
for (idx1 = p.position(), idx2 = y[j-1].position();
idx1 < p.limit(); idx1++, idx2++) {
p.put(idx1, (byte) (p.get(idx1) ^ mulTable[x[i]][y[j-1].get(idx2) &
0x000000FF]));
}
}
}
for (int i = len - 1; i >= 0; i--) {
for (int j = i + 1; j < len; j++) {
p = y[j];
for (idx1 = p.position(); idx1 < p.limit(); idx1++) {
p.put(idx1, (byte) (divTable[p.get(idx1) &
0x000000FF][x[j] ^ x[j - i - 1]]));
}
}
for (int j = i; j < len - 1; j++) {
p = y[j];
for (idx1 = p.position(), idx2 = y[j+1].position();
idx1 < p.limit(); idx1++, idx2++) {
p.put(idx1, (byte) (p.get(idx1) ^ y[j+1].get(idx2)));
}
}
}
}
/**
* Compute the multiplication of two polynomials. The index in the array
* corresponds to the power of the entry. For example p[0] is the constant
* term of the polynomial p.
*
* @param p input polynomial
* @param q input polynomial
* @return polynomial represents p*q
*/
public int[] multiply(int[] p, int[] q) {
int len = p.length + q.length - 1;
int[] result = new int[len];
for (int i = 0; i < len; i++) {
result[i] = 0;
}
for (int i = 0; i < p.length; i++) {
for (int j = 0; j < q.length; j++) {
result[i + j] = add(result[i + j], multiply(p[i], q[j]));
}
}
return result;
}
/**
* Compute the remainder of a dividend and divisor pair. The index in the
* array corresponds to the power of the entry. For example p[0] is the
* constant term of the polynomial p.
*
* @param dividend dividend polynomial, the remainder will be placed
* here when return
* @param divisor divisor polynomial
*/
public void remainder(int[] dividend, int[] divisor) {
for (int i = dividend.length - divisor.length; i >= 0; i--) {
int ratio = divTable[dividend[i +
divisor.length - 1]][divisor[divisor.length - 1]];
for (int j = 0; j < divisor.length; j++) {
int k = j + i;
dividend[k] = dividend[k] ^ mulTable[ratio][divisor[j]];
}
}
}
/**
* Compute the sum of two polynomials. The index in the array corresponds to
* the power of the entry. For example p[0] is the constant term of the
* polynomial p.
*
* @param p input polynomial
* @param q input polynomial
* @return polynomial represents p+q
*/
public int[] add(int[] p, int[] q) {
int len = Math.max(p.length, q.length);
int[] result = new int[len];
for (int i = 0; i < len; i++) {
if (i < p.length && i < q.length) {
result[i] = add(p[i], q[i]);
} else if (i < p.length) {
result[i] = p[i];
} else {
result[i] = q[i];
}
}
return result;
}
/**
* Substitute x into polynomial p(x).
*
* @param p input polynomial
* @param x input field
* @return p(x)
*/
public int substitute(int[] p, int x) {
int result = 0;
int y = 1;
for (int i = 0; i < p.length; i++) {
result = result ^ mulTable[p[i]][y];
y = mulTable[x][y];
}
return result;
}
/**
* A "bulk" version of the substitute.
* Tends to be 2X faster than the "int" substitute in a loop.
*
* @param p input polynomial
* @param q store the return result
* @param x input field
*/
public void substitute(byte[][] p, byte[] q, int x) {
int y = 1;
for (int i = 0; i < p.length; i++) {
byte[] pi = p[i];
for (int j = 0; j < pi.length; j++) {
int pij = pi[j] & 0x000000FF;
q[j] = (byte) (q[j] ^ mulTable[pij][y]);
}
y = mulTable[x][y];
}
}
/**
* A "bulk" version of the substitute.
* Tends to be 2X faster than the "int" substitute in a loop.
*
* @param p input polynomial
* @param offsets input offset.
* @param len input len.
* @param q store the return result
* @param offset input offset.
* @param x input field
*/
public void substitute(byte[][] p, int[] offsets,
int len, byte[] q, int offset, int x) {
int y = 1, iIdx, oIdx;
for (int i = 0; i < p.length; i++) {
byte[] pi = p[i];
for (iIdx = offsets[i], oIdx = offset;
iIdx < offsets[i] + len; iIdx++, oIdx++) {
int pij = pi != null ? pi[iIdx] & 0x000000FF : 0;
q[oIdx] = (byte) (q[oIdx] ^ mulTable[pij][y]);
}
y = mulTable[x][y];
}
}
/**
* A "bulk" version of the substitute, using ByteBuffer.
* Tends to be 2X faster than the "int" substitute in a loop.
*
* @param p input polynomial
* @param q store the return result
* @param x input field
* @param len input len.
*/
public void substitute(ByteBuffer[] p, int len, ByteBuffer q, int x) {
int y = 1, iIdx, oIdx;
for (int i = 0; i < p.length; i++) {
ByteBuffer pi = p[i];
int pos = pi != null ? pi.position() : 0;
int limit = pi != null ? pi.limit() : len;
for (oIdx = q.position(), iIdx = pos;
iIdx < limit; iIdx++, oIdx++) {
int pij = pi != null ? pi.get(iIdx) & 0x000000FF : 0;
q.put(oIdx, (byte) (q.get(oIdx) ^ mulTable[pij][y]));
}
y = mulTable[x][y];
}
}
/**
* The "bulk" version of the remainder.
* Warning: This function will modify the "dividend" inputs.
*
* @param divisor divisor.
* @param dividend dividend.
*/
public void remainder(byte[][] dividend, int[] divisor) {
for (int i = dividend.length - divisor.length; i >= 0; i--) {
for (int j = 0; j < divisor.length; j++) {
for (int k = 0; k < dividend[i].length; k++) {
int ratio = divTable[dividend[i + divisor.length - 1][k] &
0x00FF][divisor[divisor.length - 1]];
dividend[j + i][k] = (byte) ((dividend[j + i][k] & 0x00FF) ^
mulTable[ratio][divisor[j]]);
}
}
}
}
/**
* The "bulk" version of the remainder.
* Warning: This function will modify the "dividend" inputs.
*
* @param dividend dividend.
* @param offsets offsets.
* @param len len.
* @param divisor divisor.
*/
public void remainder(byte[][] dividend, int[] offsets,
int len, int[] divisor) {
int idx1, idx2;
for (int i = dividend.length - divisor.length; i >= 0; i--) {
for (int j = 0; j < divisor.length; j++) {
for (idx2 = offsets[j + i], idx1 = offsets[i + divisor.length - 1];
idx1 < offsets[i + divisor.length - 1] + len;
idx1++, idx2++) {
int ratio = divTable[dividend[i + divisor.length - 1][idx1] &
0x00FF][divisor[divisor.length - 1]];
dividend[j + i][idx2] = (byte) ((dividend[j + i][idx2] & 0x00FF) ^
mulTable[ratio][divisor[j]]);
}
}
}
}
/**
* The "bulk" version of the remainder, using ByteBuffer.
* Warning: This function will modify the "dividend" inputs.
*
* @param dividend dividend.
* @param divisor divisor.
*/
public void remainder(ByteBuffer[] dividend, int[] divisor) {
int idx1, idx2;
ByteBuffer b1, b2;
for (int i = dividend.length - divisor.length; i >= 0; i--) {
for (int j = 0; j < divisor.length; j++) {
b1 = dividend[i + divisor.length - 1];
b2 = dividend[j + i];
for (idx1 = b1.position(), idx2 = b2.position();
idx1 < b1.limit(); idx1++, idx2++) {
int ratio = divTable[b1.get(idx1) &
0x00FF][divisor[divisor.length - 1]];
b2.put(idx2, (byte) ((b2.get(idx2) & 0x00FF) ^
mulTable[ratio][divisor[j]]));
}
}
}
}
/**
* Perform Gaussian elimination on the given matrix. This matrix has to be a
* fat matrix (number of rows > number of columns).
*
* @param matrix matrix.
*/
public void gaussianElimination(int[][] matrix) {
assert(matrix != null && matrix.length > 0 && matrix[0].length > 0
&& matrix.length < matrix[0].length);
int height = matrix.length;
int width = matrix[0].length;
for (int i = 0; i < height; i++) {
boolean pivotFound = false;
// scan the column for a nonzero pivot and swap it to the diagonal
for (int j = i; j < height; j++) {
if (matrix[i][j] != 0) {
int[] tmp = matrix[i];
matrix[i] = matrix[j];
matrix[j] = tmp;
pivotFound = true;
break;
}
}
if (!pivotFound) {
continue;
}
int pivot = matrix[i][i];
for (int j = i; j < width; j++) {
matrix[i][j] = divide(matrix[i][j], pivot);
}
for (int j = i + 1; j < height; j++) {
int lead = matrix[j][i];
for (int k = i; k < width; k++) {
matrix[j][k] = add(matrix[j][k], multiply(lead, matrix[i][k]));
}
}
}
for (int i = height - 1; i >=0; i--) {
for (int j = 0; j < i; j++) {
int lead = matrix[j][i];
for (int k = i; k < width; k++) {
matrix[j][k] = add(matrix[j][k], multiply(lead, matrix[i][k]));
}
}
}
}
}
| GaloisField |
java | apache__kafka | server/src/main/java/org/apache/kafka/server/logger/NoOpController.java | {
"start": 863,
"end": 1220
} | class ____ implements LoggingControllerDelegate {
@Override
public Map<String, String> loggers() {
return Map.of();
}
@Override
public boolean logLevel(String loggerName, String logLevel) {
return false;
}
@Override
public boolean unsetLogLevel(String loggerName) {
return false;
}
}
| NoOpController |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/ComparatorFactory_doubleComparatorWithPrecision_Test.java | {
"start": 1264,
"end": 4118
} | class ____ {
private final ComparatorFactory INSTANCE = ComparatorFactory.INSTANCE;
@ParameterizedTest
@CsvSource({
"1.0, 1.1, 0.1",
"0.111, 0.110, 0.001",
"0.12345, 0.12346, 0.00001",
"0.7654321, 0.7654320, 0.0000001",
"1.2464, 1.2463, 0.0001" })
void should_evaluate_to_be_equal(Double double1, Double double2, Double precision) {
// GIVEN
Comparator<Double> comparator = INSTANCE.doubleComparatorWithPrecision(precision);
// WHEN
int comparisonValue = comparator.compare(double1, double2);
int inverseComparisonValue = comparator.compare(double2, double1);
// THEN
then(comparisonValue).isZero();
then(inverseComparisonValue).isZero();
}
@ParameterizedTest
@CsvSource({
"1.1, 1.0, 0.05",
"0.111, 0.110, 0.00099",
"0.12346, 0.12345, 0.0000099",
"0.7654321, 0.7654320, 0.000000099",
"0.7654321, 0.7654320, 9e-8",
"1.2464, 1.2463, 0.000099" })
void should_evaluate_given_value_to_different(Double value, Double other, Double precision) {
// GIVEN
Comparator<Double> comparator = INSTANCE.doubleComparatorWithPrecision(precision);
// WHEN
int comparisonValue = comparator.compare(value, other);
int inverseComparisonValue = comparator.compare(other, value);
// THEN
then(comparisonValue).isOne();
then(inverseComparisonValue).isEqualTo(-1);
}
@ParameterizedTest
@MethodSource
void should_follow_java_behavior_when_dealing_with_infinity_and_NaN(Double value1, Double value2) {
// GIVEN
Comparator<Double> comparator = INSTANCE.doubleComparatorWithPrecision(1d);
// WHEN
int comparisonValue = comparator.compare(value1, value2);
int javaComparisonValue = value1.compareTo(value2);
// THEN
then(comparisonValue).isEqualTo(javaComparisonValue);
}
static Stream<Arguments> should_follow_java_behavior_when_dealing_with_infinity_and_NaN() {
return Stream.of(arguments(POSITIVE_INFINITY, NEGATIVE_INFINITY),
arguments(NEGATIVE_INFINITY, POSITIVE_INFINITY),
arguments(POSITIVE_INFINITY, POSITIVE_INFINITY),
arguments(NEGATIVE_INFINITY, NEGATIVE_INFINITY),
arguments(NaN, POSITIVE_INFINITY),
arguments(NaN, NEGATIVE_INFINITY),
arguments(NaN, NaN));
}
@ParameterizedTest
@MethodSource
void should_fail_for_invalid_precision(Double precision) {
// GIVEN
Comparator<Double> comparator = INSTANCE.doubleComparatorWithPrecision(precision);
// WHEN/THEN
assertThatIllegalArgumentException().isThrownBy(() -> comparator.compare(1d, 2d));
}
static Stream<Double> should_fail_for_invalid_precision() {
return Stream.of(NaN, POSITIVE_INFINITY, NEGATIVE_INFINITY);
}
}
| ComparatorFactory_doubleComparatorWithPrecision_Test |
java | apache__camel | components/camel-jira/src/main/java/org/apache/camel/component/jira/oauth/OAuthHttpClientDecorator.java | {
"start": 1463,
"end": 3565
} | class ____ implements DisposableHttpClient {
private final HttpClient httpClient;
private final AuthenticationHandler authenticationHandler;
private URI uri;
protected OAuthHttpClientDecorator(HttpClient httpClient, AuthenticationHandler authenticationHandler) {
this.httpClient = httpClient;
this.authenticationHandler = authenticationHandler;
}
@Override
public void flushCacheByUriPattern(Pattern urlPattern) {
httpClient.flushCacheByUriPattern(urlPattern);
}
@Override
public Request.Builder newRequest() {
return new OAuthAuthenticatedRequestBuilder();
}
@Override
public Request.Builder newRequest(URI uri) {
final Request.Builder builder = new OAuthAuthenticatedRequestBuilder();
builder.setUri(uri);
this.uri = uri;
return builder;
}
@Override
public Request.Builder newRequest(URI uri, String contentType, String entity) {
final Request.Builder builder = new OAuthAuthenticatedRequestBuilder();
this.uri = uri;
builder.setUri(uri);
builder.setContentType(contentType);
builder.setEntity(entity);
return builder;
}
@Override
public Request.Builder newRequest(String uri) {
final Request.Builder builder = new OAuthAuthenticatedRequestBuilder();
this.uri = URI.create(uri);
builder.setUri(this.uri);
return builder;
}
@Override
public Request.Builder newRequest(String uri, String contentType, String entity) {
final Request.Builder builder = new OAuthAuthenticatedRequestBuilder();
this.uri = URI.create(uri);
builder.setUri(this.uri);
builder.setContentType(contentType);
builder.setEntity(entity);
return builder;
}
@Override
public <A> ResponseTransformation.Builder<A> transformation() {
return httpClient.transformation();
}
@Override
public ResponsePromise execute(Request request) {
return httpClient.execute(request);
}
public | OAuthHttpClientDecorator |
java | quarkusio__quarkus | extensions/websockets-next/runtime/src/main/java/io/quarkus/websockets/next/CloseReason.java | {
"start": 546,
"end": 2034
} | class ____ {
public static final CloseReason NORMAL = new CloseReason(WebSocketCloseStatus.NORMAL_CLOSURE.code());
public static final CloseReason ABNORMAL = new CloseReason(WebSocketCloseStatus.ABNORMAL_CLOSURE.code(), null, false);
public static final CloseReason EMPTY = new CloseReason(WebSocketCloseStatus.EMPTY.code(), null, false);
public static final CloseReason INTERNAL_SERVER_ERROR = new CloseReason(WebSocketCloseStatus.INTERNAL_SERVER_ERROR.code());
private final int code;
private final String message;
private CloseReason(int code, String message, boolean validate) {
if (validate && !WebSocketCloseStatus.isValidStatusCode(code)) {
throw new IllegalArgumentException("Invalid status code: " + code);
}
this.code = code;
this.message = message;
}
/**
*
* @param code The status code must comply with RFC-6455
*/
public CloseReason(int code) {
this(code, null, true);
}
/**
*
* @param code The status code must comply with RFC-6455
* @param message
*/
public CloseReason(int code, String message) {
this(code, message, true);
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
@Override
public String toString() {
return "CloseReason [code=" + code + ", " + (message != null ? "message=" + message : "") + "]";
}
}
| CloseReason |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/component/instance/ComponentInstance.java | {
"start": 12289,
"end": 14439
} | class ____ implements
MultipleArcTransition<ComponentInstance, ComponentInstanceEvent,
ComponentInstanceState> {
@Override
public ComponentInstanceState transition(ComponentInstance instance,
ComponentInstanceEvent event) {
if (instance.pendingCancelUpgrade) {
// cancellation of upgrade was triggered before the upgrade was
// finished.
LOG.info("{} received started but cancellation pending",
event.getContainerId());
instance.upgradeInProgress.set(true);
instance.cancelUpgrade();
instance.pendingCancelUpgrade = false;
return instance.getState();
}
instance.upgradeInProgress.set(false);
instance.setContainerState(ContainerState.RUNNING_BUT_UNREADY);
if (instance.component.getProbe() != null &&
instance.component.getProbe() instanceof DefaultProbe) {
instance.initializeStatusRetriever(event, 30);
} else {
instance.initializeStatusRetriever(event, 0);
}
instance.initializeLocalizationStatusRetriever(event.getContainerId());
Component.UpgradeStatus status = instance.getState().equals(UPGRADING) ?
instance.component.getUpgradeStatus() :
instance.component.getCancelUpgradeStatus();
status.decContainersThatNeedUpgrade();
instance.serviceVersion = status.getTargetVersion();
return ComponentInstanceState.REINITIALIZED;
}
}
private void postContainerReady() {
if (timelineServiceEnabled) {
serviceTimelinePublisher.componentInstanceBecomeReady(containerSpec);
}
try {
List<org.apache.hadoop.yarn.api.records.LocalizationStatus>
statusesFromNM = scheduler.getNmClient().getClient()
.getLocalizationStatuses(container.getId(), container.getNodeId());
if (statusesFromNM != null && !statusesFromNM.isEmpty()) {
updateLocalizationStatuses(statusesFromNM);
}
} catch (YarnException | IOException e) {
LOG.warn("{} failure getting localization statuses", container.getId(),
e);
}
}
private static | StartedAfterUpgradeTransition |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationFailureHandlerTests.java | {
"start": 1787,
"end": 4938
} | class ____ {
@Mock
private AuthenticationFailureHandler handler1;
@Mock
private AuthenticationFailureHandler handler2;
@Mock
private AuthenticationFailureHandler defaultHandler;
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
private LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> handlers;
private DelegatingAuthenticationFailureHandler handler;
@BeforeEach
public void setup() {
this.handlers = new LinkedHashMap<>();
}
@Test
public void handleByDefaultHandler() throws Exception {
this.handlers.put(BadCredentialsException.class, this.handler1);
this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler);
AuthenticationException exception = new AccountExpiredException("");
this.handler.onAuthenticationFailure(this.request, this.response, exception);
verifyNoMoreInteractions(this.handler1, this.handler2);
verify(this.defaultHandler).onAuthenticationFailure(this.request, this.response, exception);
}
@Test
public void handleByMappedHandlerWithSameType() throws Exception {
this.handlers.put(BadCredentialsException.class, this.handler1); // same type
this.handlers.put(AccountStatusException.class, this.handler2);
this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler);
AuthenticationException exception = new BadCredentialsException("");
this.handler.onAuthenticationFailure(this.request, this.response, exception);
verifyNoMoreInteractions(this.handler2, this.defaultHandler);
verify(this.handler1).onAuthenticationFailure(this.request, this.response, exception);
}
@Test
public void handleByMappedHandlerWithSuperType() throws Exception {
this.handlers.put(BadCredentialsException.class, this.handler1);
this.handlers.put(AccountStatusException.class, this.handler2); // super type of
// CredentialsExpiredException
this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler);
AuthenticationException exception = new CredentialsExpiredException("");
this.handler.onAuthenticationFailure(this.request, this.response, exception);
verifyNoMoreInteractions(this.handler1, this.defaultHandler);
verify(this.handler2).onAuthenticationFailure(this.request, this.response, exception);
}
@Test
public void handlersIsNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingAuthenticationFailureHandler(null, this.defaultHandler))
.withMessage("handlers cannot be null or empty");
}
@Test
public void handlersIsEmpty() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler))
.withMessage("handlers cannot be null or empty");
}
@Test
public void defaultHandlerIsNull() {
this.handlers.put(BadCredentialsException.class, this.handler1);
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingAuthenticationFailureHandler(this.handlers, null))
.withMessage("defaultHandler cannot be null");
}
}
| DelegatingAuthenticationFailureHandlerTests |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/steps/PreloadClassesBuildStep.java | {
"start": 679,
"end": 1583
} | class ____ {
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
public void preInit(Optional<PreloadClassesEnabledBuildItem> preload, PreloadClassesRecorder recorder) {
if (!preload.isPresent())
return;
recorder.invokePreloadClasses(preload.get().doInitialize());
}
@BuildStep
public GeneratedResourceBuildItem registerPreInitClasses(List<PreloadClassBuildItem> items) {
if (items == null || items.isEmpty())
return null;
// ensure unique & sorted
final String names = items.stream().map(PreloadClassBuildItem::getClassName).sorted().distinct()
.map(s -> s.concat(System.lineSeparator())).collect(Collectors.joining());
return new GeneratedResourceBuildItem("META-INF/" + QUARKUS_GENERATED_PRELOAD_CLASSES_FILE,
names.getBytes(StandardCharsets.UTF_8));
}
}
| PreloadClassesBuildStep |
java | micronaut-projects__micronaut-core | http/src/main/java/io/micronaut/http/body/ResponseBodyWriterWrapper.java | {
"start": 1521,
"end": 3808
} | class ____<T> implements ResponseBodyWriter<T> {
private final MessageBodyWriter<T> wrapped;
ResponseBodyWriterWrapper(MessageBodyWriter<T> wrapped) {
this.wrapped = wrapped;
}
@Override
public boolean isWriteable(@NonNull Argument<T> type, @Nullable MediaType mediaType) {
return wrapped.isWriteable(type, mediaType);
}
@Override
public MessageBodyWriter<T> createSpecific(@NonNull Argument<T> type) {
return wrapped.createSpecific(type);
}
@Override
public boolean isBlocking() {
return wrapped.isBlocking();
}
@Override
public void writeTo(@NonNull Argument<T> type, @NonNull MediaType mediaType, T object, @NonNull MutableHeaders outgoingHeaders, @NonNull OutputStream outputStream) throws CodecException {
wrapped.writeTo(type, mediaType, object, outgoingHeaders, outputStream);
}
@Override
public @NonNull ByteBuffer<?> writeTo(@NonNull Argument<T> type, @NonNull MediaType mediaType, T object, @NonNull MutableHeaders outgoingHeaders, @NonNull ByteBufferFactory<?, ?> bufferFactory) throws CodecException {
return wrapped.writeTo(type, mediaType, object, outgoingHeaders, bufferFactory);
}
@Override
public @NonNull ByteBodyHttpResponse<?> write(@NonNull ByteBodyFactory bodyFactory, @NonNull HttpRequest<?> request, @NonNull MutableHttpResponse<T> httpResponse, @NonNull Argument<T> type, @NonNull MediaType mediaType, T object) throws CodecException {
return ByteBodyHttpResponseWrapper.wrap(httpResponse, writePiece(bodyFactory, httpResponse.getHeaders(), type, mediaType, object));
}
@Override
public CloseableByteBody writePiece(@NonNull ByteBodyFactory bodyFactory, @NonNull HttpRequest<?> request, @NonNull HttpResponse<?> response, @NonNull Argument<T> type, @NonNull MediaType mediaType, T object) {
return writePiece(bodyFactory, response.toMutableResponse().getHeaders(), type, mediaType, object);
}
private @NonNull CloseableByteBody writePiece(@NonNull ByteBodyFactory bodyFactory, MutableHttpHeaders headers, @NonNull Argument<T> type, @NonNull MediaType mediaType, T object) {
return bodyFactory.buffer(s -> writeTo(type, mediaType, object, headers, s));
}
}
| ResponseBodyWriterWrapper |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/RecipientListBeanSubUnitOfWorkTest.java | {
"start": 1115,
"end": 3105
} | class ____ extends ContextTestSupport {
private static int counter;
@Test
public void testOK() throws Exception {
counter = 0;
getMockEndpoint("mock:dead").expectedMessageCount(0);
getMockEndpoint("mock:start").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:a").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:b").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
template.sendBodyAndHeader("direct:start", "Hello World", "foo", "direct:a,direct:b");
assertMockEndpointsSatisfied();
}
@Test
public void testError() throws Exception {
counter = 0;
// the DLC should receive the original message which is Bye World
getMockEndpoint("mock:dead").expectedBodiesReceived("Bye World");
getMockEndpoint("mock:start").expectedBodiesReceived("Bye World");
getMockEndpoint("mock:a").expectedBodiesReceived("Donkey was here");
getMockEndpoint("mock:b").expectedMessageCount(0);
getMockEndpoint("mock:result").expectedMessageCount(0);
template.sendBodyAndHeader("direct:start", "Bye World", "foo", "direct:a,direct:b");
assertMockEndpointsSatisfied();
// 1 first + 3 redeliveries
assertEquals(4, counter);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
errorHandler(deadLetterChannel("mock:dead").useOriginalMessage().maximumRedeliveries(3).redeliveryDelay(0));
from("direct:start").to("mock:start").process(new MyPreProcessor()).bean(WhereToGoBean.class).to("mock:result");
from("direct:a").to("mock:a");
from("direct:b").process(new MyProcessor()).to("mock:b");
}
};
}
public static | RecipientListBeanSubUnitOfWorkTest |
java | micronaut-projects__micronaut-core | retry/src/main/java/io/micronaut/retry/annotation/CircuitBreaker.java | {
"start": 3084,
"end": 3707
} | class ____ use instead of {@link Retryable#includes} and {@link Retryable#excludes}
* (defaults to none)
*/
@AliasFor(annotation = Retryable.class, member = "predicate")
Class<? extends RetryPredicate> predicate() default DefaultRetryPredicate.class;
/**
* If {@code true} and the circuit is opened, it throws the original exception wrapped.
* in a {@link io.micronaut.retry.exception.CircuitOpenException}
*
* @return Whether to wrap the original exception in a {@link io.micronaut.retry.exception.CircuitOpenException}
*/
boolean throwWrappedException() default false;
}
| to |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/io/InputOutputITCase.java | {
"start": 1332,
"end": 1847
} | class ____ extends JavaProgramTestBaseJUnit4 {
@Override
protected void testProgram() throws Exception {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
TestNonRichOutputFormat output = new TestNonRichOutputFormat();
env.createInput(new TestNonRichInputFormat())
.addSink(new OutputFormatSinkFunction<>(output));
env.execute();
// we didn't break anything by making everything rich.
}
}
| InputOutputITCase |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.java | {
"start": 7919,
"end": 8608
} | class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
TestHttpSecurities.disableDefaults(http);
// @formatter:off
http
.addFilter(new WebAsyncManagerIntegrationFilter())
.anonymous(withDefaults())
.securityContext(withDefaults())
.authorizeHttpRequests((requests) -> requests
.anyRequest().permitAll())
.httpBasic(withDefaults());
// @formatter:on
return http.build();
}
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static | SecurityContextRepositoryDefaultsSecurityContextRepositoryConfig |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/lib/chain/TestMapReduceChain.java | {
"start": 6018,
"end": 6115
} | class ____ extends IDMap {
public BMap() {
super("B", "X");
}
}
public static | BMap |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/ChoiceCompoundPredicateSimpleTest.java | {
"start": 1086,
"end": 4312
} | class ____ extends ContextTestSupport {
@Test
public void testNull() throws Exception {
getMockEndpoint("mock:empty").expectedMessageCount(2);
getMockEndpoint("mock:data").expectedMessageCount(0);
template.sendBody("direct:simple", null);
template.sendBody("direct:or", null);
assertMockEndpointsSatisfied();
}
@Test
public void testEmpty() throws Exception {
getMockEndpoint("mock:empty").expectedMessageCount(2);
getMockEndpoint("mock:data").expectedMessageCount(0);
template.sendBody("direct:simple", new ArrayList<>());
template.sendBody("direct:or", new ArrayList<>());
assertMockEndpointsSatisfied();
}
@Test
public void testEmptyOr() throws Exception {
getMockEndpoint("mock:empty").expectedMessageCount(1);
getMockEndpoint("mock:data").expectedMessageCount(0);
template.sendBody("direct:or", new ArrayList<>());
assertMockEndpointsSatisfied();
}
@Test
public void testEmptySimple() throws Exception {
getMockEndpoint("mock:empty").expectedMessageCount(1);
getMockEndpoint("mock:data").expectedMessageCount(0);
template.sendBody("direct:simple", new ArrayList<>());
assertMockEndpointsSatisfied();
}
@Test
public void testData() throws Exception {
getMockEndpoint("mock:empty").expectedMessageCount(0);
getMockEndpoint("mock:data").expectedMessageCount(2);
List<String> list = new ArrayList<>();
list.add("Hello Camel");
template.sendBody("direct:simple", list);
template.sendBody("direct:or", list);
assertMockEndpointsSatisfied();
}
@Test
public void testDataOr() throws Exception {
getMockEndpoint("mock:empty").expectedMessageCount(0);
getMockEndpoint("mock:data").expectedMessageCount(1);
List<String> list = new ArrayList<>();
list.add("Hello Camel");
template.sendBody("direct:or", list);
assertMockEndpointsSatisfied();
}
@Test
public void testDataSimple() throws Exception {
getMockEndpoint("mock:empty").expectedMessageCount(0);
getMockEndpoint("mock:data").expectedMessageCount(1);
List<String> list = new ArrayList<>();
list.add("Hello Camel");
template.sendBody("direct:simple", list);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:or")
.choice()
.when(or(body().isNull(), simple("${body.size()} == 0")))
.to("mock:empty")
.otherwise()
.to("mock:data")
.end();
from("direct:simple")
.choice()
.when(simple("${body} == null || ${body.size()} == 0"))
.to("mock:empty")
.otherwise()
.to("mock:data")
.end();
}
};
}
}
| ChoiceCompoundPredicateSimpleTest |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java | {
"start": 3821,
"end": 4029
} | class ____ {@code UserRepository}. Loads a basic (non-namespace) Spring configuration file as
* well as Hibernate configuration to execute tests.
* <p>
* To test further persistence providers subclass this | for |
java | google__guava | android/guava/src/com/google/common/util/concurrent/Monitor.java | {
"start": 4250,
"end": 5166
} | class ____<V> {
* private V value;
*
* public synchronized V get() throws InterruptedException {
* while (value == null) {
* wait();
* }
* V result = value;
* value = null;
* notifyAll();
* return result;
* }
*
* public synchronized void set(V newValue) throws InterruptedException {
* while (value != null) {
* wait();
* }
* value = newValue;
* notifyAll();
* }
* }
* }
*
* <h3>{@code ReentrantLock}</h3>
*
* <p>This version is much more verbose than the {@code synchronized} version, and still suffers
* from the need for the programmer to remember to use {@code while} instead of {@code if}. However,
* one advantage is that we can introduce two separate {@code Condition} objects, which allows us to
* use {@code signal()} instead of {@code signalAll()}, which may be a performance benefit.
*
* {@snippet :
* public | SafeBox |
java | netty__netty | common/src/test/java/io/netty/util/ResourceLeakDetectorTest.java | {
"start": 8286,
"end": 8562
} | interface ____ {
boolean close();
}
private static void assertNoErrors(AtomicReference<Throwable> ref) throws Throwable {
Throwable error = ref.get();
if (error != null) {
throw error;
}
}
private static final | Resource |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/language/ConstantTrimTest.java | {
"start": 972,
"end": 1605
} | class ____ extends ContextTestSupport {
@Test
public void testTrim() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived(" Hello World ");
template.sendBody("direct:start", "Start");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.setBody().constant(" Hello World ", false)
.to("mock:result");
}
};
}
}
| ConstantTrimTest |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/PlaygroundWithDemoOfUnclonedParametersProblemTest.java | {
"start": 637,
"end": 2848
} | class ____ extends TestBase {
ImportManager importManager;
ImportLogDao importLogDao;
IImportHandler importHandler;
@Before
public void setUp() throws Exception {
importLogDao = Mockito.mock(ImportLogDao.class);
importHandler = Mockito.mock(IImportHandler.class);
importManager = new ImportManager(importLogDao);
}
@Test
public void shouldIncludeInitialLog() {
// given
int importType = 0;
Date currentDate = new GregorianCalendar(2009, 10, 12).getTime();
ImportLogBean initialLog = new ImportLogBean(currentDate, importType);
initialLog.setStatus(1);
given(importLogDao.anyImportRunningOrRunnedToday(importType, currentDate))
.willReturn(false);
willAnswer(byCheckingLogEquals(initialLog))
.given(importLogDao)
.include(any(ImportLogBean.class));
// when
importManager.startImportProcess(importType, currentDate);
// then
verify(importLogDao).include(any(ImportLogBean.class));
}
@Test
public void shouldAlterFinalLog() {
// given
int importType = 0;
Date currentDate = new GregorianCalendar(2009, 10, 12).getTime();
ImportLogBean finalLog = new ImportLogBean(currentDate, importType);
finalLog.setStatus(9);
given(importLogDao.anyImportRunningOrRunnedToday(importType, currentDate))
.willReturn(false);
willAnswer(byCheckingLogEquals(finalLog))
.given(importLogDao)
.alter(any(ImportLogBean.class));
// when
importManager.startImportProcess(importType, currentDate);
// then
verify(importLogDao).alter(any(ImportLogBean.class));
}
private Answer<Object> byCheckingLogEquals(final ImportLogBean status) {
return new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
ImportLogBean bean = invocation.getArgument(0);
assertEquals(status, bean);
return null;
}
};
}
public | PlaygroundWithDemoOfUnclonedParametersProblemTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.