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
bumptech__glide
library/test/src/test/java/com/bumptech/glide/RequestBuilderTest.java
{ "start": 1788, "end": 15453 }
class ____ { @Rule public TearDownGlide tearDownGlide = new TearDownGlide(); @Mock private RequestListener<Object> listener1; @Mock private RequestListener<Object> listener2; @Mock private Target<Object> target; @Mock private GlideContext glideContext; @Mock private RequestManager requestManager; @Captor private ArgumentCaptor<SingleRequest<Object>> requestCaptor; private Glide glide; private Application context; @Before public void setUp() { MockitoAnnotations.initMocks(this); glide = Glide.get(ApplicationProvider.getApplicationContext()); context = ApplicationProvider.getApplicationContext(); } @Test(expected = NullPointerException.class) public void testThrowsIfContextIsNull() { new RequestBuilder<>(null /*context*/, requestManager, Object.class, context); } @Test(expected = NullPointerException.class) public void testThrowsWhenTransitionsOptionsIsNull() { //noinspection ConstantConditions testing if @NonNull is enforced getNullModelRequest().transition(null); } @Test public void testDoesNotThrowWithNullModelWhenRequestIsBuilt() { getNullModelRequest().into(target); } @Test public void testDoesNotThrowWithNullModelWhenRequestIsBuiltFront() { getNullModelRequest().experimentalIntoFront(target); } @Test public void testAddsNewRequestToRequestTracker() { getNullModelRequest().into(target); verify(requestManager).track(eq(target), isA(Request.class)); } @Test public void testAddsNewRequestToRequestTrackerWithCustomExecutor() { getNullModelRequest() .into(target, /* targetListener= */ null, Executors.newSingleThreadExecutor()); verify(requestManager).track(eq(target), isA(Request.class)); } @Test public void testAddsNewRequestToRequestTrackerFront() { getNullModelRequest().experimentalIntoFront(target); verify(requestManager).track(eq(target), isA(Request.class)); } @Test public void testRemovesPreviousRequestFromRequestTracker() { Request previous = mock(Request.class); when(target.getRequest()).thenReturn(previous); getNullModelRequest().into(target); verify(requestManager).clear(eq(target)); } @Test public void testRemovesPreviousRequestFromRequestTrackerFront() { Request previous = mock(Request.class); when(target.getRequest()).thenReturn(previous); getNullModelRequest().experimentalIntoFront(target); verify(requestManager).clear(eq(target)); } @Test(expected = NullPointerException.class) public void testThrowsIfGivenNullTarget() { //noinspection ConstantConditions testing if @NonNull is enforced getNullModelRequest().into((Target<Object>) null); } @Test(expected = NullPointerException.class) public void testThrowsIfGivenNullTargetFront() { //noinspection ConstantConditions testing if @NonNull is enforced getNullModelRequest().experimentalIntoFront((Target<Object>) null); } @Test(expected = NullPointerException.class) public void testThrowsIfGivenNullView() { getNullModelRequest().into((ImageView) null); } @Test(expected = NullPointerException.class) public void testThrowsIfGivenNullViewFront() { getNullModelRequest().experimentalIntoFront((ImageView) null); } @Test(expected = RuntimeException.class) public void testThrowsIfIntoViewCalledOnBackgroundThread() throws InterruptedException { final ImageView imageView = new ImageView(ApplicationProvider.getApplicationContext()); testInBackground( new BackgroundTester() { @Override public void runTest() { getNullModelRequest().into(imageView); } }); } @Test(expected = RuntimeException.class) public void testThrowsIfIntoViewCalledOnBackgroundThreadFront() throws InterruptedException { final ImageView imageView = new ImageView(ApplicationProvider.getApplicationContext()); testInBackground( new BackgroundTester() { @Override public void runTest() { getNullModelRequest().experimentalIntoFront(imageView); } }); } @Test public void doesNotThrowIfIntoTargetCalledOnBackgroundThread() throws InterruptedException { final Target<Object> target = mock(Target.class); testInBackground( new BackgroundTester() { @Override public void runTest() { getNullModelRequest().into(target); } }); } @Test public void doesNotThrowIfIntoTargetCalledOnBackgroundThreadFront() throws InterruptedException { final Target<Object> target = mock(Target.class); testInBackground( new BackgroundTester() { @Override public void runTest() { getNullModelRequest().experimentalIntoFront(target); } }); } @Test public void doesNotThrowIfIntoTargetWithCustomExecutorCalledOnBackgroundThread() throws InterruptedException { final Target<Object> target = mock(Target.class); testInBackground( new BackgroundTester() { @Override public void runTest() { getNullModelRequest() .into(target, /* targetListener= */ null, Executors.newSingleThreadExecutor()); } }); } @Test public void testMultipleRequestListeners() { getNullModelRequest().addListener(listener1).addListener(listener2).into(target); verify(requestManager).track(any(Target.class), requestCaptor.capture()); requestCaptor .getValue() .onResourceReady( new SimpleResource<>(new Object()), DataSource.LOCAL, /* isLoadedFromAlternateCacheKey= */ false); verify(listener1) .onResourceReady(any(), any(), isA(Target.class), isA(DataSource.class), anyBoolean()); verify(listener2) .onResourceReady(any(), any(), isA(Target.class), isA(DataSource.class), anyBoolean()); } @Test public void testMultipleRequestListenersFront() { getNullModelRequest() .addListener(listener1) .addListener(listener2) .experimentalIntoFront(target); verify(requestManager).track(any(Target.class), requestCaptor.capture()); requestCaptor .getValue() .onResourceReady( new SimpleResource<>(new Object()), DataSource.LOCAL, /* isLoadedFromAlternateCacheKey= */ false); verify(listener1) .onResourceReady(any(), any(), isA(Target.class), isA(DataSource.class), anyBoolean()); verify(listener2) .onResourceReady(any(), any(), isA(Target.class), isA(DataSource.class), anyBoolean()); } @Test public void testListenerApiOverridesListeners() { getNullModelRequest().addListener(listener1).listener(listener2).into(target); verify(requestManager).track(any(Target.class), requestCaptor.capture()); requestCaptor .getValue() .onResourceReady( new SimpleResource<>(new Object()), DataSource.LOCAL, /* isLoadedFromAlternateCacheKey= */ false); // The #listener API removes any previous listeners, so the first listener should not be called. verify(listener1, never()) .onResourceReady(any(), any(), isA(Target.class), isA(DataSource.class), anyBoolean()); verify(listener2) .onResourceReady(any(), any(), isA(Target.class), isA(DataSource.class), anyBoolean()); } @Test public void testListenerApiOverridesListenersFront() { getNullModelRequest().addListener(listener1).listener(listener2).experimentalIntoFront(target); verify(requestManager).track(any(Target.class), requestCaptor.capture()); requestCaptor .getValue() .onResourceReady( new SimpleResource<>(new Object()), DataSource.LOCAL, /* isLoadedFromAlternateCacheKey= */ false); // The #listener API removes any previous listeners, so the first listener should not be called. verify(listener1, never()) .onResourceReady(any(), any(), isA(Target.class), isA(DataSource.class), anyBoolean()); verify(listener2) .onResourceReady(any(), any(), isA(Target.class), isA(DataSource.class), anyBoolean()); } @Test public void testEquals() { Object firstModel = new Object(); Object secondModel = new Object(); RequestListener<Object> firstListener = new RequestListener<>() { @Override public boolean onLoadFailed( @Nullable GlideException e, Object model, @NonNull Target<Object> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady( @NonNull Object resource, @NonNull Object model, Target<Object> target, @NonNull DataSource dataSource, boolean isFirstResource) { return false; } }; RequestListener<Object> secondListener = new RequestListener<>() { @Override public boolean onLoadFailed( @Nullable GlideException e, Object model, @NonNull Target<Object> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady( @NonNull Object resource, @NonNull Object model, Target<Object> target, @NonNull DataSource dataSource, boolean isFirstResource) { return false; } }; new EqualsTester() .addEqualityGroup(new Object()) .addEqualityGroup(newRequestBuilder(Object.class), newRequestBuilder(Object.class)) .addEqualityGroup( newRequestBuilder(Object.class).load((Object) null), newRequestBuilder(Object.class).load((Object) null), newRequestBuilder(Object.class).load((Uri) null)) .addEqualityGroup( newRequestBuilder(Object.class).load(firstModel), newRequestBuilder(Object.class).load(firstModel)) .addEqualityGroup( newRequestBuilder(Object.class).load(secondModel), newRequestBuilder(Object.class).load(secondModel)) .addEqualityGroup( newRequestBuilder(Object.class).load(Uri.EMPTY), newRequestBuilder(Object.class).load(Uri.EMPTY)) .addEqualityGroup( newRequestBuilder(Uri.class).load(Uri.EMPTY), newRequestBuilder(Uri.class).load(Uri.EMPTY)) .addEqualityGroup( newRequestBuilder(Object.class).centerCrop(), newRequestBuilder(Object.class).centerCrop()) .addEqualityGroup( newRequestBuilder(Object.class).addListener(firstListener), newRequestBuilder(Object.class).addListener(firstListener)) .addEqualityGroup( newRequestBuilder(Object.class).addListener(secondListener), newRequestBuilder(Object.class).addListener(secondListener)) .addEqualityGroup( newRequestBuilder(Object.class).error(newRequestBuilder(Object.class)), newRequestBuilder(Object.class).error(newRequestBuilder(Object.class))) .addEqualityGroup( newRequestBuilder(Object.class).error(firstModel), newRequestBuilder(Object.class).error(firstModel), newRequestBuilder(Object.class).error(newRequestBuilder(Object.class).load(firstModel))) .addEqualityGroup( newRequestBuilder(Object.class).error(secondModel), newRequestBuilder(Object.class).error(secondModel), newRequestBuilder(Object.class) .error(newRequestBuilder(Object.class).load(secondModel))) .addEqualityGroup( newRequestBuilder(Object.class) .error(newRequestBuilder(Object.class).load(firstModel).centerCrop()), newRequestBuilder(Object.class) .error(newRequestBuilder(Object.class).load(firstModel).centerCrop())) .addEqualityGroup( newRequestBuilder(Object.class) .thumbnail(newRequestBuilder(Object.class).load(firstModel)), newRequestBuilder(Object.class) .thumbnail(newRequestBuilder(Object.class).load(firstModel))) .addEqualityGroup( newRequestBuilder(Object.class) .thumbnail(newRequestBuilder(Object.class).load(secondModel)), newRequestBuilder(Object.class) .thumbnail(newRequestBuilder(Object.class).load(secondModel))) .addEqualityGroup( newRequestBuilder(Object.class) .transition(new GenericTransitionOptions<>().dontTransition()), newRequestBuilder(Object.class) .transition(new GenericTransitionOptions<>().dontTransition())) .testEquals(); } private RequestBuilder<Object> getNullModelRequest() { return newRequestBuilder(Object.class).load((Object) null); } private <ModelT> RequestBuilder<ModelT> newRequestBuilder(Class<ModelT> modelClass) { when(glideContext.buildImageViewTarget(isA(ImageView.class), isA(Class.class))) .thenReturn(mock(ViewTarget.class)); when(glideContext.getDefaultRequestOptions()).thenReturn(new RequestOptions()); when(requestManager.getDefaultRequestOptions()).thenReturn(new RequestOptions()); when(requestManager.getDefaultTransitionOptions(any(Class.class))) .thenReturn(new GenericTransitionOptions<>()); return new RequestBuilder<>(glide, requestManager, modelClass, context); } }
RequestBuilderTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Issue62.java
{ "start": 603, "end": 1102 }
class ____ { private byte[] a; private int b; private String c; public byte[] getA() { return a; } public void setA(byte[] a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public String getC() { return c; } public void setC(String c) { this.c = c; } } }
A
java
google__error-prone
check_api/src/main/java/com/google/errorprone/apply/DescriptionBasedDiff.java
{ "start": 1475, "end": 4637 }
class ____ implements DescriptionListener, Diff { private final String sourcePath; private final boolean ignoreOverlappingFixes; private final JCCompilationUnit compilationUnit; private final Set<String> importsToAdd; private final Set<String> importsToRemove; private final EndPosTable endPositions; private final Replacements replacements = new Replacements(); private final ImportOrganizer importOrganizer; public static DescriptionBasedDiff create( JCCompilationUnit compilationUnit, ImportOrganizer importOrganizer) { return new DescriptionBasedDiff(compilationUnit, false, importOrganizer); } public static DescriptionBasedDiff createIgnoringOverlaps( JCCompilationUnit compilationUnit, ImportOrganizer importOrganizer) { return new DescriptionBasedDiff(compilationUnit, true, importOrganizer); } private DescriptionBasedDiff( JCCompilationUnit compilationUnit, boolean ignoreOverlappingFixes, ImportOrganizer importOrganizer) { this.compilationUnit = checkNotNull(compilationUnit); URI sourceFileUri = compilationUnit.getSourceFile().toUri(); this.sourcePath = (sourceFileUri.isAbsolute() && Objects.equals(sourceFileUri.getScheme(), "file")) ? Paths.get(sourceFileUri).toAbsolutePath().toString() : sourceFileUri.getPath(); this.ignoreOverlappingFixes = ignoreOverlappingFixes; this.importsToAdd = new LinkedHashSet<>(); this.importsToRemove = new LinkedHashSet<>(); this.endPositions = compilationUnit.endPositions; this.importOrganizer = importOrganizer; } @Override public String getRelevantFileName() { return sourcePath; } public boolean isEmpty() { return importsToAdd.isEmpty() && importsToRemove.isEmpty() && replacements.isEmpty(); } @Override public void onDescribed(Description description) { // Use only first (most likely) suggested fix if (description.fixes.size() > 0) { handleFix(description.fixes.getFirst()); } } public void handleFix(Fix fix) { importsToAdd.addAll(fix.getImportsToAdd()); importsToRemove.addAll(fix.getImportsToRemove()); for (Replacement replacement : fix.getReplacements(endPositions)) { try { replacements.add(replacement, fix.getCoalescePolicy()); } catch (IllegalArgumentException iae) { if (!ignoreOverlappingFixes) { throw iae; } } } } @Override public void applyDifferences(SourceFile sourceFile) { if (!importsToAdd.isEmpty() || !importsToRemove.isEmpty()) { ImportStatements importStatements = ImportStatements.create(compilationUnit, importOrganizer); importStatements.addAll(importsToAdd); importStatements.removeAll(importsToRemove); if (importStatements.importsHaveChanged()) { replacements.add( Replacement.create( importStatements.getStartPos(), importStatements.getEndPos(), importStatements.toString()), Replacements.CoalescePolicy.REPLACEMENT_FIRST); } } sourceFile.makeReplacements(replacements); } }
DescriptionBasedDiff
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/functions/co/BaseBroadcastProcessFunction.java
{ "start": 3190, "end": 4074 }
class ____ extends BaseContext { /** * Fetches the {@link BroadcastState} with the specified name. * * @param stateDescriptor the {@link MapStateDescriptor} of the state to be fetched. * @return The required {@link BroadcastState broadcast state}. */ public abstract <K, V> BroadcastState<K, V> getBroadcastState( final MapStateDescriptor<K, V> stateDescriptor); } /** * A {@link BaseContext context} available to the non-broadcasted stream side of a {@link * org.apache.flink.streaming.api.datastream.BroadcastConnectedStream BroadcastConnectedStream}. * * <p>Apart from the basic functionality of a {@link BaseContext context}, this also allows to * get a <b>read-only</b> {@link Iterable} over the elements stored in the broadcast state. */ public abstract
Context
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingHandlerMappingTests.java
{ "start": 24261, "end": 24358 }
class ____ extends PackagePrivateMethodController { } }
LocalPackagePrivateMethodControllerSubclass
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/DoubleCheckedLocking.java
{ "start": 2621, "end": 10417 }
class ____ extends BugChecker implements IfTreeMatcher { @Override public Description matchIf(IfTree outerIf, VisitorState state) { DclInfo info = findDcl(outerIf); if (info == null) { return Description.NO_MATCH; } return switch (info.sym().getKind()) { case FIELD -> handleField(info.outerIf(), info.sym(), state); case LOCAL_VARIABLE -> handleLocal(info, state); default -> Description.NO_MATCH; }; } /** * Report a {@link Description} if a field used in double-checked locking is not volatile. * * <p>If the AST node for the field declaration can be located in the current compilation unit, * suggest adding the volatile modifier. */ private Description handleField(IfTree outerIf, VarSymbol sym, VisitorState state) { if (sym.getModifiers().contains(Modifier.VOLATILE)) { return Description.NO_MATCH; } if (isImmutable(sym.type, state)) { return Description.NO_MATCH; } Description.Builder builder = buildDescription(outerIf); JCTree fieldDecl = findFieldDeclaration(state.getPath(), sym); if (fieldDecl != null) { builder.addFix( SuggestedFixes.addModifiers(fieldDecl, state, Modifier.VOLATILE) .orElse(SuggestedFix.emptyFix())); } return builder.build(); } private static final ImmutableSet<String> IMMUTABLE_PRIMITIVES = ImmutableSet.of( java.lang.Boolean.class.getName(), java.lang.Byte.class.getName(), java.lang.Short.class.getName(), java.lang.Integer.class.getName(), java.lang.Character.class.getName(), java.lang.Float.class.getName(), java.lang.String.class.getName()); /** * Recognize a small set of known-immutable types that are safe for DCL even without a volatile * field. */ private static boolean isImmutable(Type type, VisitorState state) { switch (type.getKind()) { case BOOLEAN, BYTE, SHORT, INT, CHAR, FLOAT -> { return true; } case LONG, DOUBLE -> { // double-width primitives aren't written atomically return true; } default -> {} } return IMMUTABLE_PRIMITIVES.contains( state.getTypes().erasure(type).tsym.getQualifiedName().toString()); } /** * Report a diagnostic for an instance of DCL on a local variable. A match is only reported if a * non-volatile field is written to the variable after acquiring the lock and before the second * null-check on the local. * * <p>e.g. * * <pre>{@code * if ($X == null) { * synchronized (...) { * $X = myNonVolatileField; * if ($X == null) { * ... * } * ... * } * } * }</pre> */ private Description handleLocal(DclInfo info, VisitorState state) { ExpressionStatementTree expr = getChild(info.synchTree().getBlock(), ExpressionStatementTree.class); if (expr == null) { return Description.NO_MATCH; } if (getStartPosition(expr) > getStartPosition(info.innerIf())) { return Description.NO_MATCH; } if (!(expr.getExpression() instanceof AssignmentTree assign)) { return Description.NO_MATCH; } if (!Objects.equals(ASTHelpers.getSymbol(assign.getVariable()), info.sym())) { return Description.NO_MATCH; } if (!(ASTHelpers.getSymbol(assign.getExpression()) instanceof VarSymbol fvar)) { return Description.NO_MATCH; } if (fvar.getKind() != ElementKind.FIELD) { return Description.NO_MATCH; } return handleField(info.outerIf(), fvar, state); } /** * Information about an instance of DCL. * * @param outerIf The outer if statement * @param synchTree The synchronized statement * @param innerIf The inner if statement * @param sym The variable (local or field) that is double-checked */ private record DclInfo( IfTree outerIf, SynchronizedTree synchTree, IfTree innerIf, VarSymbol sym) { static DclInfo create( IfTree outerIf, SynchronizedTree synchTree, IfTree innerIf, VarSymbol sym) { return new DclInfo(outerIf, synchTree, innerIf, sym); } } /** * Matches an instance of DCL. The canonical pattern is: * * <pre>{@code * if ($X == null) { * synchronized (...) { * if ($X == null) { * ... * } * ... * } * } * }</pre> * * Gaps before the synchronized or inner 'if' statement are ignored, and the operands in the * null-checks are accepted in either order. */ private static @Nullable DclInfo findDcl(IfTree outerIf) { // TODO(cushon): Optional.ifPresent... ExpressionTree outerIfTest = getNullCheckedExpression(outerIf.getCondition()); if (outerIfTest == null) { return null; } SynchronizedTree synchTree = getChild(outerIf.getThenStatement(), SynchronizedTree.class); if (synchTree == null) { return null; } IfTree innerIf = getChild(synchTree.getBlock(), IfTree.class); if (innerIf == null) { return null; } ExpressionTree innerIfTest = getNullCheckedExpression(innerIf.getCondition()); if (innerIfTest == null) { return null; } Symbol outerSym = ASTHelpers.getSymbol(outerIfTest); if (!Objects.equals(outerSym, ASTHelpers.getSymbol(innerIfTest))) { return null; } if (!(outerSym instanceof VarSymbol var)) { return null; } return DclInfo.create(outerIf, synchTree, innerIf, var); } /** * Matches comparisons to null (e.g. {@code foo == null}) and returns the expression being tested. */ private static @Nullable ExpressionTree getNullCheckedExpression(ExpressionTree condition) { condition = stripParentheses(condition); if (!(condition instanceof BinaryTree bin)) { return null; } ExpressionTree other; if (bin.getLeftOperand().getKind() == Kind.NULL_LITERAL) { other = bin.getRightOperand(); } else if (bin.getRightOperand().getKind() == Kind.NULL_LITERAL) { other = bin.getLeftOperand(); } else { return null; } return other; } /** * Visits (possibly nested) block statements and returns the first child statement with the given * class. */ private static <T> T getChild(StatementTree tree, Class<T> clazz) { return tree.accept( new SimpleTreeVisitor<T, Void>() { @Override protected T defaultAction(Tree node, Void p) { if (clazz.isInstance(node)) { return clazz.cast(node); } return null; } @Override public T visitBlock(BlockTree node, Void p) { return visit(node.getStatements()); } private T visit(List<? extends Tree> tx) { for (Tree t : tx) { T r = t.accept(this, null); if (r != null) { return r; } } return null; } }, null); } /** * Performs a best-effort search for the AST node of a field declaration. * * <p>It will only find fields declared in a lexically enclosing scope of the current location. * Since double-checked locking should always be used on a private field, this should be * reasonably effective. */ private static @Nullable JCTree findFieldDeclaration(TreePath path, VarSymbol var) { for (TreePath curr = path; curr != null; curr = curr.getParentPath()) { Tree leaf = curr.getLeaf(); if (!(leaf instanceof JCClassDecl classTree)) { continue; } for (JCTree tree : classTree.getMembers()) { if (Objects.equals(var, ASTHelpers.getSymbol(tree))) { return tree; } } } return null; } }
DoubleCheckedLocking
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/filter/factory/JsonToGrpcGatewayFilterFactory.java
{ "start": 4792, "end": 5447 }
class ____ { private @Nullable String protoDescriptor; private @Nullable String service; private @Nullable String method; public @Nullable String getProtoDescriptor() { return protoDescriptor; } public Config setProtoDescriptor(String protoDescriptor) { this.protoDescriptor = protoDescriptor; return this; } public @Nullable String getService() { return service; } public Config setService(String service) { this.service = service; return this; } public @Nullable String getMethod() { return method; } public Config setMethod(String method) { this.method = method; return this; } }
Config
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/WrappedSessionStoreIterator.java
{ "start": 1080, "end": 2255 }
class ____ implements KeyValueIterator<Windowed<Bytes>, byte[]> { private final KeyValueIterator<Bytes, byte[]> bytesIterator; private final Function<Bytes, Windowed<Bytes>> windowConstructor; WrappedSessionStoreIterator(final KeyValueIterator<Bytes, byte[]> bytesIterator) { this(bytesIterator, SessionKeySchema::from); } WrappedSessionStoreIterator(final KeyValueIterator<Bytes, byte[]> bytesIterator, final Function<Bytes, Windowed<Bytes>> windowConstructor) { this.bytesIterator = bytesIterator; this.windowConstructor = windowConstructor; } @Override public void close() { bytesIterator.close(); } @Override public Windowed<Bytes> peekNextKey() { return windowConstructor.apply(bytesIterator.peekNextKey()); } @Override public boolean hasNext() { return bytesIterator.hasNext(); } @Override public KeyValue<Windowed<Bytes>, byte[]> next() { final KeyValue<Bytes, byte[]> next = bytesIterator.next(); return KeyValue.pair(windowConstructor.apply(next.key), next.value); } }
WrappedSessionStoreIterator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MixedMutabilityReturnTypeTest.java
{ "start": 3485, "end": 4101 }
class ____ { List<Integer> foo() { if (hashCode() > 0) { return Collections.emptyList(); } return bar(); } List<Integer> bar() { return new ArrayList<>(); } } """) .doTest(); } @Test public void allImmutable_noMatch() { compilationHelper .addSourceLines( "Test.java", """ import java.util.Collections; import java.util.List; import java.util.ArrayList;
Test
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/ValueAnnotationsDeserTest.java
{ "start": 4084, "end": 4224 }
class ____ testing broken {@link JsonDeserialize} annotation * with 'as' parameter; one with incompatible type */ final static
for
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/MapKeyTemporalJpaAnnotation.java
{ "start": 467, "end": 1460 }
class ____ implements MapKeyTemporal { private jakarta.persistence.TemporalType value; /** * Used in creating dynamic annotation instances (e.g. from XML) */ public MapKeyTemporalJpaAnnotation(ModelsContext modelContext) { } /** * Used in creating annotation instances from JDK variant */ public MapKeyTemporalJpaAnnotation(MapKeyTemporal annotation, ModelsContext modelContext) { this.value = annotation.value(); } /** * Used in creating annotation instances from Jandex variant */ public MapKeyTemporalJpaAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) { this.value = (jakarta.persistence.TemporalType) attributeValues.get( "value" ); } @Override public Class<? extends Annotation> annotationType() { return MapKeyTemporal.class; } @Override public jakarta.persistence.TemporalType value() { return value; } public void value(jakarta.persistence.TemporalType value) { this.value = value; } }
MapKeyTemporalJpaAnnotation
java
elastic__elasticsearch
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/TarInputStream.java
{ "start": 849, "end": 911 }
class ____ not suitable for general purpose tar processing! */
is
java
apache__camel
components/camel-cxf/camel-cxf-soap/src/test/java/org/apache/camel/wsdl_first/PersonImplWithWsdl.java
{ "start": 1174, "end": 1990 }
class ____ implements Person { private String reply = "Bonjour"; public void getPerson( Holder<String> personId, Holder<String> ssn, Holder<String> name) throws UnknownPersonFault { if (personId.value == null || personId.value.length() == 0) { org.apache.camel.wsdl_first.types.UnknownPersonFault fault = new org.apache.camel.wsdl_first.types.UnknownPersonFault(); fault.setPersonId(personId.value); throw new UnknownPersonFault("Get the null value of person name", fault); } name.value = reply; ssn.value = "000-000-0000"; } public String getReply() { return reply; } public void setReply(String reply) { this.reply = reply; } }
PersonImplWithWsdl
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestCorruptReplicaInfo.java
{ "start": 1872, "end": 8085 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger( TestCorruptReplicaInfo.class); private final Map<Long, BlockInfo> replicaMap = new HashMap<>(); private final Map<Long, BlockInfo> stripedBlocksMap = new HashMap<>(); // Allow easy block creation by block id. Return existing // replica block if one with same block id already exists. private BlockInfo getReplica(Long blockId) { if (!replicaMap.containsKey(blockId)) { short replFactor = 3; replicaMap.put(blockId, new BlockInfoContiguous(new Block(blockId, 0, 0), replFactor)); } return replicaMap.get(blockId); } private BlockInfo getReplica(int blkId) { return getReplica(Long.valueOf(blkId)); } private BlockInfo getStripedBlock(int blkId) { Long stripedBlockId = (1L << 63) + blkId; assertTrue(BlockIdManager.isStripedBlockID(stripedBlockId)); if (!stripedBlocksMap.containsKey(stripedBlockId)) { stripedBlocksMap.put(stripedBlockId, new BlockInfoStriped(new Block(stripedBlockId, 1024, 0), StripedFileTestUtil.getDefaultECPolicy())); } return stripedBlocksMap.get(stripedBlockId); } private void verifyCorruptBlocksCount(CorruptReplicasMap corruptReplicasMap, long expectedReplicaCount, long expectedStripedBlockCount) { long totalExpectedCorruptBlocks = expectedReplicaCount + expectedStripedBlockCount; assertEquals(totalExpectedCorruptBlocks, corruptReplicasMap.size(), "Unexpected total corrupt blocks count!"); assertEquals(expectedReplicaCount, corruptReplicasMap.getCorruptBlocks(), "Unexpected replica blocks count!"); assertEquals(expectedStripedBlockCount, corruptReplicasMap.getCorruptECBlockGroups(), "Unexpected striped blocks count!"); } @Test public void testCorruptReplicaInfo() throws IOException, InterruptedException { CorruptReplicasMap crm = new CorruptReplicasMap(); BlockIdManager bim = Mockito.mock(BlockIdManager.class); when(bim.isLegacyBlock(any(Block.class))).thenReturn(false); when(bim.isStripedBlock(any(Block.class))).thenCallRealMethod(); assertTrue(!bim.isLegacyBlock(new Block(-1))); // Make sure initial values are returned correctly assertEquals(0, crm.size(), "Total number of corrupt blocks must initially be 0!"); assertEquals(0, crm.getCorruptBlocks(), "Number of corrupt replicas must initially be 0!"); assertEquals(0, crm.getCorruptECBlockGroups(), "Number of corrupt striped block groups must initially be 0!"); assertNull(crm.getCorruptBlockIdsForTesting(bim, BlockType.CONTIGUOUS, -1, null), "Param n cannot be less than 0"); assertNull(crm.getCorruptBlockIdsForTesting(bim, BlockType.CONTIGUOUS, 101, null), "Param n cannot be greater than 100"); long[] l = crm.getCorruptBlockIdsForTesting( bim, BlockType.CONTIGUOUS, 0, null); assertNotNull(l, "n = 0 must return non-null"); assertEquals(0, l.length, "n = 0 must return an empty list"); // Create a list of block ids. A list is used to allow easy // validation of the output of getCorruptReplicaBlockIds. final int blockCount = 140; long[] replicaIds = new long[blockCount]; long[] stripedIds = new long[blockCount]; for (int i = 0; i < blockCount; i++) { replicaIds[i] = getReplica(i).getBlockId(); stripedIds[i] = getStripedBlock(i).getBlockId(); } DatanodeDescriptor dn1 = DFSTestUtil.getLocalDatanodeDescriptor(); DatanodeDescriptor dn2 = DFSTestUtil.getLocalDatanodeDescriptor(); // Add to corrupt blocks map. // Replicas addToCorruptReplicasMap(crm, getReplica(0), dn1); verifyCorruptBlocksCount(crm, 1, 0); addToCorruptReplicasMap(crm, getReplica(1), dn1); verifyCorruptBlocksCount(crm, 2, 0); addToCorruptReplicasMap(crm, getReplica(1), dn2); verifyCorruptBlocksCount(crm, 2, 0); // Striped blocks addToCorruptReplicasMap(crm, getStripedBlock(0), dn1); verifyCorruptBlocksCount(crm, 2, 1); addToCorruptReplicasMap(crm, getStripedBlock(1), dn1); verifyCorruptBlocksCount(crm, 2, 2); addToCorruptReplicasMap(crm, getStripedBlock(1), dn2); verifyCorruptBlocksCount(crm, 2, 2); // Remove from corrupt blocks map. // Replicas crm.removeFromCorruptReplicasMap(getReplica(1)); verifyCorruptBlocksCount(crm, 1, 2); crm.removeFromCorruptReplicasMap(getReplica(0)); verifyCorruptBlocksCount(crm, 0, 2); // Striped blocks crm.removeFromCorruptReplicasMap(getStripedBlock(1)); verifyCorruptBlocksCount(crm, 0, 1); crm.removeFromCorruptReplicasMap(getStripedBlock(0)); verifyCorruptBlocksCount(crm, 0, 0); for (int blockId = 0; blockId < blockCount; blockId++) { addToCorruptReplicasMap(crm, getReplica(blockId), dn1); addToCorruptReplicasMap(crm, getStripedBlock(blockId), dn1); } assertEquals(2 * blockCount, crm.size(), "Number of corrupt blocks not returning correctly"); assertTrue(Arrays.equals(Arrays.copyOfRange(replicaIds, 0, 5), crm.getCorruptBlockIdsForTesting( bim, BlockType.CONTIGUOUS, 5, null)), "First five corrupt replica blocks ids are not right!"); assertTrue(Arrays.equals(Arrays.copyOfRange(stripedIds, 0, 5), crm.getCorruptBlockIdsForTesting( bim, BlockType.STRIPED, 5, null)), "First five corrupt striped blocks ids are not right!"); assertTrue(Arrays.equals(Arrays.copyOfRange(replicaIds, 7, 17), crm.getCorruptBlockIdsForTesting( bim, BlockType.CONTIGUOUS, 10, 7L)), "10 replica blocks after 7 not returned correctly!"); assertTrue(Arrays.equals(Arrays.copyOfRange(stripedIds, 7, 17), crm.getCorruptBlockIdsForTesting(bim, BlockType.STRIPED, 10, getStripedBlock(7).getBlockId())), "10 striped blocks after 7 not returned correctly!"); } private static void addToCorruptReplicasMap(CorruptReplicasMap crm, BlockInfo blk, DatanodeDescriptor dn) { crm.addToCorruptReplicasMap(blk, dn, "TEST", Reason.NONE, blk.isStriped()); } }
TestCorruptReplicaInfo
java
apache__camel
components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/InlineQueryResultCachedDocument.java
{ "start": 1252, "end": 1868 }
class ____ extends InlineQueryResult { private static final String TYPE = "document"; @JsonProperty("document_file_id") private String documentFileId; private String title; private String caption; private String description; @JsonProperty("parse_mode") private String parseMode; @JsonProperty("input_message_content") private InputMessageContent inputMessageContext; public InlineQueryResultCachedDocument() { super(TYPE); } public static Builder builder() { return new Builder(); } public static final
InlineQueryResultCachedDocument
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/SchemaBasedMultitenancyTest.java
{ "start": 3530, "end": 3707 }
class ____ implements TenantSchemaMapper<String> { @Override public @NonNull String schemaName(@NonNull String tenantIdentifier) { return tenantIdentifier; } } }
MyMapper
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/TestPropertySourceTestMethodScopedExtensionContextNestedTests.java
{ "start": 4331, "end": 5000 }
class ____ implements TestInterface { @Autowired Environment env5; @Test void propertiesInEnvironment() { assertThat(env4).isSameAs(env5); assertThat(env5.getProperty("p1")).isNull(); assertThat(env5.getProperty("p2")).isNull(); assertThat(env5.getProperty("p3")).isEqualTo("v34"); assertThat(env5.getProperty("p4")).isEqualTo("v4"); assertThat(env5.getProperty("foo")).isEqualTo("bar"); assertThat(env5.getProperty("enigma")).isEqualTo("42"); } } } } } // ------------------------------------------------------------------------- @Configuration static
L5InheritedCfgAndTestInterfaceTests
java
elastic__elasticsearch
test/framework/src/integTest/java/org/elasticsearch/test/disruption/NetworkDisruptionIT.java
{ "start": 1904, "end": 9093 }
class ____ extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Arrays.asList(MockTransportService.TestPlugin.class); } private static final Settings DISRUPTION_TUNED_SETTINGS = Settings.builder() .put(NodeConnectionsService.CLUSTER_NODE_RECONNECT_INTERVAL_SETTING.getKey(), "2s") .build(); /** * Creates 3 to 5 mixed-node cluster and splits it into 2 parts. * The first part is guaranteed to have at least the majority of the nodes, * so that master could be elected on this side. */ private Tuple<Set<String>, Set<String>> prepareDisruptedCluster() { int numOfNodes = randomIntBetween(3, 5); internalCluster().setBootstrapMasterNodeIndex(numOfNodes - 1); Set<String> nodes = new HashSet<>(internalCluster().startNodes(numOfNodes, DISRUPTION_TUNED_SETTINGS)); ensureGreen(); assertThat(nodes.size(), greaterThanOrEqualTo(3)); int majority = nodes.size() / 2 + 1; Set<String> side1 = new HashSet<>(randomSubsetOf(randomIntBetween(majority, nodes.size() - 1), nodes)); assertThat(side1.size(), greaterThanOrEqualTo(majority)); Set<String> side2 = new HashSet<>(nodes); side2.removeAll(side1); assertThat(side2.size(), greaterThanOrEqualTo(1)); NetworkDisruption networkDisruption = new NetworkDisruption(new TwoPartitions(side1, side2), NetworkDisruption.DISCONNECT); internalCluster().setDisruptionScheme(networkDisruption); networkDisruption.startDisrupting(); return Tuple.tuple(side1, side2); } public void testClearDisruptionSchemeWhenNodeIsDown() throws IOException { Tuple<Set<String>, Set<String>> sides = prepareDisruptedCluster(); internalCluster().stopNode(randomFrom(sides.v2())); internalCluster().clearDisruptionScheme(); } public void testNetworkPartitionRemovalRestoresConnections() throws Exception { Tuple<Set<String>, Set<String>> sides = prepareDisruptedCluster(); Set<String> side1 = sides.v1(); Set<String> side2 = sides.v2(); // sends some requests to the majority side part client(randomFrom(side1)).admin().cluster().prepareNodesInfo().get(); internalCluster().clearDisruptionScheme(); // check all connections are restored for (String nodeA : side1) { for (String nodeB : side2) { TransportService serviceA = internalCluster().getInstance(TransportService.class, nodeA); TransportService serviceB = internalCluster().getInstance(TransportService.class, nodeB); // TODO assertBusy should not be here, see https://github.com/elastic/elasticsearch/issues/38348 assertBusy(() -> { assertTrue(nodeA + " is not connected to " + nodeB, serviceA.nodeConnected(serviceB.getLocalNode())); assertTrue(nodeB + " is not connected to " + nodeA, serviceB.nodeConnected(serviceA.getLocalNode())); }); } } } public void testTransportRespondsEventually() throws InterruptedException { internalCluster().setBootstrapMasterNodeIndex(0); internalCluster().ensureAtLeastNumDataNodes(randomIntBetween(3, 5)); final NetworkDisruption.DisruptedLinks disruptedLinks; if (randomBoolean()) { disruptedLinks = TwoPartitions.random(random(), internalCluster().getNodeNames()); } else { disruptedLinks = NetworkDisruption.Bridge.random(random(), internalCluster().getNodeNames()); } NetworkDisruption networkDisruption = new NetworkDisruption( disruptedLinks, randomFrom(NetworkDisruption.UNRESPONSIVE, NetworkDisruption.DISCONNECT, NetworkDisruption.NetworkDelay.random(random())) ); internalCluster().setDisruptionScheme(networkDisruption); networkDisruption.startDisrupting(); int requests = randomIntBetween(1, 200); CountDownLatch latch = new CountDownLatch(requests); for (int i = 0; i < requests - 1; ++i) { sendRequest( internalCluster().getInstance(TransportService.class), internalCluster().getInstance(TransportService.class), latch ); } // send a request that is guaranteed disrupted. Tuple<TransportService, TransportService> disruptedPair = findDisruptedPair(disruptedLinks); sendRequest(disruptedPair.v1(), disruptedPair.v2(), latch); // give a bit of time to send something under disruption. assertFalse( latch.await(500, TimeUnit.MILLISECONDS) && networkDisruption.getNetworkLinkDisruptionType() != NetworkDisruption.DISCONNECT ); networkDisruption.stopDisrupting(); latch.await(30, TimeUnit.SECONDS); assertEquals("All requests must respond, requests: " + requests, 0, latch.getCount()); } private static Tuple<TransportService, TransportService> findDisruptedPair(NetworkDisruption.DisruptedLinks disruptedLinks) { Optional<Tuple<TransportService, TransportService>> disruptedPair = disruptedLinks.nodes() .stream() .flatMap(n1 -> disruptedLinks.nodes().stream().map(n2 -> Tuple.tuple(n1, n2))) .filter(pair -> disruptedLinks.disrupt(pair.v1(), pair.v2())) .map( pair -> Tuple.tuple( internalCluster().getInstance(TransportService.class, pair.v1()), internalCluster().getInstance(TransportService.class, pair.v2()) ) ) .findFirst(); // since we have 3+ nodes, we are sure to find a disrupted pair, also for bridge disruptions. assertTrue(disruptedPair.isPresent()); return disruptedPair.get(); } private static void sendRequest(TransportService source, TransportService target, CountDownLatch latch) { source.sendRequest( target.getLocalNode(), TransportClusterHealthAction.NAME, new ClusterHealthRequest(TEST_REQUEST_TIMEOUT), new TransportResponseHandler<>() { private AtomicBoolean responded = new AtomicBoolean(); @Override public Executor executor() { return TransportResponseHandler.TRANSPORT_WORKER; } @Override public void handleResponse(TransportResponse response) { assertTrue(responded.compareAndSet(false, true)); latch.countDown(); } @Override public void handleException(TransportException exp) { assertTrue(responded.compareAndSet(false, true)); latch.countDown(); } @Override public TransportResponse read(StreamInput in) throws IOException { return ClusterHealthResponse.readResponseFrom(in); } } ); } }
NetworkDisruptionIT
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/core/AbstractClassGenerator.java
{ "start": 5512, "end": 5942 }
class ____ be generated. * Concrete subclasses of <code>AbstractClassGenerator</code> (such as <code>Enhancer</code>) * will try to choose an appropriate default if this is unset. * <p> * Classes are cached per-<code>ClassLoader</code> using a <code>WeakHashMap</code>, to allow * the generated classes to be removed when the associated loader is garbage collected. * @param classLoader the loader to generate the new
will
java
apache__camel
components/camel-twilio/src/main/java/org/apache/camel/component/twilio/internal/TwilioConstants.java
{ "start": 906, "end": 1180 }
interface ____ { /** * Suffix for parameters when passed as exchange header properties */ String PROPERTY_PREFIX = "CamelTwilio."; /** * Thread profile name for this component */ String THREAD_PROFILE_NAME = "CamelTwilio"; }
TwilioConstants
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/security/authorize/NMPolicyProvider.java
{ "start": 1572, "end": 2906 }
class ____ extends PolicyProvider { private static NMPolicyProvider nmPolicyProvider = null; private NMPolicyProvider() {} @InterfaceAudience.Private @InterfaceStability.Unstable public static NMPolicyProvider getInstance() { if (nmPolicyProvider == null) { synchronized(NMPolicyProvider.class) { if (nmPolicyProvider == null) { nmPolicyProvider = new NMPolicyProvider(); } } } return nmPolicyProvider; } private static final Service[] NODE_MANAGER_SERVICES = new Service[] { new Service(YarnConfiguration. YARN_SECURITY_SERVICE_AUTHORIZATION_CONTAINER_MANAGEMENT_PROTOCOL, ContainerManagementProtocolPB.class), new Service(YarnConfiguration. YARN_SECURITY_SERVICE_AUTHORIZATION_RESOURCE_LOCALIZER, LocalizationProtocolPB.class), new Service(YarnConfiguration. YARN_SECURITY_SERVICE_AUTHORIZATION_COLLECTOR_NODEMANAGER_PROTOCOL, CollectorNodemanagerProtocolPB.class), new Service(YarnConfiguration. YARN_SECURITY_SERVICE_AUTHORIZATION_APPLICATIONMASTER_NODEMANAGER_PROTOCOL, ApplicationMasterProtocolPB.class), }; @Override public Service[] getServices() { return NODE_MANAGER_SERVICES; } }
NMPolicyProvider
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/TestConstructorTestClassScopedExtensionContextNestedTests.java
{ "start": 3211, "end": 3556 }
class ____ { TripleNestedWithImplicitlyInheritedConfigTests(String text) { assertThat(text).isEqualTo("enigma"); } @Test void test() { } } } @Nested @NestedTestConfiguration(OVERRIDE) @SpringJUnitConfig(Config.class) @TestConstructor(autowireMode = ANNOTATED)
TripleNestedWithImplicitlyInheritedConfigTests
java
spring-projects__spring-boot
module/spring-boot-jdbc/src/test/java/org/springframework/boot/jdbc/autoconfigure/metrics/DataSourcePoolMetricsAutoConfigurationTests.java
{ "start": 14328, "end": 14810 }
class ____ implements BeanPostProcessor, PriorityOrdered { @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof HikariDataSource dataSource) { try { dataSource.getConnection().close(); } catch (SQLException ex) { throw new IllegalStateException(ex); } } return bean; } } } }
HikariSealer
java
apache__camel
components/camel-servicenow/camel-servicenow-component/src/main/java/org/apache/camel/component/servicenow/ServiceNowParams.java
{ "start": 1015, "end": 9172 }
enum ____ implements ServiceNowParam { PARAM_SYS_ID("sys_id", ServiceNowConstants.PARAM_SYS_ID, String.class), PARAM_USER_SYS_ID("user_sysid", ServiceNowConstants.PARAM_USER_SYS_ID, String.class), PARAM_USER_ID("user_id", ServiceNowConstants.PARAM_USER_ID, String.class), PARAM_CART_ITEM_ID("cart_item_id", ServiceNowConstants.PARAM_CART_ITEM_ID, String.class), PARAM_FILE_NAME("file_name", ServiceNowConstants.PARAM_FILE_NAME, String.class), PARAM_TABLE_NAME("table_name", ServiceNowConstants.PARAM_TABLE_NAME, String.class), PARAM_TABLE_SYS_ID("table_sys_id", ServiceNowConstants.PARAM_TABLE_SYS_ID, String.class), PARAM_ENCRYPTION_CONTEXT("encryption_context", ServiceNowConstants.PARAM_ENCRYPTION_CONTEXT, String.class), SYSPARM_CATEGORY("sysparm_category", ServiceNowConstants.SYSPARM_CATEGORY, String.class), SYSPARM_TYPE("sysparm_type", ServiceNowConstants.SYSPARM_TYPE, String.class), SYSPARM_CATALOG("sysparm_catalog", ServiceNowConstants.SYSPARM_CATALOG, String.class), SYSPARM_QUERY("sysparm_query", ServiceNowConstants.SYSPARM_QUERY, String.class), SYSPARM_DISPLAY_VALUE("sysparm_display_value", ServiceNowConstants.SYSPARM_DISPLAY_VALUE, String.class, ServiceNowConfiguration::getDisplayValue), SYSPARM_INPUT_DISPLAY_VALUE("sysparm_input_display_value", ServiceNowConstants.SYSPARM_INPUT_DISPLAY_VALUE, Boolean.class, ServiceNowConfiguration::getInputDisplayValue), SYSPARM_EXCLUDE_REFERENCE_LINK("sysparm_exclude_reference_link", ServiceNowConstants.SYSPARM_EXCLUDE_REFERENCE_LINK, Boolean.class, ServiceNowConfiguration::getExcludeReferenceLink), SYSPARM_FIELDS("sysparm_fields", ServiceNowConstants.SYSPARM_FIELDS, String.class), SYSPARM_LIMIT("sysparm_limit", ServiceNowConstants.SYSPARM_LIMIT, Integer.class), SYSPARM_TEXT("sysparm_text", ServiceNowConstants.SYSPARM_TEXT, String.class), SYSPARM_OFFSET("sysparm_offset", ServiceNowConstants.SYSPARM_OFFSET, Integer.class), SYSPARM_VIEW("sysparm_view", ServiceNowConstants.SYSPARM_VIEW, String.class), SYSPARM_SUPPRESS_AUTO_SYS_FIELD("sysparm_suppress_auto_sys_field", ServiceNowConstants.SYSPARM_SUPPRESS_AUTO_SYS_FIELD, Boolean.class, ServiceNowConfiguration::getSuppressAutoSysField), SYSPARM_SUPPRESS_PAGINATION_HEADER("sysparm_suppress_pagination_header", ServiceNowConstants.SYSPARM_SUPPRESS_PAGINATION_HEADER, Boolean.class, ServiceNowConfiguration::getSuppressPaginationHeader), SYSPARM_MIN_FIELDS("sysparm_min_fields", ServiceNowConstants.SYSPARM_MIN_FIELDS, String.class), SYSPARM_MAX_FIELDS("sysparm_max_fields", ServiceNowConstants.SYSPARM_MAX_FIELDS, String.class), SYSPARM_SUM_FIELDS("sysparm_sum_fields", ServiceNowConstants.SYSPARM_SUM_FIELDS, String.class), SYSPARM_AVG_FIELDS("sysparm_avg_fields", ServiceNowConstants.SYSPARM_AVG_FIELDS, String.class), SYSPARM_COUNT("sysparm_count", ServiceNowConstants.SYSPARM_COUNT, Boolean.class), SYSPARM_GROUP_BY("sysparm_group_by", ServiceNowConstants.SYSPARM_GROUP_BY, String.class), SYSPARM_ORDER_BY("sysparm_order_by", ServiceNowConstants.SYSPARM_ORDER_BY, String.class), SYSPARM_HAVING("sysparm_having", ServiceNowConstants.SYSPARM_HAVING, String.class), SYSPARM_UUID("sysparm_uuid", ServiceNowConstants.SYSPARM_UUID, String.class), SYSPARM_BREAKDOWN("sysparm_breakdown", ServiceNowConstants.SYSPARM_BREAKDOWN, String.class), SYSPARM_INCLUDE_SCORES("sysparm_include_scores", ServiceNowConstants.SYSPARM_INCLUDE_SCORES, Boolean.class, ServiceNowConfiguration::getIncludeScores), SYSPARM_INCLUDE_SCORE_NOTES("sysparm_include_score_notes", ServiceNowConstants.SYSPARM_INCLUDE_SCORE_NOTES, Boolean.class, ServiceNowConfiguration::getIncludeScoreNotes), SYSPARM_INCLUDE_AGGREGATES("sysparm_include_aggregates", ServiceNowConstants.SYSPARM_INCLUDE_AGGREGATES, Boolean.class, ServiceNowConfiguration::getIncludeAggregates), SYSPARM_INCLUDE_AVAILABLE_BREAKDOWNS("sysparm_include_available_breakdowns", ServiceNowConstants.SYSPARM_INCLUDE_AVAILABLE_BREAKDOWNS, Boolean.class, ServiceNowConfiguration::getIncludeAvailableBreakdowns), SYSPARM_INCLUDE_AVAILABLE_AGGREGATES("sysparm_include_available_aggregates", ServiceNowConstants.SYSPARM_INCLUDE_AVAILABLE_AGGREGATES, Boolean.class, ServiceNowConfiguration::getIncludeAvailableAggregates), SYSPARM_FAVORITES("sysparm_favorites", ServiceNowConstants.SYSPARM_FAVORITES, Boolean.class, ServiceNowConfiguration::getFavorites), SYSPARM_KEY("sysparm_key", ServiceNowConstants.SYSPARM_KEY, Boolean.class, ServiceNowConfiguration::getKey), SYSPARM_TARGET("sysparm_target", ServiceNowConstants.SYSPARM_TARGET, Boolean.class, ServiceNowConfiguration::getTarget), SYSPARM_DISPLAY("sysparm_display", ServiceNowConstants.SYSPARM_DISPLAY, String.class, ServiceNowConfiguration::getDisplay), SYSPARM_PER_PAGE("sysparm_per_page", ServiceNowConstants.SYSPARM_PER_PAGE, Integer.class, ServiceNowConfiguration::getPerPage), SYSPARM_SORT_BY("sysparm_sortby", ServiceNowConstants.SYSPARM_SORT_BY, String.class, ServiceNowConfiguration::getSortBy), SYSPARM_SORT_DIR("sysparm_sortdir", ServiceNowConstants.SYSPARM_SORT_DIR, String.class, ServiceNowConfiguration::getSortDir), SYSPARM_CONTAINS("sysparm_contains", ServiceNowConstants.SYSPARM_CONTAINS, String.class), SYSPARM_TAGS("sysparm_tags", ServiceNowConstants.SYSPARM_TAGS, String.class), SYSPARM_PAGE("sysparm_page", ServiceNowConstants.SYSPARM_PAGE, String.class), SYSPARM_ELEMENTS_FILTER("sysparm_elements_filter", ServiceNowConstants.SYSPARM_ELEMENTS_FILTER, String.class), SYSPARM_BREAKDOWN_RELATION("sysparm_breakdown_relation", ServiceNowConstants.SYSPARM_BREAKDOWN_RELATION, String.class), SYSPARM_DATA_SOURCE("sysparm_data_source", ServiceNowConstants.SYSPARM_DATA_SOURCE, String.class), SYSPARM_TOP_LEVEL_ONLY("sysparm_top_level_only", ServiceNowConstants.SYSPARM_TOP_LEVEL_ONLY, Boolean.class, ServiceNowConfiguration::getTopLevelOnly); private final String id; private final String header; private final Class<?> type; private final Function<ServiceNowConfiguration, ?> defaultValueSupplier; ServiceNowParams(String id, String header, Class<?> type) { this(id, header, type, null); } ServiceNowParams(String id, String header, Class<?> type, Function<ServiceNowConfiguration, ?> defaultValueSupplier) { ObjectHelper.notNull(id, "ServiceNowSysParam (id)"); ObjectHelper.notNull(header, "ServiceNowSysParam (header)"); ObjectHelper.notNull(type, "ServiceNowSysParam (type)"); this.id = id; this.header = header.startsWith(ServiceNowConstants.CAMEL_HEADER_PREFIX) ? header : ServiceNowConstants.CAMEL_HEADER_PREFIX + StringHelper.capitalize(header); this.type = type; this.defaultValueSupplier = defaultValueSupplier; } @Override public String getId() { return id; } @Override public String getHeader() { return header; } @Override public Class<?> getType() { return type; } @Override public Object getDefaultValue(ServiceNowConfiguration configuration) { return defaultValueSupplier != null ? defaultValueSupplier.apply(configuration) : null; } @Override public Object getHeaderValue(Message message) { return message.getHeader(header, type); } @Override public Object getHeaderValue(Message message, ServiceNowConfiguration configuration) { return message.getHeader(header, getDefaultValue(configuration), type); } }
ServiceNowParams
java
google__guava
android/guava/src/com/google/common/util/concurrent/Striped.java
{ "start": 20929, "end": 21141 }
class ____ extends Semaphore { // See PaddedReentrantLock comment long unused1; long unused2; long unused3; PaddedSemaphore(int permits) { super(permits, false); } } }
PaddedSemaphore
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/resilience/annotation/EnableResilientMethods.java
{ "start": 1563, "end": 2783 }
interface ____ { /** * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed * to standard Java interface-based proxies. * <p>The default is {@code false}. * <p>Note that setting this attribute to {@code true} will only affect * {@link RetryAnnotationBeanPostProcessor} and * {@link ConcurrencyLimitBeanPostProcessor}. * <p>It is usually recommendable to rely on a global default proxy configuration * instead, with specific proxy requirements for certain beans expressed through * a {@link org.springframework.context.annotation.Proxyable} annotation on * the affected bean classes. * @see org.springframework.aop.config.AopConfigUtils#forceAutoProxyCreatorToUseClassProxying */ boolean proxyTargetClass() default false; /** * Indicate the order in which the {@link RetryAnnotationBeanPostProcessor} * and {@link ConcurrencyLimitBeanPostProcessor} should be applied. * <p>The default is {@link Ordered#LOWEST_PRECEDENCE - 1} in order to run * after all common post-processors, except for {@code @EnableAsync}. * @see org.springframework.scheduling.annotation.EnableAsync#order() */ int order() default Ordered.LOWEST_PRECEDENCE - 1; }
EnableResilientMethods
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/DirMarkerTracker.java
{ "start": 1989, "end": 7241 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(DirMarkerTracker.class); /** * all leaf markers. */ private final Map<Path, Marker> leafMarkers = new TreeMap<>(); /** * all surplus markers. */ private final Map<Path, Marker> surplusMarkers = new TreeMap<>(); /** * Base path of the tracking operation. */ private final Path basePath; /** * Should surplus markers be recorded in * the {@link #surplusMarkers} map? */ private final boolean recordSurplusMarkers; /** * last parent directory checked. */ private Path lastDirChecked; /** * Count of scans; used for test assertions. */ private int scanCount; /** * How many files were found. */ private int filesFound; /** * How many markers were found. */ private int markersFound; /** * How many objects of any kind were found? */ private int objectsFound; /** * Construct. * <p> * The base path is currently only used for information rather than * validating paths supplied in other methods. * @param basePath base path of track * @param recordSurplusMarkers save surplus markers to a map? */ public DirMarkerTracker(final Path basePath, boolean recordSurplusMarkers) { this.basePath = basePath; this.recordSurplusMarkers = recordSurplusMarkers; } /** * Get the base path of the tracker. * @return the path */ public Path getBasePath() { return basePath; } /** * A marker has been found; this may or may not be a leaf. * <p> * Trigger a move of all markers above it into the surplus map. * @param path marker path * @param key object key * @param source listing source * @return the surplus markers found. */ public List<Marker> markerFound(Path path, final String key, final S3ALocatedFileStatus source) { markersFound++; leafMarkers.put(path, new Marker(path, key, source)); return pathFound(path, key, source); } /** * A file has been found. Trigger a move of all * markers above it into the surplus map. * @param path marker path * @param key object key * @param source listing source * @return the surplus markers found. */ public List<Marker> fileFound(Path path, final String key, final S3ALocatedFileStatus source) { filesFound++; return pathFound(path, key, source); } /** * A path has been found. * <p> * Declare all markers above it as surplus * @param path marker path * @param key object key * @param source listing source * @return the surplus markers found. */ private List<Marker> pathFound(Path path, final String key, final S3ALocatedFileStatus source) { objectsFound++; List<Marker> removed = new ArrayList<>(); // all parent entries are superfluous final Path parent = path.getParent(); if (parent == null || parent.equals(lastDirChecked)) { // short cut exit return removed; } removeParentMarkers(parent, removed); lastDirChecked = parent; return removed; } /** * Remove all markers from the path and its parents from the * {@link #leafMarkers} map. * <p> * if {@link #recordSurplusMarkers} is true, the marker is * moved to the surplus map. Not doing this is simply an * optimisation designed to reduce risk of excess memory consumption * when renaming (hypothetically) large directory trees. * @param path path to start at * @param removed list of markers removed; is built up during the * recursive operation. */ private void removeParentMarkers(final Path path, List<Marker> removed) { if (path == null || path.isRoot()) { return; } scanCount++; removeParentMarkers(path.getParent(), removed); final Marker value = leafMarkers.remove(path); if (value != null) { // marker is surplus removed.add(value); if (recordSurplusMarkers) { surplusMarkers.put(path, value); } } } /** * Get the map of leaf markers. * @return all leaf markers. */ public Map<Path, Marker> getLeafMarkers() { return leafMarkers; } /** * Get the map of surplus markers. * <p> * Empty if they were not being recorded. * @return all surplus markers. */ public Map<Path, Marker> getSurplusMarkers() { return surplusMarkers; } public Path getLastDirChecked() { return lastDirChecked; } /** * How many objects were found. * @return count */ public int getObjectsFound() { return objectsFound; } public int getScanCount() { return scanCount; } public int getFilesFound() { return filesFound; } public int getMarkersFound() { return markersFound; } @Override public String toString() { return "DirMarkerTracker{" + "leafMarkers=" + leafMarkers.size() + ", surplusMarkers=" + surplusMarkers.size() + ", lastDirChecked=" + lastDirChecked + ", filesFound=" + filesFound + ", scanCount=" + scanCount + '}'; } /** * This is a marker entry stored in the map and * returned as markers are deleted. */ public static final
DirMarkerTracker
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/persistence/TestingStateHandleStore.java
{ "start": 1562, "end": 5579 }
class ____<T extends Serializable> implements StateHandleStore<T, IntegerResourceVersion> { private final BiFunctionWithException<String, T, RetrievableStateHandle<T>, Exception> addFunction; private final ThrowingConsumer<Tuple3<String, IntegerResourceVersion, T>, Exception> replaceConsumer; private final FunctionWithException<String, IntegerResourceVersion, Exception> existsFunction; private final FunctionWithException<String, RetrievableStateHandle<T>, Exception> getFunction; private final SupplierWithException<List<Tuple2<RetrievableStateHandle<T>, String>>, Exception> getAllSupplier; private final SupplierWithException<Collection<String>, Exception> getAllHandlesSupplier; private final FunctionWithException<String, Boolean, Exception> removeFunction; private final RunnableWithException clearEntriesRunnable; private final ThrowingConsumer<String, Exception> releaseConsumer; private final RunnableWithException releaseAllHandlesRunnable; private TestingStateHandleStore( BiFunctionWithException<String, T, RetrievableStateHandle<T>, Exception> addFunction, ThrowingConsumer<Tuple3<String, IntegerResourceVersion, T>, Exception> replaceConsumer, FunctionWithException<String, IntegerResourceVersion, Exception> existsFunction, FunctionWithException<String, RetrievableStateHandle<T>, Exception> getFunction, SupplierWithException<List<Tuple2<RetrievableStateHandle<T>, String>>, Exception> getAllSupplier, SupplierWithException<Collection<String>, Exception> getAllHandlesSupplier, FunctionWithException<String, Boolean, Exception> removeFunction, RunnableWithException clearEntriesRunnable, ThrowingConsumer<String, Exception> releaseConsumer, RunnableWithException releaseAllHandlesRunnable) { this.addFunction = addFunction; this.replaceConsumer = replaceConsumer; this.existsFunction = existsFunction; this.getFunction = getFunction; this.getAllSupplier = getAllSupplier; this.getAllHandlesSupplier = getAllHandlesSupplier; this.removeFunction = removeFunction; this.clearEntriesRunnable = clearEntriesRunnable; this.releaseConsumer = releaseConsumer; this.releaseAllHandlesRunnable = releaseAllHandlesRunnable; } @Override @Nullable public RetrievableStateHandle<T> addAndLock(String name, T state) throws Exception { return addFunction.apply(name, state); } @Override public void replace(String name, IntegerResourceVersion resourceVersion, T state) throws Exception { replaceConsumer.accept(new Tuple3<>(name, resourceVersion, state)); } @Override public IntegerResourceVersion exists(String name) throws Exception { return existsFunction.apply(name); } @Override @Nullable public RetrievableStateHandle<T> getAndLock(String name) throws Exception { return getFunction.apply(name); } @Override public List<Tuple2<RetrievableStateHandle<T>, String>> getAllAndLock() throws Exception { return getAllSupplier.get(); } @Override public Collection<String> getAllHandles() throws Exception { return getAllHandlesSupplier.get(); } @Override public boolean releaseAndTryRemove(String name) throws Exception { return removeFunction.apply(name); } @Override public void clearEntries() throws Exception { clearEntriesRunnable.run(); } @Override public void release(String name) throws Exception { releaseConsumer.accept(name); } @Override public void releaseAll() throws Exception { releaseAllHandlesRunnable.run(); } public static <T extends Serializable> Builder<T> newBuilder() { return new Builder<>(); } /** Builder
TestingStateHandleStore
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/floatarray/FloatArrayAssert_isNullOrEmpty_Test.java
{ "start": 939, "end": 1394 }
class ____ extends FloatArrayAssertBaseTest { @Override protected FloatArrayAssert invoke_api_method() { assertions.isNullOrEmpty(); return null; } @Override protected void verify_internal_effects() { verify(arrays).assertNullOrEmpty(getInfo(assertions), getActual(assertions)); } @Override @Test public void should_return_this() { // Disable this test since isNullOrEmpty is void } }
FloatArrayAssert_isNullOrEmpty_Test
java
apache__camel
components/camel-spring-parent/camel-undertow-spring-security/src/main/java/org/apache/camel/component/spring/security/SpringSecurityConfiguration.java
{ "start": 895, "end": 1152 }
interface ____ { /** * Provides security filter gained from configured spring security (5+). Filter could be obtained for example from * DelegatingFilterProxyRegistrationBean. */ Filter getSecurityFilter(); }
SpringSecurityConfiguration
java
apache__camel
components/camel-olingo4/camel-olingo4-api/src/test/java/org/apache/camel/component/olingo4/Olingo4AppAPITest.java
{ "start": 34872, "end": 36626 }
class ____<T> implements Olingo4ResponseHandler<T> { private T response; private Exception error; private CountDownLatch latch = new CountDownLatch(1); @Override public void onResponse(T response, Map<String, String> responseHeaders) { this.response = response; if (LOG.isDebugEnabled()) { if (response instanceof ClientEntitySet) { LOG.debug("Received response: {}", prettyPrint((ClientEntitySet) response)); } else if (response instanceof ClientEntity) { LOG.debug("Received response: {}", prettyPrint((ClientEntity) response)); } else { LOG.debug("Received response: {}", response); } } latch.countDown(); } @Override public void onException(Exception ex) { error = ex; latch.countDown(); } @Override public void onCanceled() { error = new IllegalStateException("Request Canceled"); latch.countDown(); } public T await() throws Exception { return await(TIMEOUT, TimeUnit.SECONDS); } public T await(long timeout, TimeUnit unit) throws Exception { assertTrue(latch.await(timeout, unit), "Timeout waiting for response"); if (error != null) { throw error; } assertNotNull(response, "Response"); return response; } public void reset() { latch.countDown(); latch = new CountDownLatch(1); response = null; error = null; } } }
TestOlingo4ResponseHandler
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/MatcherShouldHaveGroup_create_Test.java
{ "start": 1080, "end": 2036 }
class ____ { @Test void should_create_error_message_with_int_group_identifier() { // GIVEN Matcher actual = compile("a*").matcher("abc"); // WHEN String message = shouldHaveGroup(actual, 1).create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting java.util.regex.Matcher[pattern=a* region=0,3 lastmatch=] to have group 1")); } @Test void should_create_error_message_with_string_group_identifier() { // GIVEN Matcher actual = compile("a*").matcher("abc"); // WHEN String message = shouldHaveGroup(actual, "foo").create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting java.util.regex.Matcher[pattern=a* region=0,3 lastmatch=] to have group \"foo\"")); } }
MatcherShouldHaveGroup_create_Test
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/DigitTest.java
{ "start": 734, "end": 4379 }
class ____ extends TestCase { private char[] text = "[-5.041598256063065E-20,-7210028408342716000]".toCharArray(); private int COUNT = 1000 * 1000; public void test_perf() throws Exception { for (int i = 0; i < 50; ++i) { f_isDigitBitSet(); f_isDigitArray(); f_isDigitRange(); f_isDigitSwitch(); f_isDigitProhibit(); System.out.println(); System.out.println(); } } public void f_isDigitBitSet() throws Exception { long startNano = System.nanoTime(); for (int i = 0; i < COUNT; ++i) { for (char ch : text) { isDigitBitSet(ch); } } long nano = System.nanoTime() - startNano; System.out.println("bitset \t: " + NumberFormat.getInstance().format(nano)); } public void f_isDigitRange() throws Exception { long startNano = System.nanoTime(); for (int i = 0; i < COUNT; ++i) { for (char ch : text) { isDigitRange(ch); } } long nano = System.nanoTime() - startNano; System.out.println("range \t: " + NumberFormat.getInstance().format(nano)); } public void f_isDigitArray() throws Exception { long startNano = System.nanoTime(); for (int i = 0; i < COUNT; ++i) { for (char ch : text) { isDigitArray(ch); } } long nano = System.nanoTime() - startNano; System.out.println("array \t: " + NumberFormat.getInstance().format(nano)); } public void f_isDigitSwitch() throws Exception { long startNano = System.nanoTime(); for (int i = 0; i < COUNT; ++i) { for (char ch : text) { isDigitSwitch(ch); } } long nano = System.nanoTime() - startNano; System.out.println("swtich \t: " + NumberFormat.getInstance().format(nano)); } public void f_isDigitProhibit() throws Exception { long startNano = System.nanoTime(); for (int i = 0; i < COUNT; ++i) { for (char ch : text) { isDigitProhibit(ch); } } long nano = System.nanoTime() - startNano; System.out.println("prohi \t: " + NumberFormat.getInstance().format(nano)); } private static final boolean[] digitBits = new boolean[256]; static { for (char ch = '0'; ch <= '9'; ++ch) { digitBits[ch] = true; } } public final boolean isDigitArray(char ch) { return digitBits[ch]; } private static final DetectProhibitChar digitDetectProhibitChar = new DetectProhibitChar(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }); public final boolean isDigitProhibit(char ch) { return digitDetectProhibitChar.isProhibitChar(ch); } public final boolean isDigitRange(char ch) { return ch >= '0' && ch <= '9'; } private static final BitSet bits = new BitSet(); static { for (char ch = '0'; ch <= '9'; ++ch) { bits.set(ch, true); } } public final boolean isDigitBitSet(char ch) { return bits.get(ch); } private final boolean isDigitSwitch(char ch) { switch (ch) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return true; default: return false; } } }
DigitTest
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/junit/jupiter/SoftAssertionsExtension.java
{ "start": 9447, "end": 18011 }
class ____ Collection<Field> softAssertionsFields = findFields(testInstance.getClass(), field -> isAnnotated(field, InjectSoftAssertions.class), HierarchyTraversalMode.BOTTOM_UP); for (Field softAssertionsField : softAssertionsFields) { checkIsNotStaticOrFinal(softAssertionsField); Class<? extends SoftAssertionsProvider> softAssertionsProviderClass = asSoftAssertionsProviderClass(softAssertionsField, softAssertionsField.getType()); checkIsNotAbstract(softAssertionsField, softAssertionsProviderClass); checkHasDefaultConstructor(softAssertionsField, softAssertionsProviderClass); SoftAssertionsProvider softAssertions = getSoftAssertionsProvider(context, softAssertionsProviderClass); setTestInstanceSoftAssertionsField(testInstance, softAssertionsField, softAssertions); } } @Override public void beforeEach(ExtensionContext context) throws Exception { AssertionErrorCollector collector = getAssertionErrorCollector(context); if (isPerClassConcurrent(context)) { // If the current context is "per class+concurrent", then getSoftAssertionsProvider() will have already set the delegate // for all the soft assertions provider to the thread-local error collector, so all we need to do is set the tlec's value // for the current thread. ThreadLocalErrorCollector tlec = getThreadLocalCollector(context); tlec.setDelegate(collector); } else { // Make sure that all of the soft assertion provider instances have their delegate initialised to the assertion error // collector for the current context. Also check enclosing contexts (in the case of nested tests). while (initialiseDelegate(context, collector) && context.getParent().isPresent()) { context = context.getParent().get(); } } } private static boolean initialiseDelegate(ExtensionContext context, AssertionErrorCollector collector) { Collection<SoftAssertionsProvider> providers = getSoftAssertionsProviders(context); if (providers == null) return false; providers.forEach(x -> x.setDelegate(collector)); return context.getParent().isPresent(); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { // Abort if parameter type is unsupported. if (isUnsupportedParameterType(parameterContext.getParameter())) return false; Executable executable = parameterContext.getDeclaringExecutable(); // @Testable is used as a meta-annotation on @Test, @TestFactory, @TestTemplate, etc. boolean isTestableMethod = executable instanceof Method && isAnnotated(executable, Testable.class); if (!isTestableMethod) { throw new ParameterResolutionException("Configuration error: cannot resolve SoftAssertionsProvider instances for [%s]. Only test methods are supported.".formatted( executable)); } Class<?> parameterType = parameterContext.getParameter().getType(); if (isAbstract(parameterType.getModifiers())) { throw new ParameterResolutionException("Configuration error: the resolved SoftAssertionsProvider implementation [%s] is abstract and cannot be instantiated.".formatted( executable)); } try { parameterType.getDeclaredConstructor(); } catch (@SuppressWarnings("unused") Exception e) { throw new ParameterResolutionException("Configuration error: the resolved SoftAssertionsProvider implementation [%s] has no default constructor and cannot be instantiated.".formatted( executable)); } return true; } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { // The parameter type is guaranteed to be an instance of SoftAssertionsProvider @SuppressWarnings("unchecked") Class<? extends SoftAssertionsProvider> concreteSoftAssertionsProviderType = (Class<? extends SoftAssertionsProvider>) parameterContext.getParameter() .getType(); SoftAssertionsProvider provider = ReflectionSupport.newInstance(concreteSoftAssertionsProviderType); provider.setDelegate(getAssertionErrorCollector(extensionContext)); return provider; } @Override public void afterTestExecution(ExtensionContext extensionContext) { AssertionErrorCollector collector; if (isPerClassConcurrent(extensionContext)) { ThreadLocalErrorCollector tlec = getThreadLocalCollector(extensionContext); collector = tlec.getDelegate() .orElseThrow(() -> new IllegalStateException("Expecting delegate to be present for current context")); tlec.reset(); } else { collector = getAssertionErrorCollector(extensionContext); } AbstractSoftAssertions.assertAll(collector); } private static boolean isUnsupportedParameterType(Parameter parameter) { Class<?> type = parameter.getType(); return !SoftAssertionsProvider.class.isAssignableFrom(type); } private static Store getStore(ExtensionContext extensionContext) { return extensionContext.getStore(SOFT_ASSERTIONS_EXTENSION_NAMESPACE); } private static ThreadLocalErrorCollector getThreadLocalCollector(ExtensionContext context) { return getStore(context).getOrComputeIfAbsent(ThreadLocalErrorCollector.class, unused -> new ThreadLocalErrorCollector(), ThreadLocalErrorCollector.class); } /** * Returns the {@link AssertionErrorCollector} for the given extension context, if none exists for the current context then * one is created. * <p> * This method is thread safe - all extensions attempting to access the {@code AssertionErrorCollector} for a given context * through this method will get a reference to the same {@code AssertionErrorCollector} instance, regardless of the order * in which they are called. * <p> * Third-party extensions that wish to provide soft-asserting behavior can use this method to obtain the current * {@code AssertionErrorCollector} instance and record their assertion failures into it by calling * {@link AssertionErrorCollector#collectAssertionError(AssertionError) collectAssertionError(AssertionError)}.<br> * In this way their soft assertions will integrate with the existing AssertJ soft assertions and the assertion failures (both * AssertJ's and the third-party extension's) will be reported in the order that they occurred. * * @param context the {@code ExtensionContext} whose error collector we are attempting to retrieve. * @return The {@code AssertionErrorCollector} for the given context. */ @Beta public static AssertionErrorCollector getAssertionErrorCollector(ExtensionContext context) { return getStore(context).getOrComputeIfAbsent(AssertionErrorCollector.class, unused -> new DefaultAssertionErrorCollector(), AssertionErrorCollector.class); } @SuppressWarnings("unchecked") private static Collection<SoftAssertionsProvider> getSoftAssertionsProviders(ExtensionContext context) { return getStore(context).getOrComputeIfAbsent(Collection.class, unused -> new ConcurrentLinkedQueue<>(), Collection.class); } private static <T extends SoftAssertionsProvider> T instantiateProvider(ExtensionContext context, Class<T> providerType) { T softAssertions = ReflectionSupport.newInstance(providerType); // If we are running single-threaded, we won't have any concurrency issues. Likewise, // if we are running "per-method", then every test gets its own instance and again there // won't be any concurrency issues. But we need to special-case the situation where // we are running *both* per
hierarchy
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/VoidMissingNullableTest.java
{ "start": 1025, "end": 1832 }
class ____ { private final CompilationTestHelper conservativeCompilationHelper = CompilationTestHelper.newInstance(VoidMissingNullable.class, getClass()); private final CompilationTestHelper aggressiveCompilationHelper = CompilationTestHelper.newInstance(VoidMissingNullable.class, getClass()) .setArgs("-XepOpt:Nullness:Conservative=false"); private final BugCheckerRefactoringTestHelper aggressiveRefactoringHelper = BugCheckerRefactoringTestHelper.newInstance(VoidMissingNullable.class, getClass()) .setArgs("-XepOpt:Nullness:Conservative=false"); @Test public void positive() { aggressiveCompilationHelper .addSourceLines( "Test.java", """ import javax.annotation.Nullable;
VoidMissingNullableTest
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4553CoreArtifactFilterConsidersGroupIdTest.java
{ "start": 1193, "end": 2276 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Verify that the core artifact filter considers both artifact id and group id. * * @throws Exception in case of failure */ @Test public void testit() throws Exception { File testDir = extractResources("/mng-4553"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.deleteArtifacts("org.apache.maven.its.mng4553"); verifier.filterFile("settings-template.xml", "settings.xml"); verifier.addCliArgument("-s"); verifier.addCliArgument("settings.xml"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); Properties pclProps = verifier.loadProperties("target/pcl.properties"); assertNotNull(pclProps.getProperty("mng4553.properties")); assertEquals("1", pclProps.getProperty("mng4553.properties.count")); } }
MavenITmng4553CoreArtifactFilterConsidersGroupIdTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/impl/prefetch/SingleFilePerBlockCache.java
{ "start": 4093, "end": 21273 }
enum ____ { READ, WRITE } private Entry previous; private Entry next; Entry(int blockNumber, Path path, int size, long checksum) { this.blockNumber = blockNumber; this.path = path; this.size = size; this.checksum = checksum; this.lock = new ReentrantReadWriteLock(); this.previous = null; this.next = null; } @Override public String toString() { return String.format( "([%03d] %s: size = %d, checksum = %d)", blockNumber, path, size, checksum); } /** * Take the read or write lock. * * @param lockType type of the lock. */ private void takeLock(LockType lockType) { if (LockType.READ == lockType) { lock.readLock().lock(); } else if (LockType.WRITE == lockType) { lock.writeLock().lock(); } } /** * Release the read or write lock. * * @param lockType type of the lock. */ private void releaseLock(LockType lockType) { if (LockType.READ == lockType) { lock.readLock().unlock(); } else if (LockType.WRITE == lockType) { lock.writeLock().unlock(); } } /** * Try to take the read or write lock within the given timeout. * * @param lockType type of the lock. * @param timeout the time to wait for the given lock. * @param unit the time unit of the timeout argument. * @return true if the lock of the given lock type was acquired. */ private boolean takeLock(LockType lockType, long timeout, TimeUnit unit) { try { if (LockType.READ == lockType) { return lock.readLock().tryLock(timeout, unit); } else if (LockType.WRITE == lockType) { return lock.writeLock().tryLock(timeout, unit); } } catch (InterruptedException e) { LOG.warn("Thread interrupted while trying to acquire {} lock", lockType, e); Thread.currentThread().interrupt(); } return false; } private Entry getPrevious() { return previous; } private void setPrevious(Entry previous) { this.previous = previous; } private Entry getNext() { return next; } private void setNext(Entry next) { this.next = next; } } /** * Constructs an instance of a {@code SingleFilePerBlockCache}. * * @param prefetchingStatistics statistics for this stream. * @param maxBlocksCount max blocks count to be kept in cache at any time. * @param trackerFactory tracker with statistics to update */ public SingleFilePerBlockCache(PrefetchingStatistics prefetchingStatistics, int maxBlocksCount, DurationTrackerFactory trackerFactory) { this.prefetchingStatistics = requireNonNull(prefetchingStatistics); this.closed = new AtomicBoolean(false); this.maxBlocksCount = maxBlocksCount; Preconditions.checkArgument(maxBlocksCount > 0, "maxBlocksCount should be more than 0"); blocks = new ConcurrentHashMap<>(); blocksLock = new ReentrantReadWriteLock(); this.trackerFactory = trackerFactory != null ? trackerFactory : stubDurationTrackerFactory(); } /** * Indicates whether the given block is in this cache. */ @Override public boolean containsBlock(int blockNumber) { return blocks.containsKey(blockNumber); } /** * Gets the blocks in this cache. */ @Override public Iterable<Integer> blocks() { return Collections.unmodifiableList(new ArrayList<>(blocks.keySet())); } /** * Gets the number of blocks in this cache. */ @Override public int size() { return blocks.size(); } /** * Gets the block having the given {@code blockNumber}. * * @throws IllegalArgumentException if buffer is null. */ @Override public void get(int blockNumber, ByteBuffer buffer) throws IOException { if (closed.get()) { return; } checkNotNull(buffer, "buffer"); Entry entry = getEntry(blockNumber); entry.takeLock(Entry.LockType.READ); try { buffer.clear(); readFile(entry.path, buffer); buffer.rewind(); validateEntry(entry, buffer); } finally { entry.releaseLock(Entry.LockType.READ); } } protected int readFile(Path path, ByteBuffer buffer) throws IOException { int numBytesRead = 0; int numBytes; try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) { while ((numBytes = channel.read(buffer)) > 0) { numBytesRead += numBytes; } buffer.limit(buffer.position()); } return numBytesRead; } private Entry getEntry(int blockNumber) { Validate.checkNotNegative(blockNumber, "blockNumber"); Entry entry = blocks.get(blockNumber); if (entry == null) { throw new IllegalStateException(String.format("block %d not found in cache", blockNumber)); } numGets++; addToLinkedListHead(entry); return entry; } /** * Helper method to add the given entry to the head of the linked list. * * @param entry Block entry to add. */ private void addToLinkedListHead(Entry entry) { blocksLock.writeLock().lock(); try { addToHeadOfLinkedList(entry); } finally { blocksLock.writeLock().unlock(); } } /** * Add the given entry to the head of the linked list. * * @param entry Block entry to add. */ private void addToHeadOfLinkedList(Entry entry) { if (head == null) { head = entry; tail = entry; } LOG.debug( "Block num {} to be added to the head. Current head block num: {} and tail block num: {}", entry.blockNumber, head.blockNumber, tail.blockNumber); if (entry != head) { Entry prev = entry.getPrevious(); Entry nxt = entry.getNext(); // no-op if the block is already evicted if (!blocks.containsKey(entry.blockNumber)) { return; } if (prev != null) { prev.setNext(nxt); } if (nxt != null) { nxt.setPrevious(prev); } entry.setPrevious(null); entry.setNext(head); head.setPrevious(entry); head = entry; if (prev != null && prev.getNext() == null) { tail = prev; } } } /** * Puts the given block in this cache. * * @param blockNumber the block number, used as a key for blocks map. * @param buffer buffer contents of the given block to be added to this cache. * @param conf the configuration. * @param localDirAllocator the local dir allocator instance. * @throws IOException if either local dir allocator fails to allocate file or if IO error * occurs while writing the buffer content to the file. * @throws IllegalArgumentException if buffer is null, or if buffer.limit() is zero or negative. */ @Override public void put(int blockNumber, ByteBuffer buffer, Configuration conf, LocalDirAllocator localDirAllocator) throws IOException { if (closed.get()) { return; } checkNotNull(buffer, "buffer"); if (blocks.containsKey(blockNumber)) { Entry entry = blocks.get(blockNumber); entry.takeLock(Entry.LockType.READ); try { validateEntry(entry, buffer); } finally { entry.releaseLock(Entry.LockType.READ); } addToLinkedListHead(entry); return; } Validate.checkPositiveInteger(buffer.limit(), "buffer.limit()"); Path blockFilePath = getCacheFilePath(conf, localDirAllocator); long size = Files.size(blockFilePath); if (size != 0) { String message = String.format("[%d] temp file already has data. %s (%d)", blockNumber, blockFilePath, size); throw new IllegalStateException(message); } writeFile(blockFilePath, buffer); long checksum = BufferData.getChecksum(buffer); Entry entry = new Entry(blockNumber, blockFilePath, buffer.limit(), checksum); blocks.put(blockNumber, entry); // Update stream_read_blocks_in_cache stats only after blocks map is updated with new file // entry to avoid any discrepancy related to the value of stream_read_blocks_in_cache. // If stream_read_blocks_in_cache is updated before updating the blocks map here, closing of // the input stream can lead to the removal of the cache file even before blocks is added // with the new cache file, leading to incorrect value of stream_read_blocks_in_cache. prefetchingStatistics.blockAddedToFileCache(); addToLinkedListAndEvictIfRequired(entry); } /** * Add the given entry to the head of the linked list and if the LRU cache size * exceeds the max limit, evict tail of the LRU linked list. * * @param entry Block entry to add. */ private void addToLinkedListAndEvictIfRequired(Entry entry) { blocksLock.writeLock().lock(); try { addToHeadOfLinkedList(entry); entryListSize++; if (entryListSize > maxBlocksCount && !closed.get()) { Entry elementToPurge = tail; tail = tail.getPrevious(); if (tail == null) { tail = head; } tail.setNext(null); elementToPurge.setPrevious(null); deleteBlockFileAndEvictCache(elementToPurge); } } finally { blocksLock.writeLock().unlock(); } } /** * Delete cache file as part of the block cache LRU eviction. * * @param elementToPurge Block entry to evict. */ private void deleteBlockFileAndEvictCache(Entry elementToPurge) { try (DurationTracker ignored = trackerFactory.trackDuration(STREAM_FILE_CACHE_EVICTION)) { boolean lockAcquired = elementToPurge.takeLock(Entry.LockType.WRITE, PrefetchConstants.PREFETCH_WRITE_LOCK_TIMEOUT, PrefetchConstants.PREFETCH_WRITE_LOCK_TIMEOUT_UNIT); if (!lockAcquired) { LOG.error("Cache file {} deletion would not be attempted as write lock could not" + " be acquired within {} {}", elementToPurge.path, PrefetchConstants.PREFETCH_WRITE_LOCK_TIMEOUT, PrefetchConstants.PREFETCH_WRITE_LOCK_TIMEOUT_UNIT); } else { try { if (Files.deleteIfExists(elementToPurge.path)) { entryListSize--; prefetchingStatistics.blockRemovedFromFileCache(); blocks.remove(elementToPurge.blockNumber); prefetchingStatistics.blockEvictedFromFileCache(); } } catch (IOException e) { LOG.warn("Failed to delete cache file {}", elementToPurge.path, e); } finally { elementToPurge.releaseLock(Entry.LockType.WRITE); } } } } private static final Set<? extends OpenOption> CREATE_OPTIONS = EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); protected void writeFile(Path path, ByteBuffer buffer) throws IOException { buffer.rewind(); try (WritableByteChannel writeChannel = Files.newByteChannel(path, CREATE_OPTIONS)) { while (buffer.hasRemaining()) { writeChannel.write(buffer); } } } /** * Return temporary file created based on the file path retrieved from local dir allocator. * * @param conf The configuration object. * @param localDirAllocator Local dir allocator instance. * @return Path of the temporary file created. * @throws IOException if IO error occurs while local dir allocator tries to retrieve path * from local FS or file creation fails or permission set fails. */ protected Path getCacheFilePath(final Configuration conf, final LocalDirAllocator localDirAllocator) throws IOException { return getTempFilePath(conf, localDirAllocator); } @Override public void close() throws IOException { if (closed.compareAndSet(false, true)) { LOG.debug(getStats()); deleteCacheFiles(); } } /** * Delete cache files as part of the close call. */ private void deleteCacheFiles() { int numFilesDeleted = 0; for (Entry entry : blocks.values()) { boolean lockAcquired = entry.takeLock(Entry.LockType.WRITE, PrefetchConstants.PREFETCH_WRITE_LOCK_TIMEOUT, PrefetchConstants.PREFETCH_WRITE_LOCK_TIMEOUT_UNIT); if (!lockAcquired) { LOG.error("Cache file {} deletion would not be attempted as write lock could not" + " be acquired within {} {}", entry.path, PrefetchConstants.PREFETCH_WRITE_LOCK_TIMEOUT, PrefetchConstants.PREFETCH_WRITE_LOCK_TIMEOUT_UNIT); continue; } try { if (Files.deleteIfExists(entry.path)) { prefetchingStatistics.blockRemovedFromFileCache(); numFilesDeleted++; } } catch (IOException e) { LOG.warn("Failed to delete cache file {}", entry.path, e); } finally { entry.releaseLock(Entry.LockType.WRITE); } } LOG.debug("Prefetch cache close: Deleted {} cache files", numFilesDeleted); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("stats: "); sb.append(getStats()); sb.append(", blocks:["); sb.append(getIntList(blocks())); sb.append("]"); return sb.toString(); } private void validateEntry(Entry entry, ByteBuffer buffer) { if (entry.size != buffer.limit()) { String message = String.format( "[%d] entry.size(%d) != buffer.limit(%d)", entry.blockNumber, entry.size, buffer.limit()); throw new IllegalStateException(message); } long checksum = BufferData.getChecksum(buffer); if (entry.checksum != checksum) { String message = String.format( "[%d] entry.checksum(%d) != buffer checksum(%d)", entry.blockNumber, entry.checksum, checksum); throw new IllegalStateException(message); } } /** * Produces a human readable list of blocks for the purpose of logging. * This method minimizes the length of returned list by converting * a contiguous list of blocks into a range. * for example, * 1, 3, 4, 5, 6, 8 becomes 1, 3~6, 8 */ private String getIntList(Iterable<Integer> nums) { List<String> numList = new ArrayList<>(); List<Integer> numbers = new ArrayList<Integer>(); for (Integer n : nums) { numbers.add(n); } Collections.sort(numbers); int index = 0; while (index < numbers.size()) { int start = numbers.get(index); int prev = start; int end = start; while ((++index < numbers.size()) && ((end = numbers.get(index)) == prev + 1)) { prev = end; } if (start == prev) { numList.add(Integer.toString(start)); } else { numList.add(String.format("%d~%d", start, prev)); } } return String.join(", ", numList); } private String getStats() { StringBuilder sb = new StringBuilder(); sb.append(String.format( "#entries = %d, #gets = %d", blocks.size(), numGets)); return sb.toString(); } private static final String CACHE_FILE_PREFIX = "fs-cache-"; /** * Determine if the cache space is available on the local FS. * * @param fileSize The size of the file. * @param conf The configuration. * @param localDirAllocator Local dir allocator instance. * @return True if the given file size is less than the available free space on local FS, * False otherwise. */ public static boolean isCacheSpaceAvailable(long fileSize, Configuration conf, LocalDirAllocator localDirAllocator) { try { Path cacheFilePath = getTempFilePath(conf, localDirAllocator); long freeSpace = new File(cacheFilePath.toString()).getUsableSpace(); LOG.info("fileSize = {}, freeSpace = {}", fileSize, freeSpace); Files.deleteIfExists(cacheFilePath); return fileSize < freeSpace; } catch (IOException e) { LOG.error("isCacheSpaceAvailable", e); return false; } } // The suffix (file extension) of each serialized index file. private static final String BINARY_FILE_SUFFIX = ".bin"; /** * Create temporary file based on the file path retrieved from local dir allocator * instance. The file is created with .bin suffix. The created file has been granted * posix file permissions available in TEMP_FILE_ATTRS. * * @param conf the configuration. * @param localDirAllocator the local dir allocator instance. * @return path of the file created. * @throws IOException if IO error occurs while local dir allocator tries to retrieve path * from local FS or file creation fails or permission set fails. */ private static Path getTempFilePath(final Configuration conf, final LocalDirAllocator localDirAllocator) throws IOException { org.apache.hadoop.fs.Path path = localDirAllocator.getLocalPathForWrite(CACHE_FILE_PREFIX, conf); File dir = new File(path.getParent().toUri().getPath()); String prefix = path.getName(); File tmpFile = File.createTempFile(prefix, BINARY_FILE_SUFFIX, dir); Path tmpFilePath = Paths.get(tmpFile.toURI()); return Files.setPosixFilePermissions(tmpFilePath, TEMP_FILE_ATTRS); } }
LockType
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/id/ForeignGeneratorTest.java
{ "start": 1264, "end": 1494 }
class ____ { @Id @GeneratedValue private Long id; @OneToOne @MapsId private Product product; public ProductDetails() { } public ProductDetails(Product product) { this.product = product; } } }
ProductDetails
java
elastic__elasticsearch
x-pack/plugin/ilm/src/main/java/org/elasticsearch/xpack/ilm/action/TransportGetStatusAction.java
{ "start": 1297, "end": 3011 }
class ____ extends TransportLocalProjectMetadataAction<GetStatusAction.Request, Response> { /** * NB prior to 9.1 this was a TransportMasterNodeAction so for BwC it must be registered with the TransportService until * we no longer need to support calling this action remotely. */ @UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) @SuppressWarnings("this-escape") @Inject public TransportGetStatusAction( TransportService transportService, ClusterService clusterService, ThreadPool threadPool, ActionFilters actionFilters, ProjectResolver projectResolver ) { super( GetStatusAction.NAME, actionFilters, transportService.getTaskManager(), clusterService, threadPool.executor(ThreadPool.Names.MANAGEMENT), projectResolver ); transportService.registerRequestHandler( actionName, executor, false, true, GetStatusAction.Request::new, (request, channel, task) -> executeDirect(task, request, new ChannelActionListener<>(channel)) ); } @Override protected void localClusterStateOperation( Task task, GetStatusAction.Request request, ProjectState state, ActionListener<Response> listener ) { listener.onResponse(new Response(currentILMMode(state.metadata()))); } @Override protected ClusterBlockException checkBlock(GetStatusAction.Request request, ProjectState state) { return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_WRITE); } }
TransportGetStatusAction
java
elastic__elasticsearch
x-pack/plugin/profiling/src/test/java/org/elasticsearch/xpack/profiling/action/CarthesianCombinator.java
{ "start": 381, "end": 1708 }
class ____<T> { private final T[] elems; private final int[] index; private final T[] result; private final int len; @SuppressWarnings("unchecked") CarthesianCombinator(T[] elems, int len) { if (elems.length == 0) { throw new IllegalArgumentException("elems must not be empty"); } this.elems = elems; this.index = new int[len]; this.result = (T[]) Array.newInstance(elems[0].getClass(), len); this.len = len; } private void init(int length) { for (int i = 0; i < length; i++) { index[i] = 0; result[i] = elems[0]; } } public void forEach(Consumer<T[]> action) { // Initialize index and result init(len); int pos = 0; while (pos < len) { if (index[pos] < elems.length) { result[pos] = elems[index[pos]]; action.accept(result); index[pos]++; continue; } while (pos < len && index[pos] + 1 >= elems.length) { pos++; } if (pos < len) { index[pos]++; result[pos] = elems[index[pos]]; init(pos); pos = 0; } } } }
CarthesianCombinator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ImmutableMemberCollectionTest.java
{ "start": 2035, "end": 2619 }
class ____ { @SuppressWarnings("ImmutableMemberCollection") private final List<String> myList; Test(List<String> myList) { this.myList = myList; } } """) .expectUnchanged() .doTest(); } @Test public void listInitConstructor_notMutated_replacesTypeWithImmutableList() { refactoringHelper .addInputLines( "Test.java", """ import com.google.common.collect.ImmutableList; import java.util.List;
Test
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/VariableNameSameAsTypeTest.java
{ "start": 3065, "end": 3349 }
class ____ { void f() { String string; } } """) .doTest(); } @Test public void negativeInitializedLowerCase() { helper .addSourceLines( "Test.java", """
Test
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/postings/Lucene90BlockTreeTermsWriter.java
{ "start": 9473, "end": 16612 }
class ____ extends FieldsConsumer { /** * Suggested default value for the {@code minItemsInBlock} parameter to {@link * #Lucene90BlockTreeTermsWriter(SegmentWriteState,PostingsWriterBase,int,int)}. */ public static final int DEFAULT_MIN_BLOCK_SIZE = 25; /** * Suggested default value for the {@code maxItemsInBlock} parameter to {@link * #Lucene90BlockTreeTermsWriter(SegmentWriteState,PostingsWriterBase,int,int)}. */ public static final int DEFAULT_MAX_BLOCK_SIZE = 48; public static final int OUTPUT_FLAGS_NUM_BITS = 2; public static final int OUTPUT_FLAGS_MASK = 0x3; public static final int OUTPUT_FLAG_IS_FLOOR = 0x1; public static final int OUTPUT_FLAG_HAS_TERMS = 0x2; /** Extension of terms meta file */ static final String TERMS_EXTENSION = "tim"; static final String TERMS_CODEC_NAME = "BlockTreeTermsDict"; // public static boolean DEBUG = false; // public static boolean DEBUG2 = false; // private final static boolean SAVE_DOT_FILES = false; private final IndexOutput metaOut; private final IndexOutput termsOut; private final IndexOutput indexOut; final int maxDoc; final int minItemsInBlock; final int maxItemsInBlock; final int version; final PostingsWriterBase postingsWriter; final FieldInfos fieldInfos; private final List<ByteBuffersDataOutput> fields = new ArrayList<>(); /** * Create a new writer. The number of items (terms or sub-blocks) per block will aim to be between * minItemsPerBlock and maxItemsPerBlock, though in some cases the blocks may be smaller than the * min. */ public Lucene90BlockTreeTermsWriter( SegmentWriteState state, PostingsWriterBase postingsWriter, int minItemsInBlock, int maxItemsInBlock ) throws IOException { this(state, postingsWriter, minItemsInBlock, maxItemsInBlock, Lucene90BlockTreeTermsReader.VERSION_CURRENT); } /** Expert constructor that allows configuring the version, used for bw tests. */ public Lucene90BlockTreeTermsWriter( SegmentWriteState state, PostingsWriterBase postingsWriter, int minItemsInBlock, int maxItemsInBlock, int version ) throws IOException { validateSettings(minItemsInBlock, maxItemsInBlock); this.minItemsInBlock = minItemsInBlock; this.maxItemsInBlock = maxItemsInBlock; if (version < Lucene90BlockTreeTermsReader.VERSION_START || version > Lucene90BlockTreeTermsReader.VERSION_CURRENT) { throw new IllegalArgumentException( "Expected version in range [" + Lucene90BlockTreeTermsReader.VERSION_START + ", " + Lucene90BlockTreeTermsReader.VERSION_CURRENT + "], but got " + version ); } this.version = version; this.maxDoc = state.segmentInfo.maxDoc(); this.fieldInfos = state.fieldInfos; this.postingsWriter = postingsWriter; final String termsName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TERMS_EXTENSION); termsOut = state.directory.createOutput(termsName, state.context); boolean success = false; IndexOutput metaOut = null, indexOut = null; try { CodecUtil.writeIndexHeader(termsOut, TERMS_CODEC_NAME, version, state.segmentInfo.getId(), state.segmentSuffix); final String indexName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TERMS_INDEX_EXTENSION); indexOut = state.directory.createOutput(indexName, state.context); CodecUtil.writeIndexHeader(indexOut, TERMS_INDEX_CODEC_NAME, version, state.segmentInfo.getId(), state.segmentSuffix); // segment = state.segmentInfo.name; final String metaName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TERMS_META_EXTENSION); metaOut = state.directory.createOutput(metaName, state.context); CodecUtil.writeIndexHeader(metaOut, TERMS_META_CODEC_NAME, version, state.segmentInfo.getId(), state.segmentSuffix); postingsWriter.init(metaOut, state); // have consumer write its format/header this.metaOut = metaOut; this.indexOut = indexOut; success = true; } finally { if (success == false) { IOUtils.closeWhileHandlingException(metaOut, termsOut, indexOut); } } } /** Throws {@code IllegalArgumentException} if any of these settings is invalid. */ public static void validateSettings(int minItemsInBlock, int maxItemsInBlock) { if (minItemsInBlock <= 1) { throw new IllegalArgumentException("minItemsInBlock must be >= 2; got " + minItemsInBlock); } if (minItemsInBlock > maxItemsInBlock) { throw new IllegalArgumentException( "maxItemsInBlock must be >= minItemsInBlock; got maxItemsInBlock=" + maxItemsInBlock + " minItemsInBlock=" + minItemsInBlock ); } if (2 * (minItemsInBlock - 1) > maxItemsInBlock) { throw new IllegalArgumentException( "maxItemsInBlock must be at least 2*(minItemsInBlock-1); got maxItemsInBlock=" + maxItemsInBlock + " minItemsInBlock=" + minItemsInBlock ); } } @Override public void write(Fields fields, NormsProducer norms) throws IOException { // if (DEBUG) System.out.println("\nBTTW.write seg=" + segment); String lastField = null; for (String field : fields) { assert lastField == null || lastField.compareTo(field) < 0; lastField = field; // if (DEBUG) System.out.println("\nBTTW.write seg=" + segment + " field=" + field); Terms terms = fields.terms(field); if (terms == null) { continue; } TermsEnum termsEnum = terms.iterator(); TermsWriter termsWriter = new TermsWriter(fieldInfos.fieldInfo(field)); while (true) { BytesRef term = termsEnum.next(); // if (DEBUG) System.out.println("BTTW: next term " + term); if (term == null) { break; } // if (DEBUG) System.out.println("write field=" + fieldInfo.name + " term=" + // ToStringUtils.bytesRefToString(term)); termsWriter.write(term, termsEnum, norms); } termsWriter.finish(); // if (DEBUG) System.out.println("\nBTTW.write done seg=" + segment + " field=" + field); } } static long encodeOutput(long fp, boolean hasTerms, boolean isFloor) { assert fp < (1L << 62); return (fp << 2) | (hasTerms ? OUTPUT_FLAG_HAS_TERMS : 0) | (isFloor ? OUTPUT_FLAG_IS_FLOOR : 0); } private static
Lucene90BlockTreeTermsWriter
java
google__guava
android/guava-tests/test/com/google/common/base/TestExceptions.java
{ "start": 1072, "end": 1139 }
class ____ extends RuntimeException {} static
SomeUncheckedException
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableSubscribeOnTest.java
{ "start": 1091, "end": 3259 }
class ____ extends RxJavaTest { @Test public void issue813() throws InterruptedException { // https://github.com/ReactiveX/RxJava/issues/813 final CountDownLatch scheduled = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch doneLatch = new CountDownLatch(1); TestObserver<Integer> to = new TestObserver<>(); Observable .unsafeCreate(new ObservableSource<Integer>() { @Override public void subscribe( final Observer<? super Integer> observer) { observer.onSubscribe(Disposable.empty()); scheduled.countDown(); try { try { latch.await(); } catch (InterruptedException e) { // this means we were unsubscribed (Scheduler shut down and interrupts) // ... but we'll pretend we are like many Observables that ignore interrupts } observer.onComplete(); } catch (Throwable e) { observer.onError(e); } finally { doneLatch.countDown(); } } }).subscribeOn(Schedulers.computation()).subscribe(to); // wait for scheduling scheduled.await(); // trigger unsubscribe to.dispose(); latch.countDown(); doneLatch.await(); to.assertNoErrors(); to.assertComplete(); } @Test public void onError() { TestObserverEx<String> to = new TestObserverEx<>(); Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposable.empty()); observer.onError(new RuntimeException("fail")); } }).subscribeOn(Schedulers.computation()).subscribe(to); to.awaitDone(1000, TimeUnit.MILLISECONDS); to.assertTerminated(); } public static
ObservableSubscribeOnTest
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/shutdown/ShutdownTimer.java
{ "start": 73, "end": 170 }
class ____ { public static long requestStarted; public static Socket socket; }
ShutdownTimer
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/type/TypeFactoryWithRecursiveTypesTest.java
{ "start": 592, "end": 1120 }
class ____ extends Base { @JsonProperty int sub = 2; } private final ObjectMapper MAPPER = newJsonMapper(); @Test public void testBasePropertiesIncludedWhenSerializingSubWhenSubTypeLoadedAfterBaseType() throws IOException { TypeFactory tf = defaultTypeFactory(); tf.constructType(Base.class); tf.constructType(Sub.class); Sub sub = new Sub(); String serialized = MAPPER.writeValueAsString(sub); assertEquals("{\"base\":1,\"sub\":2}", serialized); } }
Sub
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateCompletionSizeAndBatchConsumerTest.java
{ "start": 1132, "end": 2739 }
class ____ extends ContextTestSupport { @Test public void testAggregateExpressionSize() throws Exception { MockEndpoint result = getMockEndpoint("mock:result"); // A+A+A gets completed by size, the others by consumer result.expectedBodiesReceived("A+A+A", "A", "B+B", "Z"); result.message(0).exchangeProperty(Exchange.AGGREGATED_COMPLETED_BY).isEqualTo("size"); result.message(1).exchangeProperty(Exchange.AGGREGATED_COMPLETED_BY).isEqualTo("consumer"); result.message(2).exchangeProperty(Exchange.AGGREGATED_COMPLETED_BY).isEqualTo("consumer"); result.message(3).exchangeProperty(Exchange.AGGREGATED_COMPLETED_BY).isEqualTo("consumer"); template.sendBody("direct:start", "A"); template.sendBody("direct:start", "A"); template.sendBody("direct:start", "B"); template.sendBody("direct:start", "A"); template.sendBody("direct:start", "B"); template.sendBody("direct:start", "A"); // send the last one with the batch size property template.sendBodyAndProperty("direct:start", "Z", Exchange.BATCH_SIZE, 7); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").aggregate(body(), new BodyInAggregatingStrategy()).completionSize(3) .completionFromBatchConsumer().to("log:result", "mock:result"); } }; } }
AggregateCompletionSizeAndBatchConsumerTest
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/support/FileLineParserTests.java
{ "start": 545, "end": 1416 }
class ____ extends ESTestCase { public void testParse() throws IOException { Path path = getDataPath("../authc/support/role_mapping.yml"); final Map<Integer, String> lines = new HashMap<>( Map.of( 7, "security:", 8, " - \"cn=avengers,ou=marvel,o=superheros\"", 9, " - \"cn=shield,ou=marvel,o=superheros\"", 10, "avenger:", 11, " - \"cn=avengers,ou=marvel,o=superheros\"", 12, " - \"cn=Horatio Hornblower,ou=people,o=sevenSeas\"" ) ); FileLineParser.parse(path, (lineNumber, line) -> { assertThat(lines.remove(lineNumber), equalTo(line)); }); assertThat(lines.isEmpty(), is(true)); } }
FileLineParserTests
java
google__guice
core/test/com/googlecode/guice/JakartaTest.java
{ "start": 14241, "end": 14377 }
class ____ extends AbstractM { @Override @SuppressWarnings("OverridesJakartaInjectableMethod") void setB(B b) {} } static
M
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AddressSelectionTest.java
{ "start": 3938, "end": 4531 }
class ____ { void f() throws Exception { new Socket("127.0.0.1", 80); InetAddress.getByName("127.0.0.1"); new InetSocketAddress("127.0.0.1", 80); new Socket("::1", 80); InetAddress.getByName("::1"); new InetSocketAddress("::1", 80); } } """) .addOutputLines( "Test.java", """ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket;
Test
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/ImmutableMapAsBasicTests.java
{ "start": 6290, "end": 6595 }
class ____ { @Id private Integer id; @Immutable @Convert( converter = MapConverter.class ) private Map<String,String> data; private TestEntity() { // for use by Hibernate } public TestEntity(Integer id, Map<String,String> data) { this.id = id; this.data = data; } } }
TestEntity
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java
{ "start": 20193, "end": 21149 }
class ____<C> extends Task implements Executor.Action<SimpleConnectionPool<C>> { private final PoolWaiter<C> waiter; private final Completable<Boolean> handler; private boolean cancelled; public Cancel(PoolWaiter<C> waiter, Completable<Boolean> handler) { this.waiter = waiter; this.handler = handler; } @Override public Task execute(SimpleConnectionPool<C> pool) { if (pool.closed) { return new Task() { @Override public void run() { handler.fail(POOL_CLOSED_EXCEPTION); } }; } if (pool.waiters.remove(waiter)) { cancelled = true; waiter.disposed = true; } else if (!waiter.disposed) { waiter.disposed = true; cancelled = true; } else { cancelled = false; } return this; } @Override public void run() { handler.succeed(cancelled); } } static
Cancel
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/constraint/AllocationTags.java
{ "start": 1087, "end": 3124 }
class ____ { private TargetApplicationsNamespace ns; private Set<String> tags; private ApplicationId applicationId; private AllocationTags(TargetApplicationsNamespace namespace, Set<String> allocationTags) { this.ns = namespace; this.tags = allocationTags; } private AllocationTags(TargetApplicationsNamespace namespace, Set<String> allocationTags, ApplicationId currentAppId) { this.ns = namespace; this.tags = allocationTags; this.applicationId = currentAppId; } /** * @return the namespace of these tags. */ public TargetApplicationsNamespace getNamespace() { return this.ns; } public ApplicationId getCurrentApplicationId() { return this.applicationId; } /** * @return the allocation tags. */ public Set<String> getTags() { return this.tags; } @VisibleForTesting public static AllocationTags createSingleAppAllocationTags( ApplicationId appId, Set<String> tags) { TargetApplicationsNamespace namespace = new TargetApplicationsNamespace.AppID(appId); return new AllocationTags(namespace, tags); } @VisibleForTesting public static AllocationTags createGlobalAllocationTags(Set<String> tags) { TargetApplicationsNamespace namespace = new TargetApplicationsNamespace.All(); return new AllocationTags(namespace, tags); } @VisibleForTesting public static AllocationTags createOtherAppAllocationTags( ApplicationId currentApp, Set<String> tags) { TargetApplicationsNamespace namespace = new TargetApplicationsNamespace.NotSelf(); return new AllocationTags(namespace, tags, currentApp); } public static AllocationTags createAllocationTags( ApplicationId currentApplicationId, String namespaceString, Set<String> tags) throws InvalidAllocationTagsQueryException { TargetApplicationsNamespace namespace = TargetApplicationsNamespace .parse(namespaceString); return new AllocationTags(namespace, tags, currentApplicationId); } }
AllocationTags
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/util/Builder.java
{ "start": 1623, "end": 2307 }
interface ____<T> { /** * Builds the object after all configuration has been set. This will use default values for any * unspecified attributes for the object. * * @return the configured instance. * @throws org.apache.logging.log4j.core.config.ConfigurationException if there was an error building the * object. */ T build(); default boolean isValid() { return PluginBuilder.validateFields(this, getErrorPrefix()); } /** * Prefix to use to report errors from this builder. * * @return The prefix of all logged errors. */ default String getErrorPrefix() { return "Component"; } }
Builder
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/analyze/GroupAggregationAnalyzer.java
{ "start": 2128, "end": 6301 }
class ____ implements PlanAnalyzer { public static final GroupAggregationAnalyzer INSTANCE = new GroupAggregationAnalyzer(); private GroupAggregationAnalyzer() {} @Override public Optional<AnalyzedResult> analyze(FlinkRelNode rel) { TableConfig tableConfig = ShortcutUtils.unwrapTableConfig(rel); List<Integer> targetRelIds = new ArrayList<>(); if (rel instanceof FlinkPhysicalRel) { rel.accept( new RelShuttleImpl() { @Override public RelNode visit(RelNode other) { if (other instanceof StreamPhysicalGroupAggregate) { if (((TwoStageOptimizedAggregateRule) TwoStageOptimizedAggregateRule.INSTANCE) .matchesTwoStage( (StreamPhysicalGroupAggregate) other, other.getInput(0).getInput(0))) { targetRelIds.add(other.getId()); } } return super.visit(other); } }); if (!targetRelIds.isEmpty()) { return Optional.of( new AnalyzedResult() { @Override public PlanAdvice getAdvice() { return new PlanAdvice( PlanAdvice.Kind.ADVICE, PlanAdvice.Scope.NODE_LEVEL, getAdviceContent(tableConfig)); } @Override public List<Integer> getTargetIds() { return targetRelIds; } }); } } return Optional.empty(); } private String getAdviceContent(TableConfig tableConfig) { boolean isMiniBatchEnabled = tableConfig.get(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ENABLED); AggregatePhaseStrategy aggStrategy = getAggPhaseStrategy(tableConfig); long miniBatchLatency = tableConfig .get(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ALLOW_LATENCY) .toMillis(); long miniBatchSize = tableConfig.get(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_SIZE); Map<ConfigOption<?>, String> tuningConfigs = new LinkedHashMap<>(); if (aggStrategy == AggregatePhaseStrategy.ONE_PHASE) { tuningConfigs.put( OptimizerConfigOptions.TABLE_OPTIMIZER_AGG_PHASE_STRATEGY, String.format( "'%s'", OptimizerConfigOptions.TABLE_OPTIMIZER_AGG_PHASE_STRATEGY .defaultValue())); } if (!isMiniBatchEnabled) { tuningConfigs.put(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ENABLED, "'true'"); } if (miniBatchLatency <= 0) { tuningConfigs.put( ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ALLOW_LATENCY, "a positive long value"); } if (miniBatchSize <= 0) { tuningConfigs.put( ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_SIZE, "a positive long value"); } return String.format( "You might want to enable local-global two-phase optimization by configuring %s.", tuningConfigs.entrySet().stream() .map( entry -> String.format( "'%s' to %s", entry.getKey().key(), entry.getValue())) .collect(Collectors.joining(", ", "(", ")"))); } }
GroupAggregationAnalyzer
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/embeddable/EmbeddableInheritanceAssciationsTest.java
{ "start": 9396, "end": 9854 }
class ____ { @Id private Long id; @Embedded private ParentEmbeddable embeddable; public TestEntity() { } public TestEntity(Long id, ParentEmbeddable embeddable) { this.id = id; this.embeddable = embeddable; } public ParentEmbeddable getEmbeddable() { return embeddable; } public void setEmbeddable(ParentEmbeddable embeddable) { this.embeddable = embeddable; } } @Entity( name = "AssociatedEntity" ) static
TestEntity
java
google__guice
core/test/com/google/inject/ScopesTest.java
{ "start": 40778, "end": 40933 }
class ____ { /** Relies on Guice implementation to inject S first, which provides a barrier . */ @Inject I0(I1 i) {} } @Singleton static
I0
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/TestsSSLService.java
{ "start": 512, "end": 1014 }
class ____ extends SSLService { public TestsSSLService(Environment environment) { super(environment); } /** * Allows to get alternative ssl context, like for the http client */ public SSLContext sslContext(Settings settings) { return sslContextHolder(super.sslConfiguration(settings)).sslContext(); } public SSLContext sslContext(String context) { return sslContextHolder(super.getSSLConfiguration(context)).sslContext(); } }
TestsSSLService
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/contract/ITestAbfsFileSystemContractSetTimes.java
{ "start": 1123, "end": 1816 }
class ____ extends AbstractContractSetTimesTest { private final boolean isSecure; private final ABFSContractTestBinding binding; public ITestAbfsFileSystemContractSetTimes() throws Exception { binding = new ABFSContractTestBinding(); this.isSecure = binding.isSecureMode(); } @BeforeEach @Override public void setup() throws Exception { binding.setup(); super.setup(); } @Override protected Configuration createConfiguration() { return binding.getRawConfiguration(); } @Override protected AbstractFSContract createContract(final Configuration conf) { return new AbfsFileSystemContract(conf, isSecure); } }
ITestAbfsFileSystemContractSetTimes
java
hibernate__hibernate-orm
hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/DB2iLegacySqlAstTranslator.java
{ "start": 714, "end": 2042 }
class ____<T extends JdbcOperation> extends DB2LegacySqlAstTranslator<T> { private final DatabaseVersion version; public DB2iLegacySqlAstTranslator(SessionFactoryImplementor sessionFactory, Statement statement, DatabaseVersion version) { super( sessionFactory, statement ); this.version = version; } @Override protected boolean shouldEmulateFetchClause(QueryPart queryPart) { // Check if current query part is already row numbering to avoid infinite recursion if ( getQueryPartForRowNumbering() == queryPart ) { return false; } // Percent fetches or ties fetches aren't supported in DB2 if ( useOffsetFetchClause( queryPart ) && !isRowsOnlyFetchClauseType( queryPart ) ) { return true; } // According to LegacyDB2LimitHandler, variable limit also isn't supported before 7.1 return version.isBefore(7, 1) && queryPart.getFetchClauseExpression() != null && !( queryPart.getFetchClauseExpression() instanceof Literal ); } @Override protected boolean supportsOffsetClause() { return version.isSameOrAfter(7, 1); } @Override protected void renderComparison(Expression lhs, ComparisonOperator operator, Expression rhs) { renderComparisonStandard( lhs, operator, rhs ); } @Override public DatabaseVersion getDB2Version() { return DB2_LUW_VERSION9; } }
DB2iLegacySqlAstTranslator
java
elastic__elasticsearch
x-pack/plugin/deprecation/src/test/java/org/elasticsearch/xpack/deprecation/NodesDeprecationCheckResponseTests.java
{ "start": 1005, "end": 4578 }
class ____ extends AbstractWireSerializingTestCase<NodesDeprecationCheckResponse> { @Override protected Writeable.Reader<NodesDeprecationCheckResponse> instanceReader() { return NodesDeprecationCheckResponse::new; } @Override protected NodesDeprecationCheckResponse createTestInstance() { List<NodesDeprecationCheckAction.NodeResponse> responses = Arrays.asList( randomArray(1, 10, NodesDeprecationCheckAction.NodeResponse[]::new, NodesDeprecationCheckResponseTests::randomNodeResponse) ); return new NodesDeprecationCheckResponse(new ClusterName(randomAlphaOfLength(10)), responses, Collections.emptyList()); } @Override protected NodesDeprecationCheckResponse mutateInstance(NodesDeprecationCheckResponse instance) { int mutate = randomIntBetween(1, 3); return switch (mutate) { case 1 -> { List<NodesDeprecationCheckAction.NodeResponse> responses = new ArrayList<>(instance.getNodes()); responses.add(randomNodeResponse()); yield new NodesDeprecationCheckResponse(instance.getClusterName(), responses, instance.failures()); } case 2 -> { ArrayList<FailedNodeException> failures = new ArrayList<>(instance.failures()); failures.add(new FailedNodeException("test node", "test failure", new RuntimeException(randomAlphaOfLength(10)))); yield new NodesDeprecationCheckResponse(instance.getClusterName(), instance.getNodes(), failures); } case 3 -> { String clusterName = randomValueOtherThan(instance.getClusterName().value(), () -> randomAlphaOfLengthBetween(5, 15)); yield new NodesDeprecationCheckResponse(new ClusterName(clusterName), instance.getNodes(), instance.failures()); } default -> throw new AssertionError("invalid mutation"); }; } private static DiscoveryNode randomDiscoveryNode() throws Exception { InetAddress inetAddress = InetAddress.getByAddress( randomAlphaOfLength(5), new byte[] { (byte) 192, (byte) 168, (byte) 0, (byte) 1 } ); TransportAddress transportAddress = new TransportAddress(inetAddress, randomIntBetween(0, 65535)); return DiscoveryNodeUtils.create( randomAlphaOfLength(5), randomAlphaOfLength(5), transportAddress, Collections.emptyMap(), Collections.emptySet() ); } private static NodesDeprecationCheckAction.NodeResponse randomNodeResponse() { DiscoveryNode node; try { node = randomDiscoveryNode(); } catch (Exception e) { throw new RuntimeException(e); } List<DeprecationIssue> issuesList = Arrays.asList( randomArray(0, 10, DeprecationIssue[]::new, NodesDeprecationCheckResponseTests::createTestDeprecationIssue) ); return new NodesDeprecationCheckAction.NodeResponse(node, issuesList); } private static DeprecationIssue createTestDeprecationIssue() { String details = randomBoolean() ? randomAlphaOfLength(10) : null; return new DeprecationIssue( randomFrom(Level.values()), randomAlphaOfLength(10), randomAlphaOfLength(10), details, randomBoolean(), randomMap(1, 5, () -> Tuple.tuple(randomAlphaOfLength(4), randomAlphaOfLength(4))) ); } }
NodesDeprecationCheckResponseTests
java
micronaut-projects__micronaut-core
http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/PublisherExceptionHandlerTest.java
{ "start": 1531, "end": 2938 }
class ____ { private static final String SPEC_NAME = "PublisherExceptionHandlerTest"; // https://github.com/micronaut-projects/micronaut-core/issues/6395 @Test public void publisherError() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/publisher-error?msg=foo")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("handled: foo") .build()); }) .run(); } @Test public void validationIsWorking() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/publisher-error?msg=")) .assertion((server, request) -> { AssertionUtils.assertThrows(server, request, HttpResponseAssertion.builder() .status(HttpStatus.BAD_REQUEST) .headers(Collections.singletonMap(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)) .build() ); }) .run(); } @Controller("/publisher-error") @Requires(property = "spec.name", value = SPEC_NAME) static
PublisherExceptionHandlerTest
java
apache__camel
components/camel-aws/camel-aws2-s3/src/test/java/org/apache/camel/component/aws2/s3/integration/S3StreamUploadTimestampGroupingEdgeCasesIT.java
{ "start": 1498, "end": 15380 }
class ____ extends Aws2S3Base { @EndpointInject private ProducerTemplate template; @EndpointInject("mock:result") private MockEndpoint result; @Test public void testTimestampGroupingWithInvalidStringTimestamp() throws Exception { result.reset(); result.expectedMessageCount(5); // Test with invalid string timestamp - should fall back to current time for (int i = 0; i < 5; i++) { template.sendBodyAndHeader("direct:timestampGrouping", "Message with invalid timestamp: " + i, Exchange.MESSAGE_TIMESTAMP, "invalid-timestamp-" + i); } MockEndpoint.assertIsSatisfied(context); Exchange ex = template.request("direct:listObjects", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.listObjects); exchange.getIn().setHeader(AWS2S3Constants.PREFIX, "edgeTest"); } }); List<S3Object> resp = ex.getMessage().getBody(List.class); assertTrue(resp.size() >= 1, "Should create at least 1 file even with invalid timestamps"); } @Test public void testTimestampGroupingWithMixedTimestampTypes() throws Exception { result.reset(); result.expectedMessageCount(6); long baseTime = 1704096000000L; // 2024-01-01 08:00:00 UTC // Mix of Long, Date, String, and invalid timestamps template.sendBodyAndHeader("direct:timestampGrouping", "Message 1 - Long", Exchange.MESSAGE_TIMESTAMP, baseTime); template.sendBodyAndHeader("direct:timestampGrouping", "Message 2 - Date", Exchange.MESSAGE_TIMESTAMP, new Date(baseTime + 60000)); template.sendBodyAndHeader("direct:timestampGrouping", "Message 3 - String", Exchange.MESSAGE_TIMESTAMP, String.valueOf(baseTime + 120000)); template.sendBodyAndHeader("direct:timestampGrouping", "Message 4 - Invalid", Exchange.MESSAGE_TIMESTAMP, "not-a-timestamp"); template.sendBody("direct:timestampGrouping", "Message 5 - No header"); template.sendBodyAndHeader("direct:timestampGrouping", "Message 6 - Null", Exchange.MESSAGE_TIMESTAMP, null); MockEndpoint.assertIsSatisfied(context); Exchange ex = template.request("direct:listObjects", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.listObjects); exchange.getIn().setHeader(AWS2S3Constants.PREFIX, "edgeTest"); } }); List<S3Object> resp = ex.getMessage().getBody(List.class); assertTrue(resp.size() >= 1, "Should handle mixed timestamp types gracefully"); } @Test public void testTimestampGroupingWithVeryLargeWindow() throws Exception { result.reset(); result.expectedMessageCount(10); // Test with very large window (1 hour = 3600000ms) long baseTime = 1704096000000L; // 2024-01-01 08:00:00 UTC // Send messages spread over 30 minutes - should all go to same window for (int i = 0; i < 10; i++) { long timestamp = baseTime + (i * 180000); // 3 minutes apart template.sendBodyAndHeader("direct:timestampGroupingLargeWindow", "Message in large window: " + i, Exchange.MESSAGE_TIMESTAMP, timestamp); } MockEndpoint.assertIsSatisfied(context); Exchange ex = template.request("direct:listObjects", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.listObjects); exchange.getIn().setHeader(AWS2S3Constants.PREFIX, "largeWindowTest"); } }); List<S3Object> resp = ex.getMessage().getBody(List.class); assertEquals(1, resp.size(), "Should create only 1 file for large time window"); } @Test public void testTimestampGroupingWithVerySmallWindow() throws Exception { result.reset(); result.expectedMessageCount(6); // Test with very small window (5 seconds = 5000ms) long baseTime = 1704096000000L; // 2024-01-01 08:00:00 UTC // Send messages spread across 3 different 5-second windows to ensure clear separation // Window 1: 08:00:00 - 08:00:05 template.sendBodyAndHeader("direct:timestampGroupingSmallWindow", "Message in window 1a", Exchange.MESSAGE_TIMESTAMP, baseTime); template.sendBodyAndHeader("direct:timestampGroupingSmallWindow", "Message in window 1b", Exchange.MESSAGE_TIMESTAMP, baseTime + 2000); // Window 2: 08:00:10 - 08:00:15 (skip 5 seconds to be in different window) template.sendBodyAndHeader("direct:timestampGroupingSmallWindow", "Message in window 2a", Exchange.MESSAGE_TIMESTAMP, baseTime + 10000); template.sendBodyAndHeader("direct:timestampGroupingSmallWindow", "Message in window 2b", Exchange.MESSAGE_TIMESTAMP, baseTime + 12000); // Window 3: 08:00:20 - 08:00:25 template.sendBodyAndHeader("direct:timestampGroupingSmallWindow", "Message in window 3a", Exchange.MESSAGE_TIMESTAMP, baseTime + 20000); template.sendBodyAndHeader("direct:timestampGroupingSmallWindow", "Message in window 3b", Exchange.MESSAGE_TIMESTAMP, baseTime + 22000); MockEndpoint.assertIsSatisfied(context); // Add a delay to ensure all uploads complete via timeout Thread.sleep(5000); Exchange ex = template.request("direct:listObjects", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.listObjects); exchange.getIn().setHeader(AWS2S3Constants.PREFIX, "smallWindowTest"); } }); List<S3Object> resp = ex.getMessage().getBody(List.class); assertTrue(resp.size() >= 3, "Should create 3 files for 3 different 5-second windows, got: " + resp.size()); } @Test public void testTimestampGroupingWithBoundaryTimestamps() throws Exception { result.reset(); result.expectedMessageCount(6); // Test messages exactly at window boundaries long windowStart = 1704096000000L; // Exact start of 5-minute window long windowSize = 300000L; // 5 minutes // Send messages at exact boundaries template.sendBodyAndHeader("direct:timestampGrouping", "Message at window start", Exchange.MESSAGE_TIMESTAMP, windowStart); template.sendBodyAndHeader("direct:timestampGrouping", "Message 1ms before window end", Exchange.MESSAGE_TIMESTAMP, windowStart + windowSize - 1); template.sendBodyAndHeader("direct:timestampGrouping", "Message at next window start", Exchange.MESSAGE_TIMESTAMP, windowStart + windowSize); template.sendBodyAndHeader("direct:timestampGrouping", "Message in first window middle", Exchange.MESSAGE_TIMESTAMP, windowStart + windowSize / 2); template.sendBodyAndHeader("direct:timestampGrouping", "Message in second window middle", Exchange.MESSAGE_TIMESTAMP, windowStart + windowSize + windowSize / 2); template.sendBodyAndHeader("direct:timestampGrouping", "Message at exact boundary", Exchange.MESSAGE_TIMESTAMP, windowStart + windowSize); MockEndpoint.assertIsSatisfied(context); Exchange ex = template.request("direct:listObjects", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.listObjects); exchange.getIn().setHeader(AWS2S3Constants.PREFIX, "edgeTest"); } }); List<S3Object> resp = ex.getMessage().getBody(List.class); assertEquals(2, resp.size(), "Should create exactly 2 files for boundary timestamps"); } @Test public void testTimestampGroupingWithOldTimestamps() throws Exception { result.reset(); result.expectedMessageCount(8); // Test with very old timestamps (year 2000) long oldBaseTime = 946684800000L; // 2000-01-01 00:00:00 UTC for (int i = 0; i < 8; i++) { long timestamp = oldBaseTime + (i * 60000); // 1 minute apart template.sendBodyAndHeader("direct:timestampGrouping", "Message with old timestamp: " + i, Exchange.MESSAGE_TIMESTAMP, timestamp); } MockEndpoint.assertIsSatisfied(context); Exchange ex = template.request("direct:listObjects", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.listObjects); exchange.getIn().setHeader(AWS2S3Constants.PREFIX, "edgeTest"); } }); List<S3Object> resp = ex.getMessage().getBody(List.class); assertTrue(resp.size() >= 1, "Should handle old timestamps correctly"); // Verify files have correct naming with old dates boolean foundOldDateFile = false; for (S3Object s3Object : resp) { String key = s3Object.key(); if (key.contains("20000101")) { // Check for year 2000 foundOldDateFile = true; break; } } assertTrue(foundOldDateFile, "Should create files with old date naming"); } @Test public void testTimestampGroupingWithFutureTimestamps() throws Exception { result.reset(); result.expectedMessageCount(6); // Test with future timestamps (year 2030) long futureBaseTime = 1893456000000L; // 2030-01-01 00:00:00 UTC for (int i = 0; i < 6; i++) { long timestamp = futureBaseTime + (i * 60000); // 1 minute apart template.sendBodyAndHeader("direct:timestampGrouping", "Message with future timestamp: " + i, Exchange.MESSAGE_TIMESTAMP, timestamp); } MockEndpoint.assertIsSatisfied(context); Exchange ex = template.request("direct:listObjects", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.listObjects); exchange.getIn().setHeader(AWS2S3Constants.PREFIX, "edgeTest"); } }); List<S3Object> resp = ex.getMessage().getBody(List.class); assertTrue(resp.size() >= 1, "Should handle future timestamps correctly"); // Verify files have correct naming with future dates boolean foundFutureDateFile = false; for (S3Object s3Object : resp) { String key = s3Object.key(); if (key.contains("20300101")) { // Check for year 2030 foundFutureDateFile = true; break; } } assertTrue(foundFutureDateFile, "Should create files with future date naming"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // Standard timestamp grouping route String timestampGroupingEndpoint = String.format( "aws2-s3://%s?autoCreateBucket=true&streamingUploadMode=true&keyName=edgeTest.txt" + "&batchMessageNumber=3&timestampGroupingEnabled=true&timestampWindowSizeMillis=300000" + "&timestampHeaderName=CamelMessageTimestamp", name.get()); from("direct:timestampGrouping").to(timestampGroupingEndpoint).to("mock:result"); // Large window test (1 hour) String largeWindowEndpoint = String.format( "aws2-s3://%s?autoCreateBucket=true&streamingUploadMode=true&keyName=largeWindowTest.txt" + "&batchMessageNumber=5&timestampGroupingEnabled=true&timestampWindowSizeMillis=3600000" + "&timestampHeaderName=CamelMessageTimestamp", name.get()); from("direct:timestampGroupingLargeWindow").to(largeWindowEndpoint).to("mock:result"); // Small window test (5 seconds) String smallWindowEndpoint = String.format( "aws2-s3://%s?autoCreateBucket=true&streamingUploadMode=true&keyName=smallWindowTest.txt" + "&batchMessageNumber=3&timestampGroupingEnabled=true&timestampWindowSizeMillis=5000" + "&timestampHeaderName=CamelMessageTimestamp&streamingUploadTimeout=2000", name.get()); from("direct:timestampGroupingSmallWindow").to(smallWindowEndpoint).to("mock:result"); // Common route for listing objects String listEndpoint = String.format("aws2-s3://%s?autoCreateBucket=true", name.get()); from("direct:listObjects").to(listEndpoint); } }; } }
S3StreamUploadTimestampGroupingEdgeCasesIT
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_1200/Issue1246.java
{ "start": 373, "end": 986 }
class ____ extends TestCase { public void test_for_issue() throws Exception { B b = new B(); b.setX("xx"); String test = JSON.toJSONString( b ); System.out.println(test); assertEquals("{}", test); C c = new C(); c.ab = b ; String testC = JSON.toJSONString( c ); System.out.println(testC); assertEquals("{\"ab\":{}}",testC); D d = new D(); d.setAb( b ); String testD = JSON.toJSONString( d ); System.out.println(testD); assertEquals("{\"ab\":{}}",testD); } public static
Issue1246
java
elastic__elasticsearch
modules/lang-expression/src/yamlRestTest/java/org/elasticsearch/script/expression/LangExpressionClientYamlTestSuiteIT.java
{ "start": 877, "end": 1493 }
class ____ extends ESClientYamlSuiteTestCase { @ClassRule public static ElasticsearchCluster cluster = ElasticsearchCluster.local().module("lang-expression").build(); public LangExpressionClientYamlTestSuiteIT(@Name("yaml") ClientYamlTestCandidate testCandidate) { super(testCandidate); } @ParametersFactory public static Iterable<Object[]> parameters() throws Exception { return ESClientYamlSuiteTestCase.createParameters(); } @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } }
LangExpressionClientYamlTestSuiteIT
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/channels/EmitterExample.java
{ "start": 423, "end": 868 }
class ____ { @Inject @Channel("sink") Emitter<String> emitter; private final List<String> list = new CopyOnWriteArrayList<>(); public void run() { emitter.send("a"); emitter.send("b"); emitter.send("c"); emitter.complete(); } @Incoming("sink") public void consume(String s) { list.add(s); } public List<String> list() { return list; } }
EmitterExample
java
alibaba__nacos
plugin/control/src/main/java/com/alibaba/nacos/plugin/control/configs/ControlConfigs.java
{ "start": 820, "end": 2844 }
class ____ { private static volatile ControlConfigs instance = null; public static ControlConfigs getInstance() { if (instance == null) { synchronized (ControlConfigs.class) { if (instance == null) { instance = new ControlConfigs(); Collection<ControlConfigsInitializer> load = NacosServiceLoader .load(ControlConfigsInitializer.class); for (ControlConfigsInitializer controlConfigsInitializer : load) { controlConfigsInitializer.initialize(instance); } } } } return instance; } public static void setInstance(ControlConfigs instance) { ControlConfigs.instance = instance; } private String connectionRuntimeEjector = "nacos"; private String ruleExternalStorage = ""; private String localRuleStorageBaseDir = ""; private String controlManagerType = ""; public String getRuleExternalStorage() { return ruleExternalStorage; } public void setRuleExternalStorage(String ruleExternalStorage) { this.ruleExternalStorage = ruleExternalStorage; } public String getConnectionRuntimeEjector() { return connectionRuntimeEjector; } public void setConnectionRuntimeEjector(String connectionRuntimeEjector) { this.connectionRuntimeEjector = connectionRuntimeEjector; } public String getLocalRuleStorageBaseDir() { return localRuleStorageBaseDir; } public void setLocalRuleStorageBaseDir(String localRuleStorageBaseDir) { this.localRuleStorageBaseDir = localRuleStorageBaseDir; } public String getControlManagerType() { return controlManagerType; } public void setControlManagerType(String controlManagerType) { this.controlManagerType = controlManagerType; } }
ControlConfigs
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java
{ "start": 1079, "end": 1341 }
class ____ implements ConverterFactory<String, Enum> { @Override public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) { return new StringToEnum(ConversionUtils.getEnumType(targetType)); } private static
StringToEnumConverterFactory
java
dropwizard__dropwizard
dropwizard-db/src/main/java/io/dropwizard/db/DataSourceFactory.java
{ "start": 1278, "end": 10103 }
class ____ of the JDBC driver class. * Only required if there were no JDBC drivers registered in {@code META-INF/services/java.sql.Driver}. * </td> * </tr> * <tr> * <td>{@code user}</td> * <td><b>none</b></td> * <td>The username used to connect to the server.</td> * </tr> * <tr> * <td>{@code password}</td> * <td>none</td> * <td>The password used to connect to the server.</td> * </tr> * <tr> * <td>{@code removeAbandoned}</td> * <td>{@code false}</td> * <td> * Remove abandoned connections if they exceed the {@code removeAbandonedTimeout}. * If set to {@code true} a connection is considered abandoned and eligible for removal if it has * been in use longer than the {@code removeAbandonedTimeout} and the condition for * {@code abandonWhenPercentageFull} is met. * </td> * </tr> * <tr> * <td>{@code removeAbandonedTimeout}</td> * <td>60 seconds</td> * <td> * The time before a database connection can be considered abandoned. * </td> * </tr> * <tr> * <td>{@code abandonWhenPercentageFull}</td> * <td>0</td> * <td> * Connections that have been abandoned (timed out) won't get closed and reported up * unless the number of connections in use are above the percentage defined by * {@code abandonWhenPercentageFull}. The value should be between 0-100. * </td> * </tr> * <tr> * <td>{@code alternateUsernamesAllowed}</td> * <td>{@code false}</td> * <td> * Set to true if the call * {@link javax.sql.DataSource#getConnection(String, String) getConnection(username,password)} * is allowed. This is used for when the pool is used by an application accessing * multiple schemas. There is a performance impact turning this option on, even when not * used. * </td> * </tr> * <tr> * <td>{@code commitOnReturn}</td> * <td>{@code false}</td> * <td> * Set to true if you want the connection pool to commit any pending transaction when a * connection is returned. * </td> * </tr> * <tr> * <td>{@code rollbackOnReturn}</td> * <td>{@code false}</td> * <td> * Set to true if you want the connection pool to rollback any pending transaction when a * connection is returned. * </td> * </tr> * <tr> * <td>{@code autoCommitByDefault}</td> * <td>JDBC driver's default</td> * <td>The default auto-commit state of the connections.</td> * </tr> * <tr> * <td>{@code readOnlyByDefault}</td> * <td>JDBC driver's default</td> * <td>The default read-only state of the connections.</td> * </tr> * <tr> * <td>{@code properties}</td> * <td>none</td> * <td>Any additional JDBC driver parameters.</td> * </tr> * <tr> * <td>{@code defaultCatalog}</td> * <td>none</td> * <td>The default catalog to use for the connections.</td> * </tr> * <tr> * <td>{@code defaultTransactionIsolation}</td> * <td>JDBC driver default</td> * <td> * The default transaction isolation to use for the connections. Can be one of * {@code none}, {@code default}, {@code read-uncommitted}, {@code read-committed}, * {@code repeatable-read}, or {@code serializable}. * </td> * </tr> * <tr> * <td>{@code useFairQueue}</td> * <td>{@code true}</td> * <td> * If {@code true}, calls to {@code getConnection} are handled in a FIFO manner. * </td> * </tr> * <tr> * <td>{@code initialSize}</td> * <td>10</td> * <td> * The initial size of the connection pool. May be zero, which will allow you to start * the connection pool without requiring the DB to be up. In the latter case the {@link #minSize} * must also be set to zero. * </td> * </tr> * <tr> * <td>{@code minSize}</td> * <td>10</td> * <td> * The minimum size of the connection pool. * </td> * </tr> * <tr> * <td>{@code maxSize}</td> * <td>100</td> * <td> * The maximum size of the connection pool. * </td> * </tr> * <tr> * <td>{@code initializationQuery}</td> * <td>none</td> * <td> * A custom query to be run when a connection is first created. * </td> * </tr> * <tr> * <td>{@code logAbandonedConnections}</td> * <td>{@code false}</td> * <td> * If {@code true}, logs stack traces of abandoned connections. * </td> * </tr> * <tr> * <td>{@code logValidationErrors}</td> * <td>{@code false}</td> * <td> * If {@code true}, logs errors when connections fail validation. * </td> * </tr> * <tr> * <td>{@code maxConnectionAge}</td> * <td>none</td> * <td> * If set, connections which have been open for longer than {@code maxConnectionAge} are * closed when returned. * </td> * </tr> * <tr> * <td>{@code maxWaitForConnection}</td> * <td>30 seconds</td> * <td> * If a request for a connection is blocked for longer than this period, an exception * will be thrown. * </td> * </tr> * <tr> * <td>{@code minIdleTime}</td> * <td>1 minute</td> * <td> * The minimum amount of time an connection must sit idle in the pool before it is * eligible for eviction. * </td> * </tr> * <tr> * <td>{@code validationQuery}</td> * <td>{@code SELECT 1}</td> * <td> * The SQL query that will be used to validate connections from this pool before * returning them to the caller or pool. If specified, this query does not have to * return any data, it just can't throw a SQLException. * </td> * </tr> * <tr> * <td>{@code validationQueryTimeout}</td> * <td>none</td> * <td> * The timeout before a connection validation queries fail. * </td> * </tr> * <tr> * <td>{@code checkConnectionWhileIdle}</td> * <td>{@code true}</td> * <td> * Set to true if query validation should take place while the connection is idle. * </td> * </tr> * <tr> * <td>{@code checkConnectionOnBorrow}</td> * <td>{@code false}</td> * <td> * Whether or not connections will be validated before being borrowed from the pool. If * the connection fails to validate, it will be dropped from the pool, and another will * be borrowed. * </td> * </tr> * <tr> * <td>{@code checkConnectionOnConnect}</td> * <td>{@code true}</td> * <td> * Whether or not connections will be validated before being added to the pool. If the * connection fails to validate, it won't be added to the pool. * </td> * </tr> * <tr> * <td>{@code checkConnectionOnReturn}</td> * <td>{@code false}</td> * <td> * Whether or not connections will be validated after being returned to the pool. If * the connection fails to validate, it will be dropped from the pool. * </td> * </tr> * <tr> * <td>{@code autoCommentsEnabled}</td> * <td>{@code true}</td> * <td> * Whether or not ORMs should automatically add comments. * </td> * </tr> * <tr> * <td>{@code evictionInterval}</td> * <td>5 seconds</td> * <td> * The amount of time to sleep between runs of the idle connection validation, abandoned * cleaner and idle pool resizing. * </td> * </tr> * <tr> * <td>{@code validationInterval}</td> * <td>30 seconds</td> * <td> * To avoid excess validation, only run validation once every interval. * </td> * </tr> * <tr> * <td>{@code validatorClassName}</td> * <td>(none)</td> * <td> * Name of a
name
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/impl/NullsAsEmptyProvider.java
{ "start": 337, "end": 875 }
class ____ implements NullValueProvider, java.io.Serializable { private static final long serialVersionUID = 1L; protected final ValueDeserializer<?> _deserializer; public NullsAsEmptyProvider(ValueDeserializer<?> deser) { _deserializer = deser; } @Override public AccessPattern getNullAccessPattern() { return AccessPattern.DYNAMIC; } @Override public Object getNullValue(DeserializationContext ctxt) { return _deserializer.getEmptyValue(ctxt); } }
NullsAsEmptyProvider
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/CheckpointStorageWorkerView.java
{ "start": 1397, "end": 4431 }
interface ____ { /** * Resolves a storage location reference into a CheckpointStreamFactory. * * <p>The reference may be the {@link CheckpointStorageLocationReference#isDefaultReference() * default reference}, in which case the method should return the default location, taking * existing configuration and checkpoint ID into account. * * @param checkpointId The ID of the checkpoint that the location is initialized for. * @param reference The checkpoint location reference. * @return A checkpoint storage location reflecting the reference and checkpoint ID. * @throws IOException Thrown, if the storage location cannot be initialized from the reference. */ CheckpointStreamFactory resolveCheckpointStorageLocation( long checkpointId, CheckpointStorageLocationReference reference) throws IOException; /** * Opens a stream to persist checkpoint state data that is owned strictly by tasks and not * attached to the life cycle of a specific checkpoint. * * <p>This method should be used when the persisted data cannot be immediately dropped once the * checkpoint that created it is dropped. Examples are write-ahead-logs. For those, the state * can only be dropped once the data has been moved to the target system, which may sometimes * take longer than one checkpoint (if the target system is temporarily unable to keep up). * * <p>The fact that the job manager does not own the life cycle of this type of state means also * that it is strictly the responsibility of the tasks to handle the cleanup of this data. * * <p>Developer note: In the future, we may be able to make this a special case of "shared * state", where the task re-emits the shared state reference as long as it needs to hold onto * the persisted state data. * * @return A checkpoint state stream to the location for state owned by tasks. * @throws IOException Thrown, if the stream cannot be opened. */ CheckpointStateOutputStream createTaskOwnedStateStream() throws IOException; /** * A complementary method to {@link #createTaskOwnedStateStream()}. Creates a toolset that gives * access to additional operations that can be performed in the task owned state location. * * @return A toolset for additional operations for state owned by tasks. */ CheckpointStateToolset createTaskOwnedCheckpointStateToolset(); /** * Return {@link org.apache.flink.runtime.state.filesystem.FsMergingCheckpointStorageAccess} if * file merging is enabled. Otherwise, return itself. File merging is supported by subclasses of * {@link org.apache.flink.runtime.state.filesystem.AbstractFsCheckpointStorageAccess}. */ default CheckpointStorageWorkerView toFileMergingStorage( FileMergingSnapshotManager mergingSnapshotManager, Environment environment) throws IOException { return this; } }
CheckpointStorageWorkerView
java
micronaut-projects__micronaut-core
context/src/main/java/io/micronaut/logging/LoggingSystem.java
{ "start": 926, "end": 1364 }
interface ____ { /** * Set the log level for the logger found by name (or created if not found). * * @param name the logger name * @param level the log level to set on the named logger */ void setLogLevel(@NotBlank String name, @NotNull LogLevel level); /** * Refreshes Logging System with the goal of cleaning its internal caches. * */ default void refresh() { } }
LoggingSystem
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/node/RequiredAccessorTest.java
{ "start": 356, "end": 6344 }
class ____ extends DatabindTestUtil { private final ObjectMapper MAPPER = newJsonMapper(); private final JsonNode TEST_OBJECT, TEST_ARRAY; public RequiredAccessorTest() throws Exception { TEST_OBJECT = MAPPER.readTree(a2q( "{ 'data' : { 'primary' : 15, 'vector' : [ 'yes', false ], 'nullable' : null },\n" +" 'array' : [ true, {\"messsage\":'hello', 'value' : 42, 'misc' : [1, 2] }, null, 0.25 ]\n" +"}" )); TEST_ARRAY = MAPPER.readTree(a2q( "[ true, { 'data' : { 'primary' : 15, 'vector' : [ 'yes', false ] } }, 0.25, 'last' ]" )); } @Test public void testIMPORTANT() { _checkRequiredAtFail(TEST_OBJECT, "/data/weird/and/more", "/weird/and/more"); } @Test public void testRequiredAtObjectOk() throws Exception { assertNotNull(TEST_OBJECT.requiredAt("/array")); assertNotNull(TEST_OBJECT.requiredAt("/array/0")); assertTrue(TEST_OBJECT.requiredAt("/array/0").isBoolean()); assertNotNull(TEST_OBJECT.requiredAt("/array/1/misc/1")); assertEquals(2, TEST_OBJECT.requiredAt("/array/1/misc/1").intValue()); } @Test public void testRequiredAtArrayOk() throws Exception { assertTrue(TEST_ARRAY.requiredAt("/0").isBoolean()); assertTrue(TEST_ARRAY.requiredAt("/1").isObject()); assertNotNull(TEST_ARRAY.requiredAt("/1/data/primary")); assertNotNull(TEST_ARRAY.requiredAt("/1/data/vector/1")); } @Test public void testRequiredAtFailOnObjectBasic() throws Exception { _checkRequiredAtFail(TEST_OBJECT, "/0", "/0"); _checkRequiredAtFail(TEST_OBJECT, "/bogus", "/bogus"); _checkRequiredAtFail(TEST_OBJECT, "/data/weird/and/more", "/weird/and/more"); _checkRequiredAtFail(TEST_OBJECT, "/data/vector/other/3", "/other/3"); _checkRequiredAtFail(TEST_OBJECT, "/data/primary/more", "/more"); } @Test public void testRequiredAtFailOnArray() throws Exception { _checkRequiredAtFail(TEST_ARRAY, "/1/data/vector/25", "/25"); _checkRequiredAtFail(TEST_ARRAY, "/0/data/x", "/data/x"); } private void _checkRequiredAtFail(JsonNode doc, String fullPath, String mismatchPart) { try { JsonNode n = doc.requiredAt(fullPath); fail("Should NOT pass: got node ("+n.getClass().getSimpleName()+") -> {"+n+"}"); } catch (DatabindException e) { verifyException(e, "No node at '"+fullPath+"' (unmatched part: '"+mismatchPart+"')"); } } @Test public void testSimpleRequireOk() throws Exception { // first basic working accessors on node itself assertSame(TEST_OBJECT, TEST_OBJECT.require()); assertSame(TEST_OBJECT, TEST_OBJECT.requireNonNull()); assertSame(TEST_OBJECT, TEST_OBJECT.requiredAt("")); assertSame(TEST_OBJECT, TEST_OBJECT.requiredAt(JsonPointer.compile(""))); assertSame(TEST_OBJECT.get("data"), TEST_OBJECT.required("data")); assertSame(TEST_ARRAY.get(0), TEST_ARRAY.required(0)); assertSame(TEST_ARRAY.get(3), TEST_ARRAY.required(3)); // check diff between missing, null nodes TEST_OBJECT.path("data").path("nullable").require(); try { JsonNode n = TEST_OBJECT.path("data").path("nullable").requireNonNull(); fail("Should not pass; got: "+n); } catch (DatabindException e) { verifyException(e, "requireNonNull() called on `NullNode`"); } } @Test public void testSimpleRequireAtFailure() throws Exception { try { TEST_OBJECT.requiredAt("/some-random-path"); fail("Should not pass"); } catch (JsonNodeException e) { verifyException(e, "No node at"); } try { TEST_ARRAY.requiredAt("/some-random-path"); fail("Should not pass"); } catch (JsonNodeException e) { verifyException(e, "No node at"); } try { TEST_OBJECT.requiredAt(JsonPointer.compile("/some-random-path")); fail("Should not pass"); } catch (JsonNodeException e) { verifyException(e, "No node at"); } try { TEST_ARRAY.requiredAt(JsonPointer.compile("/some-random-path")); fail("Should not pass"); } catch (JsonNodeException e) { verifyException(e, "No node at"); } } @Test public void testSimpleRequireFail() throws Exception { // required(String) try { TEST_OBJECT.required("bogus"); fail("Should not pass"); } catch (JsonNodeException e) { verifyException(e, "No value for property 'bogus'"); } // required(String) try { TEST_ARRAY.required("bogus"); fail("Should not pass"); } catch (JsonNodeException e) { verifyException(e, "Node of type `tools.jackson.databind.node.ArrayNode` has no fields"); } // required(int) try { TEST_OBJECT.required(-1); fail("Should not pass"); } catch (JsonNodeException e) { verifyException(e, "has no indexed values"); } // required(int) try { TEST_ARRAY.required(-1); fail("Should not pass"); } catch (JsonNodeException e) { verifyException(e, "No value at index #"); } } // [databind#3005] @Test public void testRequiredAtFailOnObjectScalar3005() throws Exception { JsonNode n = MAPPER.readTree("{\"simple\":5}"); try { JsonNode match = n.requiredAt("/simple/property"); fail("Should NOT pass: got node ("+match.getClass().getSimpleName()+") -> {"+match+"}"); } catch (DatabindException e) { verifyException(e, "No node at '/simple/property' (unmatched part: '/property')"); } } }
RequiredAccessorTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/DateScriptFieldType.java
{ "start": 2396, "end": 13017 }
class ____ extends AbstractScriptFieldType.Builder<DateFieldScript.Factory> { private final FieldMapper.Parameter<String> format = FieldMapper.Parameter.stringParam( "format", true, RuntimeField.initializerNotSupported(), null, (b, n, v) -> { if (v != null && false == v.equals(DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.pattern())) { b.field(n, v); } } ).acceptsNull(); private final FieldMapper.Parameter<Locale> locale = new FieldMapper.Parameter<>( "locale", true, () -> null, (n, c, o) -> o == null ? null : LocaleUtils.parse(o.toString()), RuntimeField.initializerNotSupported(), (b, n, v) -> { if (v != null && false == v.equals(DateFieldMapper.DEFAULT_LOCALE)) { b.field(n, v.toString()); } }, Object::toString ).acceptsNull(); protected Builder(String name) { super(name, DateFieldScript.CONTEXT); } @Override protected List<FieldMapper.Parameter<?>> getParameters() { List<FieldMapper.Parameter<?>> parameters = new ArrayList<>(super.getParameters()); parameters.add(format); parameters.add(locale); return Collections.unmodifiableList(parameters); } protected AbstractScriptFieldType<?> createFieldType( String name, DateFieldScript.Factory factory, Script script, Map<String, String> meta, IndexVersion supportedVersion, OnScriptError onScriptError ) { String pattern = format.getValue() == null ? DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.pattern() : format.getValue(); Locale locale = this.locale.getValue() == null ? DateFieldMapper.DEFAULT_LOCALE : this.locale.getValue(); DateFormatter dateTimeFormatter = DateFormatter.forPattern(pattern, supportedVersion).withLocale(locale); return new DateScriptFieldType(name, factory, dateTimeFormatter, script, meta, onScriptError); } @Override protected AbstractScriptFieldType<?> createFieldType( String name, DateFieldScript.Factory factory, Script script, Map<String, String> meta, OnScriptError onScriptError ) { return createFieldType(name, factory, script, meta, IndexVersion.current(), onScriptError); } @Override protected DateFieldScript.Factory getParseFromSourceFactory() { return DateFieldScript.PARSE_FROM_SOURCE; } @Override protected DateFieldScript.Factory getCompositeLeafFactory( Function<SearchLookup, CompositeFieldScript.LeafFactory> parentScriptFactory ) { return DateFieldScript.leafAdapter(parentScriptFactory); } } public static RuntimeField sourceOnly(String name, DateFormatter dateTimeFormatter, IndexVersion supportedVersion) { Builder builder = new Builder(name); builder.format.setValue(dateTimeFormatter.pattern()); return builder.createRuntimeField(DateFieldScript.PARSE_FROM_SOURCE, supportedVersion); } private final DateFormatter dateTimeFormatter; private final DateMathParser dateMathParser; DateScriptFieldType( String name, DateFieldScript.Factory scriptFactory, DateFormatter dateTimeFormatter, Script script, Map<String, String> meta, OnScriptError onScriptError ) { super( name, searchLookup -> scriptFactory.newFactory(name, script.getParams(), searchLookup, dateTimeFormatter, onScriptError), script, scriptFactory.isResultDeterministic(), meta, scriptFactory.isParsedFromSource() ); this.dateTimeFormatter = dateTimeFormatter; this.dateMathParser = dateTimeFormatter.toDateMathParser(); } @Override public String typeName() { return DateFieldMapper.CONTENT_TYPE; } @Override public Object valueForDisplay(Object value) { Long val = (Long) value; if (val == null) { return null; } return dateTimeFormatter.format(Resolution.MILLISECONDS.toInstant(val).atZone(ZoneOffset.UTC)); } @Override public DocValueFormat docValueFormat(@Nullable String format, ZoneId timeZone) { DateFormatter dateTimeFormatter = this.dateTimeFormatter; if (format != null) { dateTimeFormatter = DateFormatter.forPattern(format).withLocale(dateTimeFormatter.locale()); } if (timeZone == null) { timeZone = ZoneOffset.UTC; } return new DocValueFormat.DateTime(dateTimeFormatter, timeZone, Resolution.MILLISECONDS); } @Override public BlockLoader blockLoader(BlockLoaderContext blContext) { FallbackSyntheticSourceBlockLoader fallbackSyntheticSourceBlockLoader = fallbackSyntheticSourceBlockLoader( blContext, BlockLoader.BlockFactory::longs, this::fallbackSyntheticSourceBlockLoaderReader ); if (fallbackSyntheticSourceBlockLoader != null) { return fallbackSyntheticSourceBlockLoader; } return new DateScriptBlockDocValuesReader.DateScriptBlockLoader(leafFactory(blContext.lookup())); } private FallbackSyntheticSourceBlockLoader.Reader<?> fallbackSyntheticSourceBlockLoaderReader() { return new FallbackSyntheticSourceBlockLoader.SingleValueReader<Long>(null) { @Override public void convertValue(Object value, List<Long> accumulator) { try { if (value instanceof Number) { accumulator.add(((Number) value).longValue()); } else { // when the value is given a string formatted date; ex. 2020-07-22T16:09:41.355Z accumulator.add(dateTimeFormatter.parseMillis(value.toString())); } } catch (Exception e) { // ensure a malformed value doesn't crash } } @Override public void writeToBlock(List<Long> values, BlockLoader.Builder blockBuilder) { var longBuilder = (BlockLoader.LongBuilder) blockBuilder; for (Long value : values) { longBuilder.appendLong(value); } } @Override protected void parseNonNullValue(XContentParser parser, List<Long> accumulator) throws IOException { try { String dateAsStr = parser.textOrNull(); if (dateAsStr == null) { accumulator.add(dateTimeFormatter.parseMillis(null)); } else { accumulator.add(dateTimeFormatter.parseMillis(dateAsStr)); } } catch (Exception e) { // ensure a malformed value doesn't crash } } }; } @Override public DateScriptFieldData.Builder fielddataBuilder(FieldDataContext fieldDataContext) { return new DateScriptFieldData.Builder( name(), leafFactory(fieldDataContext.lookupSupplier().get()), Resolution.MILLISECONDS.getDefaultToScriptFieldFactory() ); } @Override public Query distanceFeatureQuery(Object origin, String pivot, SearchExecutionContext context) { applyScriptContext(context); return DateFieldType.handleNow(context, now -> { long originLong = DateFieldType.parseToLong( origin, true, null, this.dateMathParser, now, DateFieldMapper.Resolution.MILLISECONDS ); TimeValue pivotTime = TimeValue.parseTimeValue(pivot, "distance_feature.pivot"); return new LongScriptFieldDistanceFeatureQuery( script, leafFactory(context)::newInstance, name(), originLong, pivotTime.getMillis() ); }); } @Override public Query existsQuery(SearchExecutionContext context) { applyScriptContext(context); return new LongScriptFieldExistsQuery(script, leafFactory(context)::newInstance, name()); } @Override public Query rangeQuery( Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, ZoneId timeZone, @Nullable DateMathParser parser, SearchExecutionContext context ) { parser = parser == null ? this.dateMathParser : parser; applyScriptContext(context); return DateFieldType.dateRangeQuery( lowerTerm, upperTerm, includeLower, includeUpper, timeZone, parser, context, DateFieldMapper.Resolution.MILLISECONDS, name(), (l, u) -> new LongScriptFieldRangeQuery(script, leafFactory(context)::newInstance, name(), l, u) ); } @Override public Query termQuery(Object value, SearchExecutionContext context) { return DateFieldType.handleNow(context, now -> { long l = DateFieldType.parseToLong(value, false, null, this.dateMathParser, now, DateFieldMapper.Resolution.MILLISECONDS); applyScriptContext(context); return new LongScriptFieldTermQuery(script, leafFactory(context)::newInstance, name(), l); }); } @Override public Query termsQuery(Collection<?> values, SearchExecutionContext context) { if (values.isEmpty()) { return Queries.newMatchAllQuery(); } return DateFieldType.handleNow(context, now -> { Set<Long> terms = Sets.newHashSetWithExpectedSize(values.size()); for (Object value : values) { terms.add(DateFieldType.parseToLong(value, false, null, this.dateMathParser, now, DateFieldMapper.Resolution.MILLISECONDS)); } applyScriptContext(context); return new LongScriptFieldTermsQuery(script, leafFactory(context)::newInstance, name(), terms); }); } }
Builder
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/user/RestSetEnabledAction.java
{ "start": 1300, "end": 2821 }
class ____ extends NativeUserBaseRestHandler { public RestSetEnabledAction(Settings settings, XPackLicenseState licenseState) { super(settings, licenseState); } @Override public List<Route> routes() { return List.of( new Route(POST, "/_security/user/{username}/_enable"), new Route(PUT, "/_security/user/{username}/_enable"), new Route(POST, "/_security/user/{username}/_disable"), new Route(PUT, "/_security/user/{username}/_disable") ); } @Override public String getName() { return "security_set_enabled_action"; } @Override public RestChannelConsumer innerPrepareRequest(RestRequest request, NodeClient client) throws IOException { // TODO consider splitting up enable and disable to have their own rest handler final boolean enabled = request.path().endsWith("_enable"); assert enabled || request.path().endsWith("_disable"); final String username = request.param("username"); return channel -> new SetEnabledRequestBuilder(client).username(username) .enabled(enabled) .execute(new RestBuilderListener<>(channel) { @Override public RestResponse buildResponse(ActionResponse.Empty setEnabledResponse, XContentBuilder builder) throws Exception { return new RestResponse(RestStatus.OK, builder.startObject().endObject()); } }); } }
RestSetEnabledAction
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/JsonDataFormat.java
{ "start": 11797, "end": 13652 }
class ____ has @JsonView annotations */ public void setJsonView(Class<?> jsonView) { this.jsonView = jsonView; } public String getInclude() { return include; } /** * If you want to marshal a pojo to JSON, and the pojo has some fields with null values. And you want to skip these * null values, you can set this option to <tt>NON_NULL</tt> */ public void setInclude(String include) { this.include = include; } public String getAllowJmsType() { return allowJmsType; } /** * Used for JMS users to allow the JMSType header from the JMS spec to specify a FQN classname to use to unmarshal * to. */ public void setAllowJmsType(String allowJmsType) { this.allowJmsType = allowJmsType; } public String getCollectionTypeName() { return collectionTypeName; } /** * Refers to a custom collection type to lookup in the registry to use. This option should rarely be used, but * allows using different collection types than java.util.Collection based as default. */ public void setCollectionTypeName(String collectionTypeName) { this.collectionTypeName = collectionTypeName; } public Class<?> getCollectionType() { return collectionType; } public void setCollectionType(Class<?> collectionType) { this.collectionType = collectionType; } public String getUseList() { return useList; } /** * To unmarshal to a List of Map or a List of Pojo. */ public void setUseList(String useList) { this.useList = useList; } public String getModuleClassNames() { return moduleClassNames; } /** * To use custom Jackson modules com.fasterxml.jackson.databind.Module specified as a String with FQN
which
java
quarkusio__quarkus
integration-tests/amazon-lambda-http/src/main/java/io/quarkus/it/amazon/lambda/GreetingVertx.java
{ "start": 282, "end": 1039 }
class ____ { @Route(path = "/vertx/hello", methods = GET) void hello(RoutingContext context) { context.response().headers().set("Content-Type", "text/plain"); context.response().setStatusCode(200).end("hello"); } @Route(path = "/vertx/hello", methods = POST) void helloPost(RoutingContext context) { String name = context.getBodyAsString(); context.response().headers().set("Content-Type", "text/plain"); context.response().setStatusCode(200).end("hello " + name); } @Route(path = "/vertx/exchange/hello", methods = GET) void exchange(RoutingExchange exchange) { exchange.response().headers().set("Content-Type", "text/plain"); exchange.ok("hello"); } }
GreetingVertx
java
apache__camel
components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastMapProducerForSpringTest.java
{ "start": 1957, "end": 8124 }
class ____ extends HazelcastCamelSpringTestSupport { @Mock private IMap<Object, Object> map; @Override protected void trainHazelcastInstance(HazelcastInstance hazelcastInstance) { when(hazelcastInstance.getMap("foo")).thenReturn(map); } @Override protected void verifyHazelcastInstance(HazelcastInstance hazelcastInstance) { verify(hazelcastInstance, atLeastOnce()).getMap("foo"); } @AfterEach public void verifyMapMock() { verifyNoMoreInteractions(map); } @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("/META-INF/spring/test-camel-context-map.xml"); } @Test public void testPut() throws InterruptedException { template.sendBodyAndHeader("direct:put", "my-foo", HazelcastConstants.OBJECT_ID, 4711L); verify(map).put(4711L, "my-foo"); } @Test public void testUpdate() { template.sendBodyAndHeader("direct:update", "my-fooo", HazelcastConstants.OBJECT_ID, 4711L); verify(map).lock(4711L); verify(map).replace(4711L, "my-fooo"); verify(map).unlock(4711L); } @Test public void testGet() { when(map.get(4711L)).thenReturn("my-foo"); template.sendBodyAndHeader("direct:get", null, HazelcastConstants.OBJECT_ID, 4711L); verify(map).get(4711L); String body = consumer.receiveBody("seda:out", 5000, String.class); assertEquals("my-foo", body); } @Test public void testDelete() { template.sendBodyAndHeader("direct:delete", null, HazelcastConstants.OBJECT_ID, 4711L); verify(map).remove(4711L); } @Test public void testQuery() { String sql = "bar > 1000"; when(map.values(any(SqlPredicate.class))) .thenReturn(Arrays.<Object> asList(new Dummy("beta", 2000), new Dummy("gamma", 3000))); template.sendBodyAndHeader("direct:query", null, HazelcastConstants.QUERY, sql); verify(map).values(any(SqlPredicate.class)); Collection<?> b1 = consumer.receiveBody("seda:out", 5000, Collection.class); assertNotNull(b1); assertEquals(2, b1.size()); } @Test public void testPutIfAbsent() throws InterruptedException { Map<String, Object> headers = new HashMap<>(); headers.put(HazelcastConstants.OBJECT_ID, "4711"); template.sendBodyAndHeaders("direct:putIfAbsent", "replaced", headers); verify(map).putIfAbsent("4711", "replaced"); } @Test public void testPutIfAbsentWithTtl() throws InterruptedException { Map<String, Object> headers = new HashMap<>(); headers.put(HazelcastConstants.OBJECT_ID, "4711"); headers.put(HazelcastConstants.TTL_VALUE, Long.valueOf(1)); headers.put(HazelcastConstants.TTL_UNIT, TimeUnit.MINUTES); template.sendBodyAndHeaders("direct:putIfAbsent", "replaced", headers); verify(map).putIfAbsent("4711", "replaced", Long.valueOf(1), TimeUnit.MINUTES); } @Test public void testGetAllEmptySet() { Set<Object> l = new HashSet<>(); Map t = new HashMap(); t.put("key1", "value1"); t.put("key2", "value2"); t.put("key3", "value3"); when(map.getAll(anySet())).thenReturn(t); template.sendBodyAndHeader("direct:getAll", null, HazelcastConstants.OBJECT_ID, l); String body = consumer.receiveBody("seda:out", 5000, String.class); verify(map).getAll(l); assertTrue(body.contains("key1=value1")); assertTrue(body.contains("key2=value2")); assertTrue(body.contains("key3=value3")); } @Test public void testGetAllOnlyOneKey() { Set<Object> l = new HashSet<>(); l.add("key1"); Map t = new HashMap(); t.put("key1", "value1"); when(map.getAll(l)).thenReturn(t); template.sendBodyAndHeader("direct:getAll", null, HazelcastConstants.OBJECT_ID, l); String body = consumer.receiveBody("seda:out", 5000, String.class); verify(map).getAll(l); assertEquals("{key1=value1}", body); } @Test public void testClear() throws InterruptedException { template.sendBody("direct:clear", "test"); verify(map).clear(); } @Test public void testEvict() throws InterruptedException { Map<String, Object> headers = new HashMap<>(); headers.put(HazelcastConstants.OBJECT_ID, "4711"); template.sendBodyAndHeaders("direct:evict", "", headers); verify(map).evict("4711"); } @Test public void testEvictAll() throws InterruptedException { Map<String, Object> headers = new HashMap<>(); template.sendBodyAndHeaders("direct:evictAll", "", headers); verify(map).evictAll(); } @Test public void testContainsKey() { when(map.containsKey("testOk")).thenReturn(true); when(map.containsKey("testKo")).thenReturn(false); template.sendBodyAndHeader("direct:containsKey", null, HazelcastConstants.OBJECT_ID, "testOk"); Boolean body = consumer.receiveBody("seda:out", 5000, Boolean.class); verify(map).containsKey("testOk"); assertEquals(true, body); template.sendBodyAndHeader("direct:containsKey", null, HazelcastConstants.OBJECT_ID, "testKo"); body = consumer.receiveBody("seda:out", 5000, Boolean.class); verify(map).containsKey("testKo"); assertEquals(false, body); } @Test public void testContainsValue() { when(map.containsValue("testOk")).thenReturn(true); when(map.containsValue("testKo")).thenReturn(false); template.sendBody("direct:containsValue", "testOk"); Boolean body = consumer.receiveBody("seda:out", 5000, Boolean.class); verify(map).containsValue("testOk"); assertEquals(true, body); template.sendBody("direct:containsValue", "testKo"); body = consumer.receiveBody("seda:out", 5000, Boolean.class); verify(map).containsValue("testKo"); assertEquals(false, body); } }
HazelcastMapProducerForSpringTest
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/common/notifications/AbstractAuditMessageFactory.java
{ "start": 380, "end": 485 }
interface ____ means for creating audit messages. * @param <T> type of the audit message */ public
provides
java
alibaba__nacos
naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorRpcImplTest.java
{ "start": 4008, "end": 4498 }
class ____ implements Answer<Void> { @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { NotifySubscriberRequest pushRequest = invocationOnMock.getArgument(1); assertEquals(pushData.getOriginalData().toString(), pushRequest.getServiceInfo().toString()); PushCallBack callBack = invocationOnMock.getArgument(2); callBack.onSuccess(); return null; } } }
CallbackAnswer
java
apache__dubbo
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.java
{ "start": 1241, "end": 4227 }
class ____ implements Registry { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ListenerRegistryWrapper.class); private final Registry registry; private final List<RegistryServiceListener> listeners; public ListenerRegistryWrapper(Registry registry, List<RegistryServiceListener> listeners) { this.registry = registry; this.listeners = listeners; } @Override public URL getUrl() { return registry.getUrl(); } @Override public boolean isAvailable() { return registry.isAvailable(); } @Override public void destroy() { registry.destroy(); } @Override public void register(URL url) { try { if (registry != null) { registry.register(url); } } finally { if (!UrlUtils.isConsumer(url)) { listenerEvent(serviceListener -> serviceListener.onRegister(url, registry)); } } } @Override public void unregister(URL url) { try { if (registry != null) { registry.unregister(url); } } finally { if (!UrlUtils.isConsumer(url)) { listenerEvent(serviceListener -> serviceListener.onUnregister(url, registry)); } } } @Override public void subscribe(URL url, NotifyListener listener) { try { if (registry != null) { registry.subscribe(url, listener); } } finally { listenerEvent(serviceListener -> serviceListener.onSubscribe(url, registry)); } } @Override public void unsubscribe(URL url, NotifyListener listener) { try { registry.unsubscribe(url, listener); } finally { listenerEvent(serviceListener -> serviceListener.onUnsubscribe(url, registry)); } } @Override public boolean isServiceDiscovery() { return registry.isServiceDiscovery(); } @Override public List<URL> lookup(URL url) { return registry.lookup(url); } public Registry getRegistry() { return registry; } private void listenerEvent(Consumer<RegistryServiceListener> consumer) { if (CollectionUtils.isNotEmpty(listeners)) { RuntimeException exception = null; for (RegistryServiceListener listener : listeners) { if (listener != null) { try { consumer.accept(listener); } catch (RuntimeException t) { logger.error(INTERNAL_ERROR, "unknown error in registry module", "", t.getMessage(), t); exception = t; } } } if (exception != null) { throw exception; } } } }
ListenerRegistryWrapper
java
apache__camel
components/camel-platform-http/src/generated/java/org/apache/camel/component/platform/http/PlatformHttpEndpointUriFactory.java
{ "start": 523, "end": 3009 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":path"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(25); props.add("bridgeErrorHandler"); props.add("consumes"); props.add("cookieDomain"); props.add("cookieHttpOnly"); props.add("cookieMaxAge"); props.add("cookiePath"); props.add("cookieSameSite"); props.add("cookieSecure"); props.add("exceptionHandler"); props.add("exchangePattern"); props.add("fileNameExtWhitelist"); props.add("handleWriteResponseError"); props.add("headerFilterStrategy"); props.add("httpMethodRestrict"); props.add("matchOnUriPrefix"); props.add("muteException"); props.add("path"); props.add("platformHttpEngine"); props.add("populateBodyWithForm"); props.add("produces"); props.add("requestTimeout"); props.add("returnHttpRequestHeaders"); props.add("useBodyHandler"); props.add("useCookieHandler"); props.add("useStreaming"); PROPERTY_NAMES = Collections.unmodifiableSet(props); SECRET_PROPERTY_NAMES = Collections.emptySet(); MULTI_VALUE_PREFIXES = Collections.emptyMap(); } @Override public boolean isEnabled(String scheme) { return "platform-http".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "path", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
PlatformHttpEndpointUriFactory
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ConfigurationProperties.java
{ "start": 1582, "end": 7623 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(ConfigurationProperties.class); private final Map<String, PrefixNode> nodes; private static final String DELIMITER = "\\."; /** * A constructor defined in order to conform to the type used by * {@code Configuration}. It must only be called by String keys and values. * @param props properties to store */ public ConfigurationProperties(Map<String, String> props) { this.nodes = new HashMap<>(); storePropertiesInPrefixNodes(props); } /** * Filters all properties by a prefix. The property keys are trimmed by the * given prefix. * @param prefix prefix to filter property keys * @return properties matching given prefix */ public Map<String, String> getPropertiesWithPrefix(String prefix) { return getPropertiesWithPrefix(prefix, false); } /** * Filters all properties by a prefix. * @param prefix prefix to filter property keys * @param fullyQualifiedKey whether collected property keys are to be trimmed * by the prefix, or must be kept as it is * @return properties matching given prefix */ public Map<String, String> getPropertiesWithPrefix( String prefix, boolean fullyQualifiedKey) { List<String> propertyPrefixParts = splitPropertyByDelimiter(prefix); Map<String, String> properties = new HashMap<>(); String trimPrefix; if (fullyQualifiedKey) { trimPrefix = ""; } else { // To support the behaviour where the // CapacitySchedulerConfiguration.getQueuePrefix(String queue) method // returned with the queue prefix with a dot appended to it the last dot // should be removed trimPrefix = prefix.endsWith(CapacitySchedulerConfiguration.DOT) ? prefix.substring(0, prefix.length() - 1) : prefix; } collectPropertiesRecursively(nodes, properties, propertyPrefixParts.iterator(), trimPrefix); return properties; } /** * Collects properties stored in all nodes that match the given prefix. * @param childNodes children to consider when collecting properties * @param properties aggregated property storage * @param prefixParts prefix parts split by delimiter * @param trimPrefix a string that needs to be trimmed from the collected * property, empty if the key must be kept as it is */ private void collectPropertiesRecursively( Map<String, PrefixNode> childNodes, Map<String, String> properties, Iterator<String> prefixParts, String trimPrefix) { if (prefixParts.hasNext()) { String prefix = prefixParts.next(); PrefixNode candidate = childNodes.get(prefix); if (candidate != null) { if (!prefixParts.hasNext()) { copyProperties(properties, trimPrefix, candidate.getValues()); } collectPropertiesRecursively(candidate.getChildren(), properties, prefixParts, trimPrefix); } } else { for (Map.Entry<String, PrefixNode> child : childNodes.entrySet()) { copyProperties(properties, trimPrefix, child.getValue().getValues()); collectPropertiesRecursively(child.getValue().getChildren(), properties, prefixParts, trimPrefix); } } } /** * Copy properties stored in a node to an aggregated property storage. * @param copyTo property storage that collects processed properties stored * in nodes * @param trimPrefix a string that needs to be trimmed from the collected * property, empty if the key must be kept as it is * @param copyFrom properties stored in a node */ private void copyProperties( Map<String, String> copyTo, String trimPrefix, Map<String, String> copyFrom) { for (Map.Entry<String, String> configEntry : copyFrom.entrySet()) { String key = configEntry.getKey(); String prefixToTrim = trimPrefix; if (!trimPrefix.isEmpty()) { if (!key.equals(trimPrefix)) { prefixToTrim += CapacitySchedulerConfiguration.DOT; } key = configEntry.getKey().substring(prefixToTrim.length()); } copyTo.put(key, configEntry.getValue()); } } /** * Stores the given properties in the correct node. * @param props properties that need to be stored */ private void storePropertiesInPrefixNodes(Map<String, String> props) { for (Map.Entry<String, String> prop : props.entrySet()) { List<String> propertyKeyParts = splitPropertyByDelimiter(prop.getKey()); if (!propertyKeyParts.isEmpty()) { PrefixNode node = findOrCreatePrefixNode(nodes, propertyKeyParts.iterator()); node.getValues().put(prop.getKey(), prop.getValue()); } else { LOG.warn("Empty configuration property, skipping..."); } } } /** * Finds the node that matches the whole key or create it, if it does not * exist. * @param children child nodes on current level * @param propertyKeyParts a property key split by delimiter * @return the last node */ private PrefixNode findOrCreatePrefixNode( Map<String, PrefixNode> children, Iterator<String> propertyKeyParts) { String prefix = propertyKeyParts.next(); PrefixNode candidate = children.get(prefix); if (candidate == null) { candidate = new PrefixNode(); children.put(prefix, candidate); } if (!propertyKeyParts.hasNext()) { return candidate; } return findOrCreatePrefixNode(candidate.getChildren(), propertyKeyParts); } private List<String> splitPropertyByDelimiter(String property) { return Arrays.asList(property.split(DELIMITER)); } /** * A node that represents a prefix part. For example: * yarn.scheduler consists of a "yarn" and a "scheduler" node. * children: contains the child nodes, like "yarn" has a "scheduler" child * values: contains the actual property key-value pairs with this prefix. */ private static
ConfigurationProperties
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/filter/ServerHttpObservationFilterTests.java
{ "start": 9637, "end": 9820 }
class ____ extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } } static
NoOpServlet
java
reactor__reactor-core
reactor-tools/src/buildPluginTest/java/reactor/tools/agent/ApplyingByteBuddyPluginGradleTest.java
{ "start": 1033, "end": 2092 }
class ____ { static File testProjectDir; @BeforeEach void setup() { String testProjectPath = System.getProperty("mock-gradle-dir"); assertNotNull(testProjectPath, "Cannot find testProjectPath, set or verify -Dmock-gradle-dir"); testProjectDir = new File(testProjectPath); assertTrue(testProjectDir.exists() && testProjectDir.isDirectory(), "testProjectDir not created correctly"); } @Test void applyingByteBuddyPluginDuringGradleBuild() { BuildResult result = GradleRunner.create() .withProjectDir(testProjectDir) .withDebug(true) .withArguments("test", "--info", "--stacktrace") .build(); //the test task in reactor-tools/src/buildPluginTest/resources/mock-gradle/src/test/java/demo/SomeClassTest.java //checks that applying the reactor-tool ByteBuddy plugin in Gradle instruments prod code but not test code. assertTrue(result.getOutput().contains("test")); final BuildTask task = result.task(":test"); assertNotNull(task); assertEquals(TaskOutcome.SUCCESS, task.getOutcome()); } }
ApplyingByteBuddyPluginGradleTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/propertyref/cachedcollections/CachedPropertyRefCollectionTest.java
{ "start": 901, "end": 2129 }
class ____ { private ManagedObject mo; @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { mo = new ManagedObject( "test", "test" ); mo.getMembers().add( "members" ); session.persist( mo ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> session.remove( mo ) ); } @Test public void testRetrievalOfCachedCollectionWithPropertyRefKey(SessionFactoryScope scope) { // First attempt to load it via PK lookup scope.inTransaction( session -> { ManagedObject obj = session.get( ManagedObject.class, 1L ); assertNotNull( obj ); assertTrue( Hibernate.isInitialized( obj ) ); obj.getMembers().size(); assertTrue( Hibernate.isInitialized( obj.getMembers() ) ); } ); // Now try to access it via natural key scope.inTransaction( session -> { ManagedObject obj = session.bySimpleNaturalId( ManagedObject.class ).load( "test" ); assertNotNull( obj ); assertTrue( Hibernate.isInitialized( obj ) ); obj.getMembers().size(); assertTrue( Hibernate.isInitialized( obj.getMembers() ) ); } ); } }
CachedPropertyRefCollectionTest
java
grpc__grpc-java
binder/src/main/java/io/grpc/binder/ParcelableUtils.java
{ "start": 898, "end": 2003 }
class ____ { private ParcelableUtils() {} /** * Create a {@link Metadata.Key} for passing a Parcelable object in the metadata of an RPC, * treating instances as mutable. * * <p><b>Note:<b/>Parcelables can only be sent across in-process and binder channels. */ public static <P extends Parcelable> Metadata.Key<P> metadataKey( String name, Parcelable.Creator<P> creator) { return Metadata.Key.of( name, new MetadataHelper.ParcelableMetadataMarshaller<P>(creator, false)); } /** * Create a {@link Metadata.Key} for passing a Parcelable object in the metadata of an RPC, * treating instances as immutable. Immutability may be used for optimization purposes (e.g. Not * copying for in-process calls). * * <p><b>Note:<b/>Parcelables can only be sent across in-process and binder channels. */ public static <P extends Parcelable> Metadata.Key<P> metadataKeyForImmutableType( String name, Parcelable.Creator<P> creator) { return Metadata.Key.of(name, new MetadataHelper.ParcelableMetadataMarshaller<P>(creator, true)); } }
ParcelableUtils
java
spring-projects__spring-boot
module/spring-boot-jersey/src/main/java/org/springframework/boot/jersey/autoconfigure/actuate/web/JerseySameManagementContextConfiguration.java
{ "start": 3000, "end": 3581 }
class ____ { @Bean @ConditionalOnMissingBean JerseyApplicationPath jerseyApplicationPath(JerseyProperties properties, ResourceConfig config) { return new DefaultJerseyApplicationPath(properties.getApplicationPath(), config); } @Bean ResourceConfig resourceConfig(ObjectProvider<ResourceConfigCustomizer> resourceConfigCustomizers) { ResourceConfig resourceConfig = new ResourceConfig(); resourceConfigCustomizers.orderedStream().forEach((customizer) -> customizer.customize(resourceConfig)); return resourceConfig; } } }
JerseyInfrastructureConfiguration
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/GrpcXdsClientImplV3Test.java
{ "start": 37194, "end": 37960 }
class ____ implements ArgumentMatcher<LoadStatsRequest> { private final List<String> expected; private LrsRequestMatcher(List<String[]> clusterNames) { expected = new ArrayList<>(); for (String[] pair : clusterNames) { expected.add(pair[0] + ":" + (pair[1] == null ? "" : pair[1])); } Collections.sort(expected); } @Override public boolean matches(LoadStatsRequest argument) { List<String> actual = new ArrayList<>(); for (ClusterStats clusterStats : argument.getClusterStatsList()) { actual.add(clusterStats.getClusterName() + ":" + clusterStats.getClusterServiceName()); } Collections.sort(actual); return actual.equals(expected); } } private static
LrsRequestMatcher
java
spring-projects__spring-boot
module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/docker/compose/SqlServerJdbcDockerComposeConnectionDetailsFactory.java
{ "start": 1191, "end": 1738 }
class ____ extends DockerComposeConnectionDetailsFactory<JdbcConnectionDetails> { protected SqlServerJdbcDockerComposeConnectionDetailsFactory() { super("mssql/server"); } @Override protected JdbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new SqlServerJdbcDockerComposeConnectionDetails(source.getRunningService()); } /** * {@link JdbcConnectionDetails} backed by a {@code mssql/server} * {@link RunningService}. */ static
SqlServerJdbcDockerComposeConnectionDetailsFactory
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/EqualsNaNTest.java
{ "start": 1356, "end": 2584 }
class ____ { // BUG: Diagnostic contains: Double.isNaN(0.0) static final boolean ZERO_DOUBLE_NAN = 0.0 == Double.NaN; // BUG: Diagnostic contains: !Double.isNaN(1.0) static final boolean ONE_NOT_DOUBLE_NAN = Double.NaN != 1.0; // BUG: Diagnostic contains: Float.isNaN(2.f) static final boolean TWO_FLOAT_NAN = 2.f == Float.NaN; // BUG: Diagnostic contains: !Float.isNaN(3.0f) static final boolean THREE_NOT_FLOAT_NAN = 3.0f != Float.NaN; // BUG: Diagnostic contains: Double.isNaN(Double.NaN) static final boolean NAN_IS_NAN = Double.NaN == Double.NaN; // BUG: Diagnostic contains: Double.isNaN(123456) static final boolean INT_IS_NAN = 123456 == Double.NaN; }\ """) .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceLines( "EqualsNaNNegativeCases.java", """ package com.google.errorprone.bugpatterns.testdata; /** * @author lowasser@google.com (Louis Wasserman) */ public
EqualsNaNPositiveCases
java
spring-projects__spring-boot
module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java
{ "start": 9392, "end": 9531 }
class ____ { @Bean ExampleTransactional exampleTransactional() { return new ExampleTransactional(); } } static
ProxyConfiguration
java
google__guava
android/guava/src/com/google/common/collect/ComparisonChain.java
{ "start": 3649, "end": 3773 }
class ____ { private ComparisonChain() {} /** Begins a new chained comparison statement. See example in the
ComparisonChain
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/LoadEntityWithIdClassEntityGraphTest.java
{ "start": 3339, "end": 3878 }
class ____ implements Serializable { private Long product; private Long order; @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } PK pk = (PK) o; return Objects.equals( product, pk.product ) && Objects.equals( order, pk.order ); } @Override public int hashCode() { return Objects.hash( product, order ); } } } @Entity(name = "Order") @Table(name = "ORDER_TABLE") public static
PK
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/DataFormatServiceCustomRefTest.java
{ "start": 932, "end": 1789 }
class ____ extends DataFormatServiceTest { @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("myCustomDataFormat", my); return jndi; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // START SNIPPET: e1 from("direct:a") // myCustomDataFormat refers to the data format from the // Registry .marshal().custom("myCustomDataFormat").to("mock:a"); from("direct:b").unmarshal().custom("myCustomDataFormat").to("mock:b"); // END SNIPPET: e1 } }; } }
DataFormatServiceCustomRefTest
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatResponse.java
{ "start": 1813, "end": 2794 }
class ____ extends AbstractResponse { private final StreamsGroupHeartbeatResponseData data; public StreamsGroupHeartbeatResponse(StreamsGroupHeartbeatResponseData data) { super(ApiKeys.STREAMS_GROUP_HEARTBEAT); this.data = data; } @Override public StreamsGroupHeartbeatResponseData data() { return data; } @Override public Map<Errors, Integer> errorCounts() { return Collections.singletonMap(Errors.forCode(data.errorCode()), 1); } @Override public int throttleTimeMs() { return data.throttleTimeMs(); } @Override public void maybeSetThrottleTimeMs(int throttleTimeMs) { data.setThrottleTimeMs(throttleTimeMs); } public static StreamsGroupHeartbeatResponse parse(Readable readable, short version) { return new StreamsGroupHeartbeatResponse(new StreamsGroupHeartbeatResponseData( readable, version)); } public
StreamsGroupHeartbeatResponse
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/createTable/OracleCreateTableTest64.java
{ "start": 1026, "end": 7304 }
class ____ extends OracleTest { public void test_types() throws Exception { String sql = // " CREATE TABLE \"SC_001\".\"TB_001\" \n" + " (\t\"STOREID\" VARCHAR2(40) NOT NULL ENABLE, \n" + "\t\"OPPTIME\" DATE, \n" + "\t\"CREATETIME\" DATE, \n" + "\t\"NAME\" VARCHAR2(254), \n" + "\t\"FILEPATH\" VARCHAR2(254), \n" + "\t\"FILENAME\" VARCHAR2(64), \n" + "\t\"EVENTCODE\" VARCHAR2(200), \n" + "\t\"FILECODE\" VARCHAR2(200), \n" + "\t\"RESULTCODE\" VARCHAR2(200), \n" + "\t\"RESULTMESSAGE\" VARCHAR2(4000), \n" + "\t\"RESULTMEMO\" VARCHAR2(200), \n" + "\t\"STATUSCODE\" VARCHAR2(200), \n" + "\t\"STATUSMESSAGE\" VARCHAR2(4000), \n" + "\t\"UPLOADSUCCESS\" VARCHAR2(200), \n" + "\t\"BZ\" VARCHAR2(4000), \n" + "\t\"DATACOUNT\" NUMBER, \n" + "\t\"FILECONTS\" CLOB, \n" + "\t\"XFJBH\" VARCHAR2(38)\n" + " ) SEGMENT CREATION IMMEDIATE \n" + " PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" + " NOCOMPRESS NOLOGGING\n" + " STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n" + " PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" + " BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" + " TABLESPACE \"XINFANG\" \n" + " LOB (\"FILECONTS\") STORE AS BASICFILE (\n" + " TABLESPACE \"XINFANG\" ENABLE STORAGE IN ROW CHUNK 8192 RETENTION \n" + " NOCACHE NOLOGGING \n" + " STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n" + " PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" + " BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)) "; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); assertEquals("CREATE TABLE \"SC_001\".\"TB_001\" (\n" + "\t\"STOREID\" VARCHAR2(40) NOT NULL ENABLE,\n" + "\t\"OPPTIME\" DATE,\n" + "\t\"CREATETIME\" DATE,\n" + "\t\"NAME\" VARCHAR2(254),\n" + "\t\"FILEPATH\" VARCHAR2(254),\n" + "\t\"FILENAME\" VARCHAR2(64),\n" + "\t\"EVENTCODE\" VARCHAR2(200),\n" + "\t\"FILECODE\" VARCHAR2(200),\n" + "\t\"RESULTCODE\" VARCHAR2(200),\n" + "\t\"RESULTMESSAGE\" VARCHAR2(4000),\n" + "\t\"RESULTMEMO\" VARCHAR2(200),\n" + "\t\"STATUSCODE\" VARCHAR2(200),\n" + "\t\"STATUSMESSAGE\" VARCHAR2(4000),\n" + "\t\"UPLOADSUCCESS\" VARCHAR2(200),\n" + "\t\"BZ\" VARCHAR2(4000),\n" + "\t\"DATACOUNT\" NUMBER,\n" + "\t\"FILECONTS\" CLOB,\n" + "\t\"XFJBH\" VARCHAR2(38)\n" + ")\n" + "PCTFREE 10\n" + "PCTUSED 40\n" + "INITRANS 1\n" + "MAXTRANS 255\n" + "NOCOMPRESS\n" + "NOLOGGING\n" + "TABLESPACE \"XINFANG\"\n" + "STORAGE (\n" + "\tINITIAL 65536\n" + "\tNEXT 1048576\n" + "\tMINEXTENTS 1\n" + "\tMAXEXTENTS 2147483645\n" + "\tPCTINCREASE 0\n" + "\tFREELISTS 1\n" + "\tFREELIST GROUPS 1\n" + "\tBUFFER_POOL DEFAULT\n" + "\tFLASH_CACHE DEFAULT\n" + "\tCELL_FLASH_CACHE DEFAULT\n" + ")\n" + "LOB (\"FILECONTS\") STORE AS BASICFILE (\n" + "\tNOLOGGING\n" + "\tTABLESPACE \"XINFANG\"\n" + "\tSTORAGE (\n" + "\t\tINITIAL 65536\n" + "\t\tNEXT 1048576\n" + "\t\tMINEXTENTS 1\n" + "\t\tMAXEXTENTS 2147483645\n" + "\t\tPCTINCREASE 0\n" + "\t\tFREELISTS 1\n" + "\t\tFREELIST GROUPS 1\n" + "\t\tBUFFER_POOL DEFAULT\n" + "\t\tFLASH_CACHE DEFAULT\n" + "\t\tCELL_FLASH_CACHE DEFAULT\n" + "\t)\n" + "\tENABLE STORAGE IN ROW\n" + "\tCHUNK 8192\n" + "\tNOCACHE\n" + "\tRETENTION\n" + ")", SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE)); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(18, visitor.getColumns().size()); assertTrue(visitor.containsColumn("SC_001.TB_001", "STOREID")); } }
OracleCreateTableTest64
java
quarkusio__quarkus
independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/classloading/MemoryClassPathElement.java
{ "start": 592, "end": 1355 }
class ____ extends AbstractClassPathElement { private static final ProtectionDomain NULL_PROTECTION_DOMAIN = new ProtectionDomain( new CodeSource(null, (Certificate[]) null), null); private volatile Map<String, byte[]> resources; private volatile long lastModified = System.currentTimeMillis(); private final boolean runtime; public MemoryClassPathElement(Map<String, byte[]> resources, boolean runtime) { this.resources = resources; this.runtime = runtime; } @Override public boolean isRuntime() { return runtime; } public void reset(Map<String, byte[]> resources) { Map<String, byte[]> newResources = new HashMap<>(resources); //we can't delete .
MemoryClassPathElement
java
elastic__elasticsearch
x-pack/plugin/mapper-version/src/main/java/org/elasticsearch/xpack/versionfield/VersionStringFieldMapper.java
{ "start": 4683, "end": 5667 }
class ____ extends FieldMapper.Builder { private final Parameter<Map<String, String>> meta = Parameter.metaParam(); Builder(String name) { super(name); } private VersionStringFieldType buildFieldType(MapperBuilderContext context, FieldType fieldtype) { return new VersionStringFieldType(context.buildFullName(leafName()), fieldtype, meta.getValue()); } @Override public VersionStringFieldMapper build(MapperBuilderContext context) { FieldType fieldtype = new FieldType(Defaults.FIELD_TYPE); return new VersionStringFieldMapper(leafName(), fieldtype, buildFieldType(context, fieldtype), builderParams(this, context)); } @Override protected Parameter<?>[] getParameters() { return new Parameter<?>[] { meta }; } } public static final TypeParser PARSER = new TypeParser((n, c) -> new Builder(n)); public static final
Builder