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
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Methods.java
{ "start": 2261, "end": 6084 }
class ____ (MethodInfo method : classInfo.methods()) { if (skipForClientProxy(method, transformUnproxyableClasses, methodsFromWhichToRemoveFinal)) { continue; } methods.putIfAbsent(new Methods.MethodKey(method), method); } // Methods declared on superclasses if (classInfo.superClassType() != null) { ClassInfo superClassInfo = getClassByName(index, classInfo.superName()); if (superClassInfo != null) { addDelegatingMethods(index, superClassInfo, methods, methodsFromWhichToRemoveFinal, transformUnproxyableClasses); } } // Methods declared on implemented interfaces // TODO support interfaces default methods for (DotName interfaceName : classInfo.interfaceNames()) { ClassInfo interfaceClassInfo = getClassByName(index, interfaceName); if (interfaceClassInfo != null) { addDelegatingMethods(index, interfaceClassInfo, methods, methodsFromWhichToRemoveFinal, transformUnproxyableClasses); } } } } private static boolean skipForClientProxy(MethodInfo method, boolean transformUnproxyableClasses, Map<String, Set<MethodKey>> methodsFromWhichToRemoveFinal) { if (Modifier.isStatic(method.flags()) || Modifier.isPrivate(method.flags())) { return true; } String methodName = method.name(); if (IGNORED_METHODS.contains(methodName)) { return true; } // skip all Object methods except for toString() if (method.declaringClass().name().equals(DotNames.OBJECT) && !methodName.equals(TO_STRING)) { return true; } if (Modifier.isFinal(method.flags())) { String className = method.declaringClass().name().toString(); if (!className.startsWith("java.")) { if (transformUnproxyableClasses && methodsFromWhichToRemoveFinal != null) { methodsFromWhichToRemoveFinal.computeIfAbsent(className, (k) -> new HashSet<>()) .add(new MethodKey(method)); return false; } // in case we want to transform classes but are unable to, we log a WARN LOGGER.warn(String.format( "Final method %s.%s() is ignored during proxy generation and should never be invoked upon the proxy instance!", className, methodName)); } else { // JDK classes with final method are not proxyable and not transformable, we skip those methods and log a WARN LOGGER.warn(String.format( "JDK class %s with final method %s() cannot be proxied and is not transformable. " + "This method will be ignored during proxy generation and should never be invoked upon the proxy instance!", className, methodName)); } return true; } return false; } static boolean skipForDelegateSubclass(MethodInfo method) { if (Modifier.isStatic(method.flags()) || method.isSynthetic()) { return true; } if (IGNORED_METHODS.contains(method.name())) { return true; } // skip all Object methods if (method.declaringClass().name().equals(DotNames.OBJECT)) { return true; } return false; } static boolean isDefault(MethodInfo method) { // Default methods are public non-abstract instance methods declared in an
for
java
elastic__elasticsearch
libs/entitlement/src/main/java/org/elasticsearch/entitlement/instrumentation/Instrumenter.java
{ "start": 1400, "end": 1587 }
class ____ instrument * @param classfileBuffer its bytecode * @param verify whether we should verify the bytecode before and after instrumentation * @return the instrumented
to
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/record/MemoryRecordsBuilder.java
{ "start": 40463, "end": 41140 }
class ____ { public final long maxTimestamp; public final long shallowOffsetOfMaxTimestamp; public RecordsInfo(long maxTimestamp, long shallowOffsetOfMaxTimestamp) { this.maxTimestamp = maxTimestamp; this.shallowOffsetOfMaxTimestamp = shallowOffsetOfMaxTimestamp; } } /** * Return the producer id of the RecordBatches created by this builder. */ public long producerId() { return this.producerId; } public short producerEpoch() { return this.producerEpoch; } public int baseSequence() { return this.baseSequence; } }
RecordsInfo
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/function/RouterFunctions.java
{ "start": 48754, "end": 49562 }
class ____<T extends ServerResponse, S extends ServerResponse> implements RouterFunction<S> { private final RouterFunction<T> routerFunction; private final HandlerFilterFunction<T, S> filterFunction; public FilteredRouterFunction( RouterFunction<T> routerFunction, HandlerFilterFunction<T, S> filterFunction) { this.routerFunction = routerFunction; this.filterFunction = filterFunction; } @Override public Optional<HandlerFunction<S>> route(ServerRequest request) { return this.routerFunction.route(request).map(this.filterFunction::apply); } @Override public void accept(Visitor visitor) { this.routerFunction.accept(visitor); } @Override public String toString() { return this.routerFunction.toString(); } } private static final
FilteredRouterFunction
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/CustomTypeConverter.java
{ "start": 841, "end": 1588 }
class ____ extends Conversion<CustomType> { private static final CustomTypeLogicalTypeFactory logicalTypeFactory = new CustomTypeLogicalTypeFactory(); @Override public Class<CustomType> getConvertedType() { return CustomType.class; } @Override public String getLogicalTypeName() { return logicalTypeFactory.getTypeName(); } @Override public Schema getRecommendedSchema() { return Schema.create(Schema.Type.STRING); } @Override public CustomType fromCharSequence(CharSequence value, Schema schema, LogicalType type) { return new CustomType(value); } @Override public CharSequence toCharSequence(CustomType value, Schema schema, LogicalType type) { return value.getName(); } }
CustomTypeConverter
java
apache__maven
api/maven-api-core/src/main/java/org/apache/maven/api/services/DependencyResolverRequest.java
{ "start": 16097, "end": 23557 }
class ____ implements Predicate<PathType> { @Override public boolean test(PathType pathType) { return true; } @Override public boolean equals(Object obj) { return obj instanceof AlwaysTrueFilter; } @Override public int hashCode() { return AlwaysTrueFilter.class.hashCode(); } @Override public String toString() { return "AlwaysTrueFilter[]"; } } private static final Predicate<PathType> DEFAULT_FILTER = new AlwaysTrueFilter(); private final RequestType requestType; private final Project project; private final Artifact rootArtifact; private final DependencyCoordinates root; private final Collection<DependencyCoordinates> dependencies; private final Collection<DependencyCoordinates> managedDependencies; private final boolean verbose; private final PathScope pathScope; private final Predicate<PathType> pathTypeFilter; private final Version targetVersion; private final List<RemoteRepository> repositories; /** * Creates a request with the specified properties. * * @param session {@link Session} * @param rootArtifact The root dependency whose transitive dependencies should be collected, may be {@code * null}. */ @SuppressWarnings("checkstyle:ParameterNumber") DefaultDependencyResolverRequest( @Nonnull Session session, @Nullable RequestTrace trace, @Nonnull RequestType requestType, @Nullable Project project, @Nullable Artifact rootArtifact, @Nullable DependencyCoordinates root, @Nonnull Collection<DependencyCoordinates> dependencies, @Nonnull Collection<DependencyCoordinates> managedDependencies, boolean verbose, @Nullable PathScope pathScope, @Nullable Predicate<PathType> pathTypeFilter, @Nullable Version targetVersion, @Nullable List<RemoteRepository> repositories) { super(session, trace); this.requestType = requireNonNull(requestType, "requestType cannot be null"); this.project = project; this.rootArtifact = rootArtifact; this.root = root; this.dependencies = List.copyOf(requireNonNull(dependencies, "dependencies cannot be null")); this.managedDependencies = List.copyOf(requireNonNull(managedDependencies, "managedDependencies cannot be null")); this.verbose = verbose; this.pathScope = requireNonNull(pathScope, "pathScope cannot be null"); this.pathTypeFilter = (pathTypeFilter != null) ? pathTypeFilter : DEFAULT_FILTER; this.targetVersion = targetVersion; this.repositories = validate(repositories); if (verbose && requestType != RequestType.COLLECT) { throw new IllegalArgumentException("verbose cannot only be true when collecting dependencies"); } } @Nonnull @Override public RequestType getRequestType() { return requestType; } @Nonnull @Override public Optional<Project> getProject() { return Optional.ofNullable(project); } @Nonnull @Override public Optional<Artifact> getRootArtifact() { return Optional.ofNullable(rootArtifact); } @Nonnull @Override public Optional<DependencyCoordinates> getRoot() { return Optional.ofNullable(root); } @Nonnull @Override public Collection<DependencyCoordinates> getDependencies() { return dependencies; } @Nonnull @Override public Collection<DependencyCoordinates> getManagedDependencies() { return managedDependencies; } @Override public boolean getVerbose() { return verbose; } @Override public PathScope getPathScope() { return pathScope; } @Override public Predicate<PathType> getPathTypeFilter() { return pathTypeFilter; } @Override public Version getTargetVersion() { return targetVersion; } @Override public List<RemoteRepository> getRepositories() { return repositories; } @Override public boolean equals(Object o) { return o instanceof DefaultDependencyResolverRequest that && verbose == that.verbose && requestType == that.requestType && Objects.equals(project, that.project) && Objects.equals(rootArtifact, that.rootArtifact) && Objects.equals(root, that.root) && Objects.equals(dependencies, that.dependencies) && Objects.equals(managedDependencies, that.managedDependencies) && Objects.equals(pathScope, that.pathScope) && Objects.equals(pathTypeFilter, that.pathTypeFilter) && Objects.equals(targetVersion, that.targetVersion) && Objects.equals(repositories, that.repositories); } @Override public int hashCode() { return Objects.hash( requestType, project, rootArtifact, root, dependencies, managedDependencies, verbose, pathScope, pathTypeFilter, targetVersion, repositories); } @Override public String toString() { return "DependencyResolverRequest[" + "requestType=" + requestType + ", project=" + project + ", rootArtifact=" + rootArtifact + ", root=" + root + ", dependencies=" + dependencies + ", managedDependencies=" + managedDependencies + ", verbose=" + verbose + ", pathScope=" + pathScope + ", pathTypeFilter=" + pathTypeFilter + ", targetVersion=" + targetVersion + ", repositories=" + repositories + ']'; } } } }
AlwaysTrueFilter
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/TestContextAnnotationUtils.java
{ "start": 9100, "end": 9221 }
class ____ an inner class? if (searchEnclosingClass(clazz)) { // Then mimic @Inherited semantics within the enclosing
of
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/ReferenceKeyTest.java
{ "start": 18022, "end": 18580 }
interface ____ @DubboReference( group = "demo", version = "1.2.4", consumer = "my-consumer", init = false, url = "dubbo://127.0.0.1:20813") private HelloService demoService; @Autowired private HelloService helloService; } @Configuration @ImportResource({ "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" }) static
type
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/time/TimeZones.java
{ "start": 1167, "end": 3175 }
class ____ { /** * A public version of {@link java.util.TimeZone}'s package private {@code GMT_ID} field. */ public static final String GMT_ID = "GMT"; /** * The GMT time zone. * * @since 3.13.0 */ public static final TimeZone GMT = TimeZones.getTimeZone(GMT_ID); private static final boolean JAVA_25 = SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_25); /** * Delegates to {@link TimeZone#getTimeZone(String)}, on Java 25 and up, maps an ID if it's a key in {@link ZoneId#SHORT_IDS}. * <p> * On Java 25, calling {@link TimeZone#getTimeZone(String)} with an ID in {@link ZoneId#SHORT_IDS} writes a message to {@link System#err} in the form: * </p> * * <pre> * WARNING: Use of the three-letter time zone ID "the-short-id" is deprecated and it will be removed in a future release * </pre> * <p> * You can disable mapping from {@link ZoneId#SHORT_IDS} by setting the system property {@code "TimeZones.mapShortIDs=false"}. * </p> * * @param id Same as {@link TimeZone#getTimeZone(String)}. * @return Same as {@link TimeZone#getTimeZone(String)}. * @since 3.20.0 */ public static TimeZone getTimeZone(final String id) { return TimeZone.getTimeZone(JAVA_25 && mapShortIDs() ? ZoneId.SHORT_IDS.getOrDefault(id, id) : id); } private static boolean mapShortIDs() { return SystemProperties.getBoolean(TimeZones.class, "mapShortIDs", () -> true); } /** * Returns the given TimeZone if non-{@code null}, otherwise {@link TimeZone#getDefault()}. * * @param timeZone a locale or {@code null}. * @return the given locale if non-{@code null}, otherwise {@link TimeZone#getDefault()}. * @since 3.13.0 */ public static TimeZone toTimeZone(final TimeZone timeZone) { return ObjectUtils.getIfNull(timeZone, TimeZone::getDefault); } /** Do not instantiate. */ private TimeZones() { } }
TimeZones
java
playframework__playframework
documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/components/CompileTimeDependencyInjection.java
{ "start": 1460, "end": 1946 }
class ____ implements ApplicationLoader { @Override public Application load(Context context) { LoggerConfigurator.apply(context.environment().classLoader()) .ifPresent( loggerConfigurator -> loggerConfigurator.configure(context.environment(), context.initialConfig())); return new MyComponents(context).application(); } } // #basic-logger-configurator // #connection-pool public
MyAppLoaderWithLoggerConfiguration
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/SystemUtils.java
{ "start": 6636, "end": 6862 }
class ____. * * <p> * Defaults to {@code null} if the runtime does not have security access to read this property or the property does not exist. * </p> * <p> * This value is initialized when the
path
java
google__guava
android/guava-tests/test/com/google/common/reflect/InvokableTest.java
{ "start": 26032, "end": 26096 }
class ____ inside static * initializer. */ private static
is
java
quarkusio__quarkus
extensions/websockets/client/deployment/src/test/java/io/quarkus/websockets/test/WebSocketClientTestCase.java
{ "start": 799, "end": 3304 }
class ____ { static Vertx vertx; static HttpServer server; @RegisterExtension public static final QuarkusUnitTest test = new QuarkusUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClasses(TestWebSocketClient.class); } }); @BeforeAll public static void startVertxWebsocket() throws ExecutionException, InterruptedException { vertx = Vertx.vertx(); server = vertx.createHttpServer(); server.webSocketHandler(new Handler<ServerWebSocket>() { @Override public void handle(ServerWebSocket serverWebSocket) { serverWebSocket.writeTextMessage("Hello World").onComplete(new Handler<AsyncResult<Void>>() { @Override public void handle(AsyncResult<Void> voidAsyncResult) { serverWebSocket.close(); } }); } }); server.listen(8081).toCompletionStage().toCompletableFuture().get(); } @AfterAll public static void stop() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); if (server != null) { server.close(new Handler<AsyncResult<Void>>() { @Override public void handle(AsyncResult<Void> voidAsyncResult) { vertx.close(new Handler<AsyncResult<Void>>() { @Override public void handle(AsyncResult<Void> event) { latch.countDown(); } }); } }); } else if (vertx != null) { vertx.close(new Handler<AsyncResult<Void>>() { @Override public void handle(AsyncResult<Void> event) { latch.countDown(); } }); } latch.await(20, TimeUnit.SECONDS); } @Test public void testWebsocketClient() throws Exception { TestWebSocketClient client = new TestWebSocketClient(); ContainerProvider.getWebSocketContainer().connectToServer(client, new URI("ws", null, "localhost", 8081, "/", null, null)); Assertions.assertEquals("Hello World", client.get()); } }
WebSocketClientTestCase
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/data/DoubleBlock.java
{ "start": 754, "end": 8955 }
interface ____ extends Block permits DoubleArrayBlock, DoubleVectorBlock, ConstantNullBlock, DoubleBigArrayBlock { /** * Retrieves the double value stored at the given value index. * * <p> Values for a given position are between getFirstValueIndex(position) (inclusive) and * getFirstValueIndex(position) + getValueCount(position) (exclusive). * * @param valueIndex the value index * @return the data value (as a double) */ double getDouble(int valueIndex); /** * Checks if this block has the given value at position. If at this index we have a * multivalue, then it returns true if any values match. * * @param position the index at which we should check the value(s) * @param value the value to check against */ default boolean hasValue(int position, double value) { final var count = getValueCount(position); final var startIndex = getFirstValueIndex(position); for (int index = startIndex; index < startIndex + count; index++) { if (value == getDouble(index)) { return true; } } return false; } @Override DoubleVector asVector(); @Override DoubleBlock filter(int... positions); /** * Make a deep copy of this {@link Block} using the provided {@link BlockFactory}, * likely copying all data. */ @Override default DoubleBlock deepCopy(BlockFactory blockFactory) { try (DoubleBlock.Builder builder = blockFactory.newDoubleBlockBuilder(getPositionCount())) { builder.copyFrom(this, 0, getPositionCount()); builder.mvOrdering(mvOrdering()); return builder.build(); } } @Override DoubleBlock keepMask(BooleanVector mask); @Override ReleasableIterator<? extends DoubleBlock> lookup(IntBlock positions, ByteSizeValue targetBlockSize); @Override DoubleBlock expand(); static DoubleBlock readFrom(BlockStreamInput in) throws IOException { final byte serializationType = in.readByte(); return switch (serializationType) { case SERIALIZE_BLOCK_VALUES -> DoubleBlock.readValues(in); case SERIALIZE_BLOCK_VECTOR -> DoubleVector.readFrom(in.blockFactory(), in).asBlock(); case SERIALIZE_BLOCK_ARRAY -> DoubleArrayBlock.readArrayBlock(in.blockFactory(), in); case SERIALIZE_BLOCK_BIG_ARRAY -> DoubleBigArrayBlock.readArrayBlock(in.blockFactory(), in); default -> { assert false : "invalid block serialization type " + serializationType; throw new IllegalStateException("invalid serialization type " + serializationType); } }; } private static DoubleBlock readValues(BlockStreamInput in) throws IOException { final int positions = in.readVInt(); try (DoubleBlock.Builder builder = in.blockFactory().newDoubleBlockBuilder(positions)) { for (int i = 0; i < positions; i++) { if (in.readBoolean()) { builder.appendNull(); } else { final int valueCount = in.readVInt(); builder.beginPositionEntry(); for (int valueIndex = 0; valueIndex < valueCount; valueIndex++) { builder.appendDouble(in.readDouble()); } builder.endPositionEntry(); } } return builder.build(); } } @Override default void writeTo(StreamOutput out) throws IOException { DoubleVector vector = asVector(); final var version = out.getTransportVersion(); if (vector != null) { out.writeByte(SERIALIZE_BLOCK_VECTOR); vector.writeTo(out); } else if (this instanceof DoubleArrayBlock b) { out.writeByte(SERIALIZE_BLOCK_ARRAY); b.writeArrayBlock(out); } else if (this instanceof DoubleBigArrayBlock b) { out.writeByte(SERIALIZE_BLOCK_BIG_ARRAY); b.writeArrayBlock(out); } else { out.writeByte(SERIALIZE_BLOCK_VALUES); DoubleBlock.writeValues(this, out); } } private static void writeValues(DoubleBlock block, StreamOutput out) throws IOException { final int positions = block.getPositionCount(); out.writeVInt(positions); for (int pos = 0; pos < positions; pos++) { if (block.isNull(pos)) { out.writeBoolean(true); } else { out.writeBoolean(false); final int valueCount = block.getValueCount(pos); out.writeVInt(valueCount); for (int valueIndex = 0; valueIndex < valueCount; valueIndex++) { out.writeDouble(block.getDouble(block.getFirstValueIndex(pos) + valueIndex)); } } } } /** * Compares the given object with this block for equality. Returns {@code true} if and only if the * given object is a DoubleBlock, and both blocks are {@link #equals(DoubleBlock, DoubleBlock) equal}. */ @Override boolean equals(Object obj); /** Returns the hash code of this block, as defined by {@link #hash(DoubleBlock)}. */ @Override int hashCode(); /** * Returns {@code true} if the given blocks are equal to each other, otherwise {@code false}. * Two blocks are considered equal if they have the same position count, and contain the same * values (including absent null values) in the same order. This definition ensures that the * equals method works properly across different implementations of the DoubleBlock interface. */ static boolean equals(DoubleBlock block1, DoubleBlock block2) { if (block1 == block2) { return true; } final int positions = block1.getPositionCount(); if (positions != block2.getPositionCount()) { return false; } for (int pos = 0; pos < positions; pos++) { if (block1.isNull(pos) || block2.isNull(pos)) { if (block1.isNull(pos) != block2.isNull(pos)) { return false; } } else { final int valueCount = block1.getValueCount(pos); if (valueCount != block2.getValueCount(pos)) { return false; } final int b1ValueIdx = block1.getFirstValueIndex(pos); final int b2ValueIdx = block2.getFirstValueIndex(pos); for (int valueIndex = 0; valueIndex < valueCount; valueIndex++) { if (block1.getDouble(b1ValueIdx + valueIndex) != block2.getDouble(b2ValueIdx + valueIndex)) { return false; } } } } return true; } /** * Generates the hash code for the given block. The hash code is computed from the block's values. * This ensures that {@code block1.equals(block2)} implies that {@code block1.hashCode()==block2.hashCode()} * for any two blocks, {@code block1} and {@code block2}, as required by the general contract of * {@link Object#hashCode}. */ static int hash(DoubleBlock block) { final int positions = block.getPositionCount(); int result = 1; for (int pos = 0; pos < positions; pos++) { if (block.isNull(pos)) { result = 31 * result - 1; } else { final int valueCount = block.getValueCount(pos); result = 31 * result + valueCount; final int firstValueIdx = block.getFirstValueIndex(pos); for (int valueIndex = 0; valueIndex < valueCount; valueIndex++) { long element = Double.doubleToLongBits(block.getDouble(firstValueIdx + valueIndex)); result = 31 * result + (int) (element ^ (element >>> 32)); } } } return result; } /** * Builder for {@link DoubleBlock} */ sealed
DoubleBlock
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/writeAsArray/WriteAsArray_Object_2_public.java
{ "start": 248, "end": 898 }
class ____ extends TestCase { public void test_0() throws Exception { A a = new A(); a.setId(123); a.setName("wenshao"); VO vo = new VO(); vo.setId(1001); vo.setValue(a); String text = JSON.toJSONString(vo, SerializerFeature.BeanToArray); Assert.assertEquals("[1001,[123,\"wenshao\"]]", text); VO vo2 = JSON.parseObject(text, VO.class, Feature.SupportArrayToBean); Assert.assertEquals(vo.getValue().getId(), vo2.getValue().getId()); Assert.assertEquals(vo.getValue().getName(), vo2.getValue().getName()); } public static
WriteAsArray_Object_2_public
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest2.java
{ "start": 154, "end": 644 }
class ____ extends TestCase { public void test_generic() throws Exception { VO vo = new VO(); vo.values = new String[] {"a", "b"}; String text = JSON.toJSONString(vo); VO vo1 = JSON.parseObject(text, VO.class); Assert.assertNotNull(vo1.values); Assert.assertEquals(2, vo1.values.length); Assert.assertEquals("a", vo1.values[0]); Assert.assertEquals("b", vo1.values[1]); } public static
GenericArrayTest2
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AnnotationPointcutTests.java
{ "start": 1091, "end": 1703 }
class ____ { private ClassPathXmlApplicationContext ctx; private AnnotatedTestBean testBean; @BeforeEach void setup() { this.ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass()); this.testBean = ctx.getBean("testBean", AnnotatedTestBean.class); } @AfterEach void tearDown() { this.ctx.close(); } @Test void annotationBindingInAroundAdvice() { assertThat(testBean.doThis()).isEqualTo("this value"); } @Test void noMatchingWithoutAnnotationPresent() { assertThat(testBean.doTheOther()).isEqualTo("doTheOther"); } }
AnnotationPointcutTests
java
elastic__elasticsearch
modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/RemoveDuplicatesTokenFilterFactory.java
{ "start": 914, "end": 1280 }
class ____ extends AbstractTokenFilterFactory { RemoveDuplicatesTokenFilterFactory(IndexSettings indexSettings, Environment env, String name, Settings settings) { super(name); } @Override public TokenStream create(TokenStream tokenStream) { return new RemoveDuplicatesTokenFilter(tokenStream); } }
RemoveDuplicatesTokenFilterFactory
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/util/LightWeightHashSet.java
{ "start": 1278, "end": 1329 }
class ____ not * support null element. * * This
does
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/TestFactoryTestDescriptorTests.java
{ "start": 5858, "end": 7827 }
class ____ { private JupiterEngineExecutionContext context; private ExtensionContext extensionContext; private TestFactoryTestDescriptor descriptor; private boolean isClosed; @BeforeEach void before() throws Exception { JupiterConfiguration jupiterConfiguration = mock(); when(jupiterConfiguration.getDefaultDisplayNameGenerator()).thenReturn(new DisplayNameGenerator.Standard()); extensionContext = mock(); isClosed = false; context = new JupiterEngineExecutionContext(mock(), mock(), mock()) // .extend() // .withThrowableCollector(new OpenTest4JAwareThrowableCollector()) // .withExtensionContext(extensionContext) // .withExtensionRegistry(mock()) // .build(); Method testMethod = CustomStreamTestCase.class.getDeclaredMethod("customStream"); descriptor = new TestFactoryTestDescriptor(UniqueId.forEngine("engine"), CustomStreamTestCase.class, testMethod, List::of, jupiterConfiguration); when(extensionContext.getTestMethod()).thenReturn(Optional.of(testMethod)); } @Test void streamsFromTestFactoriesShouldBeClosed() { Stream<DynamicTest> dynamicTestStream = Stream.empty(); prepareMockForTestInstanceWithCustomStream(dynamicTestStream); descriptor.invokeTestMethod(context, mock()); assertTrue(isClosed); } @Test void streamsFromTestFactoriesShouldBeClosedWhenTheyThrow() { Stream<Integer> integerStream = Stream.of(1, 2); prepareMockForTestInstanceWithCustomStream(integerStream); descriptor.invokeTestMethod(context, mock()); assertTrue(isClosed); } private void prepareMockForTestInstanceWithCustomStream(Stream<?> stream) { Stream<?> mockStream = stream.onClose(() -> isClosed = true); when(extensionContext.getRequiredTestInstance()).thenReturn(new CustomStreamTestCase(mockStream)); } } private record CustomStreamTestCase(Stream<?> mockStream) { @TestFactory Stream<?> customStream() { return mockStream; } } }
Streams
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/application/LogsDBFeatureSetUsage.java
{ "start": 725, "end": 4408 }
class ____ extends XPackFeatureUsage { private final int indicesCount; private final int indicesWithSyntheticSource; private final long numDocs; private final long sizeInBytes; private final boolean hasCustomCutoffDate; public LogsDBFeatureSetUsage(StreamInput input) throws IOException { super(input); indicesCount = input.readVInt(); indicesWithSyntheticSource = input.readVInt(); if (input.getTransportVersion().onOrAfter(TransportVersions.V_8_17_0)) { numDocs = input.readVLong(); sizeInBytes = input.readVLong(); } else { numDocs = 0; sizeInBytes = 0; } var transportVersion = input.getTransportVersion(); if (transportVersion.isPatchFrom(TransportVersions.V_8_17_0) || transportVersion.supports(TransportVersions.V_8_18_0)) { hasCustomCutoffDate = input.readBoolean(); } else { hasCustomCutoffDate = false; } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(indicesCount); out.writeVInt(indicesWithSyntheticSource); if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_17_0)) { out.writeVLong(numDocs); out.writeVLong(sizeInBytes); } var transportVersion = out.getTransportVersion(); if (transportVersion.isPatchFrom(TransportVersions.V_8_17_0) || transportVersion.supports(TransportVersions.V_8_18_0)) { out.writeBoolean(hasCustomCutoffDate); } } public LogsDBFeatureSetUsage( boolean available, boolean enabled, int indicesCount, int indicesWithSyntheticSource, long numDocs, long sizeInBytes, boolean hasCustomCutoffDate ) { super(XPackField.LOGSDB, available, enabled); this.indicesCount = indicesCount; this.indicesWithSyntheticSource = indicesWithSyntheticSource; this.numDocs = numDocs; this.sizeInBytes = sizeInBytes; this.hasCustomCutoffDate = hasCustomCutoffDate; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersions.V_8_17_0; } @Override protected void innerXContent(XContentBuilder builder, Params params) throws IOException { super.innerXContent(builder, params); builder.field("indices_count", indicesCount); builder.field("indices_with_synthetic_source", indicesWithSyntheticSource); builder.field("num_docs", numDocs); builder.field("size_in_bytes", sizeInBytes); builder.field("has_custom_cutoff_date", hasCustomCutoffDate); } @Override public int hashCode() { return Objects.hash(available, enabled, indicesCount, indicesWithSyntheticSource, numDocs, sizeInBytes, hasCustomCutoffDate); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } LogsDBFeatureSetUsage other = (LogsDBFeatureSetUsage) obj; return Objects.equals(available, other.available) && Objects.equals(enabled, other.enabled) && Objects.equals(indicesCount, other.indicesCount) && Objects.equals(indicesWithSyntheticSource, other.indicesWithSyntheticSource) && Objects.equals(numDocs, other.numDocs) && Objects.equals(sizeInBytes, other.sizeInBytes) && Objects.equals(hasCustomCutoffDate, other.hasCustomCutoffDate); } }
LogsDBFeatureSetUsage
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoOneOfTest.java
{ "start": 14291, "end": 14954 }
enum ____ { ACE } public abstract Kind getKind(); public abstract String ace(); public static AnnotationCopied ace(String ace) { return AutoOneOf_AutoOneOfTest_AnnotationCopied.ace(ace); } } @Test public void classAnnotationsCopiedIfCopyAnnotations() { assertThat(AnnotationCopied.class.isAnnotationPresent(CopyTest.class)).isTrue(); AnnotationCopied ace = AnnotationCopied.ace("ace"); assertThat(ace.getClass().isAnnotationPresent(CopyTest.class)).isTrue(); assertThat(ace.getClass().getAnnotation(CopyTest.class).value()).isEqualTo(23); } @AutoOneOf(MaybeEmpty.Kind.class) public abstract static
Kind
java
quarkusio__quarkus
extensions/amazon-lambda-http/runtime/src/test/java/io/quarkus/amazon/lambda/http/LambdaHttpHandlerTest.java
{ "start": 1527, "end": 6810 }
class ____ { private static final long PROCESSING_TIMEOUT = TimeUnit.SECONDS.toMillis(1); private static final String PATH = "/test/path"; private static final String QUERY = "testParam1=testValue1&testParam2=testValue2"; private static final String HOST_HEADER = "Host"; private static final String HOST = "localhost"; private static final List<String> COOKIES = List.of("testcookie1=cvalue1", "testcookie2=cvalue2"); private static final String COOKIE_HEADER_KEY = "Cookie"; private static final String COOKIE_HEADER_VALUE = "testcookie1=cvalue1; testcookie2=cvalue2"; private static final String METHOD = "GET"; private final Application application = mock(Application.class); private final APIGatewayV2HTTPEvent request = mock(APIGatewayV2HTTPEvent.class); private final APIGatewayV2HTTPEvent.RequestContext requestContext = mock(APIGatewayV2HTTPEvent.RequestContext.class); private final APIGatewayV2HTTPEvent.RequestContext.Http requestContextMethod = mock( APIGatewayV2HTTPEvent.RequestContext.Http.class); private final AmazonLambdaContext context = mock(AmazonLambdaContext.class); private final VirtualClientConnection<?> connection = mock(VirtualClientConnection.class); private final VirtualChannel peer = mock(VirtualChannel.class); @BeforeEach public void mockSetup() { when(request.getRawPath()).thenReturn(PATH); when(request.getRequestContext()).thenReturn(requestContext); when(requestContext.getHttp()).thenReturn(requestContextMethod); when(requestContextMethod.getMethod()).thenReturn(METHOD); when(request.getHeaders()).thenReturn(Collections.singletonMap(HOST_HEADER, HOST)); when(request.getCookies()).thenReturn(COOKIES); when(connection.peer()).thenReturn(peer); when(peer.remoteAddress()).thenReturn(new VirtualAddress("whatever")); } @SuppressWarnings({ "rawtypes", "unused" }) private APIGatewayV2HTTPResponse mockHttpFunction(String query, HttpResponseStatus status) throws ExecutionException, InterruptedException { when(request.getRawQueryString()).thenReturn(query); try (MockedStatic<Application> applicationMock = Mockito.mockStatic(Application.class)) { applicationMock.when(Application::currentApplication).thenReturn(application); LambdaHttpHandler lambda = new LambdaHttpHandler(); CompletableFuture<APIGatewayV2HTTPResponse> requestFuture = CompletableFuture.supplyAsync(() -> { try (MockedStatic<VirtualClientConnection> connectionMock = Mockito.mockStatic(VirtualClientConnection.class)) { connectionMock.when(() -> VirtualClientConnection.connect(any(), any(), any())).thenAnswer(i -> { VirtualResponseHandler handler = i.getArgument(0); CompletableFuture<Object> responseFuture = CompletableFuture.supplyAsync(() -> { handler.handleMessage(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status)); return null; }); return connection; }); return lambda.handleRequest(request, context); } }); return requestFuture.get(); } } public static Iterable<Object[]> queries() { return Arrays.asList(new Object[] { QUERY, PATH + "?" + QUERY }, new Object[] { "", PATH }, new Object[] { null, PATH }); } @ParameterizedTest @MethodSource("queries") public void verifyQueryParametersBypass(String query, String expected) throws ExecutionException, InterruptedException { mockHttpFunction(query, HttpResponseStatus.OK); ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class); verify(connection, timeout(PROCESSING_TIMEOUT).times(2)).sendMessage(captor.capture()); DefaultHttpRequest rq = (DefaultHttpRequest) captor.getAllValues().get(0); assertEquals(expected, rq.uri()); } public static Iterable<Object[]> responses() { return Arrays.asList(new Object[] { HttpResponseStatus.CREATED }, new Object[] { HttpResponseStatus.OK }, new Object[] { HttpResponseStatus.BAD_REQUEST }); } @ParameterizedTest @MethodSource("responses") public void verifyResponseStatusBypass(final HttpResponseStatus status) throws ExecutionException, InterruptedException { APIGatewayV2HTTPResponse response = mockHttpFunction(null, status); verify(connection, timeout(PROCESSING_TIMEOUT).times(2)).sendMessage(any()); assertEquals(status.code(), response.getStatusCode()); } @Test public void verifyCookies() throws ExecutionException, InterruptedException { mockHttpFunction(null, HttpResponseStatus.OK); ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class); verify(connection, timeout(PROCESSING_TIMEOUT).times(2)).sendMessage(captor.capture()); DefaultHttpRequest rq = (DefaultHttpRequest) captor.getAllValues().get(0); assertEquals(COOKIE_HEADER_VALUE, rq.headers().get(COOKIE_HEADER_KEY)); } }
LambdaHttpHandlerTest
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerMacroTests.java
{ "start": 2279, "end": 11336 }
class ____ { private static final String TEMPLATE_FILE = "test.ftl"; private final StaticWebApplicationContext wac = new StaticWebApplicationContext(); private final MockServletContext servletContext = new MockServletContext(); private final MockHttpServletRequest request = new MockHttpServletRequest(); private final MockHttpServletResponse response = new MockHttpServletResponse(); private final FreeMarkerConfigurer fc = new FreeMarkerConfigurer(); private Path templateLoaderPath; @BeforeEach void setUp() throws Exception { this.templateLoaderPath = Files.createTempDirectory("servlet-").toAbsolutePath(); fc.setTemplateLoaderPaths("classpath:/", "file://" + this.templateLoaderPath); fc.setServletContext(servletContext); fc.afterPropertiesSet(); wac.setServletContext(servletContext); wac.getDefaultListableBeanFactory().registerSingleton("freeMarkerConfigurer", fc); wac.refresh(); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver()); } @Test void testExposeSpringMacroHelpers() throws Exception { FreeMarkerView fv = new FreeMarkerView() { @Override @SuppressWarnings("rawtypes") protected void processTemplate(Template template, SimpleHash fmModel, HttpServletResponse response) throws TemplateException { Map model = fmModel.toMap(); assertThat(model.get(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE)).isInstanceOf(RequestContext.class); RequestContext rc = (RequestContext) model.get(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE); BindStatus status = rc.getBindStatus("tb.name"); assertThat(status.getExpression()).isEqualTo("name"); assertThat(status.getValue()).isEqualTo("juergen"); } }; fv.setUrl(TEMPLATE_FILE); fv.setApplicationContext(wac); Map<String, Object> model = new HashMap<>(); model.put("tb", new TestBean("juergen", 99)); fv.render(model, request, response); } @Test void testSpringMacroRequestContextAttributeUsed() { final String helperTool = "wrongType"; FreeMarkerView fv = new FreeMarkerView() { @Override protected void processTemplate(Template template, SimpleHash model, HttpServletResponse response) { throw new AssertionError(); } }; fv.setUrl(TEMPLATE_FILE); fv.setApplicationContext(wac); Map<String, Object> model = new HashMap<>(); model.put(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, helperTool); try { fv.render(model, request, response); } catch (Exception ex) { assertThat(ex).isInstanceOf(ServletException.class); assertThat(ex.getMessage()).contains(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE); } } @Test void testName() throws Exception { assertThat(getMacroOutput("NAME")).isEqualTo("Darren"); } @Test void testMessage() throws Exception { assertThat(getMacroOutput("MESSAGE")).isEqualTo("Howdy Mundo"); } @Test void testDefaultMessage() throws Exception { assertThat(getMacroOutput("DEFAULTMESSAGE")).isEqualTo("hi planet"); } @Test void testMessageArgs() throws Exception { assertThat(getMacroOutput("MESSAGEARGS")).isEqualTo("Howdy[World]"); } @Test void testMessageArgsWithDefaultMessage() throws Exception { assertThat(getMacroOutput("MESSAGEARGSWITHDEFAULTMESSAGE")).isEqualTo("Hi"); } @Test void testUrl() throws Exception { assertThat(getMacroOutput("URL")).isEqualTo("/springtest/aftercontext.html"); } @Test void testUrlParams() throws Exception { assertThat(getMacroOutput("URLPARAMS")).isEqualTo("/springtest/aftercontext/bar?spam=bucket"); } @Test void testForm1() throws Exception { assertThat(getMacroOutput("FORM1")).isEqualTo("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" >"); } @Test void testForm2() throws Exception { assertThat(getMacroOutput("FORM2")).isEqualTo("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" class=\"myCssClass\" >"); } @Test void testForm3() throws Exception { assertThat(getMacroOutput("FORM3")).isEqualTo("<textarea id=\"name\" name=\"name\" >\nDarren</textarea>"); } @Test void testForm4() throws Exception { assertThat(getMacroOutput("FORM4")).isEqualTo("<textarea id=\"name\" name=\"name\" rows=10 cols=30>\nDarren</textarea>"); } // TODO verify remaining output for forms 5, 6, 7, 8, and 14 (fix whitespace) @Test void testForm9() throws Exception { assertThat(getMacroOutput("FORM9")).isEqualTo("<input type=\"password\" id=\"name\" name=\"name\" value=\"\" >"); } @Test void testForm10() throws Exception { assertThat(getMacroOutput("FORM10")).isEqualTo("<input type=\"hidden\" id=\"name\" name=\"name\" value=\"Darren\" >"); } @Test void testForm11() throws Exception { assertThat(getMacroOutput("FORM11")).isEqualTo("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" >"); } @Test void testForm12() throws Exception { assertThat(getMacroOutput("FORM12")).isEqualTo("<input type=\"hidden\" id=\"name\" name=\"name\" value=\"Darren\" >"); } @Test void testForm13() throws Exception { assertThat(getMacroOutput("FORM13")).isEqualTo("<input type=\"password\" id=\"name\" name=\"name\" value=\"\" >"); } @Test void testForm15() throws Exception { String output = getMacroOutput("FORM15"); assertThat(output).as("Wrong output: " + output) .startsWith("<input type=\"hidden\" name=\"_name\" value=\"on\"/>"); assertThat(output).as("Wrong output: " + output) .contains("<input type=\"checkbox\" id=\"name\" name=\"name\" />"); } @Test void testForm16() throws Exception { String output = getMacroOutput("FORM16"); assertThat(output).as("Wrong output: " + output) .startsWith("<input type=\"hidden\" name=\"_jedi\" value=\"on\"/>"); assertThat(output).as("Wrong output: " + output) .contains("<input type=\"checkbox\" id=\"jedi\" name=\"jedi\" checked=\"checked\" />"); } @Test void testForm17() throws Exception { assertThat(getMacroOutput("FORM17")).isEqualTo("<input type=\"text\" id=\"spouses0.name\" name=\"spouses[0].name\" value=\"Fred\" >"); } @Test void testForm18() throws Exception { String output = getMacroOutput("FORM18"); assertThat(output).as("Wrong output: " + output) .startsWith("<input type=\"hidden\" name=\"_spouses[0].jedi\" value=\"on\"/>"); assertThat(output).as("Wrong output: " + output) .contains("<input type=\"checkbox\" id=\"spouses0.jedi\" name=\"spouses[0].jedi\" checked=\"checked\" />"); } private String getMacroOutput(String name) throws Exception { String macro = fetchMacro(name); assertThat(macro).isNotNull(); storeTemplateInTempDir(macro); DummyMacroRequestContext rc = new DummyMacroRequestContext(request); Map<String, String> msgMap = new HashMap<>(); msgMap.put("hello", "Howdy"); msgMap.put("world", "Mundo"); rc.setMessageMap(msgMap); rc.setContextPath("/springtest"); TestBean darren = new TestBean("Darren", 99); TestBean fred = new TestBean("Fred"); fred.setJedi(true); darren.setSpouse(fred); darren.setJedi(true); darren.setStringArray(new String[] {"John", "Fred"}); request.setAttribute("command", darren); Map<String, String> names = new HashMap<>(); names.put("Darren", "Darren Davison"); names.put("John", "John Doe"); names.put("Fred", "Fred Bloggs"); names.put("Rob&Harrop", "Rob Harrop"); Configuration config = fc.getConfiguration(); Map<String, Object> model = new HashMap<>(); model.put("command", darren); model.put(AbstractTemplateView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, rc); model.put("msgArgs", new Object[] { "World" }); model.put("nameOptionMap", names); model.put("options", names.values()); FreeMarkerView view = new FreeMarkerView(); view.setBeanName("myView"); view.setUrl("tmp.ftl"); view.setExposeSpringMacroHelpers(false); view.setConfiguration(config); view.setServletContext(servletContext); view.render(model, request, response); return getOutput(); } private static String fetchMacro(String name) throws Exception { for (String macro : loadMacros()) { if (macro.startsWith(name)) { return macro.substring(macro.indexOf("\n")).trim(); } } return null; } private static String[] loadMacros() throws IOException { ClassPathResource resource = new ClassPathResource("test.ftl", FreeMarkerMacroTests.class); assertThat(resource.exists()).isTrue(); String all = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream())); all = all.replace("\r\n", "\n"); return StringUtils.delimitedListToStringArray(all, "\n\n"); } private void storeTemplateInTempDir(String macro) throws IOException { Files.writeString(this.templateLoaderPath.resolve("tmp.ftl"), "<#import \"spring.ftl\" as spring />\n" + macro ); } private String getOutput() throws IOException { String output = response.getContentAsString(); output = output.replace("\r\n", "\n").replaceAll(" +"," "); return output.trim(); } }
FreeMarkerMacroTests
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/builditem/PodmanStatusBuildItem.java
{ "start": 542, "end": 709 }
interface ____ check if the Podman runtime is working */ public PodmanStatusBuildItem(IsPodmanWorking isPodmanWorking) { super(isPodmanWorking); } }
to
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/core/AbstractClassGenerator.java
{ "start": 7104, "end": 7876 }
class ____ are not guaranteed to be unique, the default is <code>false</code>. */ public void setAttemptLoad(boolean attemptLoad) { this.attemptLoad = attemptLoad; } public boolean getAttemptLoad() { return attemptLoad; } /** * Set the strategy to use to create the bytecode from this generator. * By default an instance of {@link DefaultGeneratorStrategy} is used. */ public void setStrategy(GeneratorStrategy strategy) { if (strategy == null) { strategy = DefaultGeneratorStrategy.INSTANCE; } this.strategy = strategy; } /** * @see #setStrategy */ public GeneratorStrategy getStrategy() { return strategy; } /** * Used internally by CGLIB. Returns the <code>AbstractClassGenerator</code> * that is being used to generate a
names
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/protocol/RefreshSuperUserGroupsConfigurationResponse.java
{ "start": 1205, "end": 1849 }
class ____ { public static RefreshSuperUserGroupsConfigurationResponse newInstance() throws IOException { return StateStoreSerializer. newRecord(RefreshSuperUserGroupsConfigurationResponse.class); } public static RefreshSuperUserGroupsConfigurationResponse newInstance(boolean status) throws IOException { RefreshSuperUserGroupsConfigurationResponse response = newInstance(); response.setStatus(status); return response; } @Public @Unstable public abstract boolean getStatus(); @Public @Unstable public abstract void setStatus(boolean result); }
RefreshSuperUserGroupsConfigurationResponse
java
google__dagger
javatests/dagger/internal/codegen/MembersInjectionTest.java
{ "start": 44918, "end": 46234 }
class ____ { ", " @Inject String valueC;", "}"); CompilerTests.daggerCompiler(classA, classB, classC) .withProcessingOptions(compilerMode.processorOptions()) .compile( subject -> { subject.hasErrorCount(0); subject.generatedSource(goldenFileRule.goldenSource("test/A_MembersInjector")); subject.generatedSource(goldenFileRule.goldenSource("test/C_MembersInjector")); try { subject.generatedSourceFileWithPath("test/B_MembersInjector"); // Can't throw an assertion error since it would be caught. throw new IllegalStateException("Test generated a B_MembersInjector"); } catch (AssertionError expected) {} }); } // Shows that we do generate a MembersInjector for a type that has an @Inject // constructor and that extends a type with @Inject fields, even if it has no local field // injection sites // TODO(erichang): Are these even used anymore? @Test public void testConstructorInjectedFieldInjection() throws Exception { Source classA = CompilerTests.javaSource( "test.A", "package test;", "", "import javax.inject.Inject;", "", "
C
java
quarkusio__quarkus
extensions/smallrye-fault-tolerance/runtime/src/main/java/io/quarkus/smallrye/faulttolerance/runtime/QuarkusFallbackHandlerProvider.java
{ "start": 592, "end": 1627 }
class ____ implements FallbackHandlerProvider { @Inject @Any Instance<FallbackHandler<?>> instance; @Override public <T> FallbackHandler<T> get(FaultToleranceOperation operation) { if (operation.hasFallback()) { return new FallbackHandler<T>() { @SuppressWarnings("unchecked") @Override public T handle(ExecutionContext context) { Class<? extends FallbackHandler<?>> clazz = operation.getFallback().value(); FallbackHandler<T> fallbackHandlerInstance = (FallbackHandler<T>) instance.select(clazz).get(); try { return fallbackHandlerInstance.handle(context); } finally { // The instance exists to service a single invocation only instance.destroy(fallbackHandlerInstance); } } }; } return null; } }
QuarkusFallbackHandlerProvider
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/discovery/predicates/TestClassPredicatesTests.java
{ "start": 13938, "end": 14153 }
class ____ { @Test void test() { } } // Intentionally commented out so that RecursiveInnerClass is NOT a candidate test class // @Nested @SuppressWarnings("InnerClassMayBeStatic")
InnerClass
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/NameNodeProxiesClient.java
{ "start": 6503, "end": 10164 }
interface ____ should be created * @param numResponseToDrop The number of responses to drop for each RPC call * @param fallbackToSimpleAuth set to true or false during calls to indicate * if a secure client falls back to simple auth * @return an object containing both the proxy and the associated * delegation token service it corresponds to. Will return null of the * given configuration does not support HA. * @throws IOException if there is an error creating the proxy */ public static <T> ProxyAndInfo<T> createProxyWithLossyRetryHandler( Configuration config, URI nameNodeUri, Class<T> xface, int numResponseToDrop, AtomicBoolean fallbackToSimpleAuth) throws IOException { Preconditions.checkArgument(numResponseToDrop > 0); AbstractNNFailoverProxyProvider<T> failoverProxyProvider = createFailoverProxyProvider(config, nameNodeUri, xface, true, fallbackToSimpleAuth); if (failoverProxyProvider != null) { // HA case int delay = config.getInt( HdfsClientConfigKeys.Failover.SLEEPTIME_BASE_KEY, HdfsClientConfigKeys.Failover.SLEEPTIME_BASE_DEFAULT); int maxCap = config.getInt( HdfsClientConfigKeys.Failover.SLEEPTIME_MAX_KEY, HdfsClientConfigKeys.Failover.SLEEPTIME_MAX_DEFAULT); int maxFailoverAttempts = config.getInt( HdfsClientConfigKeys.Failover.MAX_ATTEMPTS_KEY, HdfsClientConfigKeys.Failover.MAX_ATTEMPTS_DEFAULT); int maxRetryAttempts = config.getInt( HdfsClientConfigKeys.Retry.MAX_ATTEMPTS_KEY, HdfsClientConfigKeys.Retry.MAX_ATTEMPTS_DEFAULT); InvocationHandler dummyHandler = new LossyRetryInvocationHandler<>( numResponseToDrop, failoverProxyProvider, RetryPolicies.failoverOnNetworkException( RetryPolicies.TRY_ONCE_THEN_FAIL, maxFailoverAttempts, Math.max(numResponseToDrop + 1, maxRetryAttempts), delay, maxCap)); @SuppressWarnings("unchecked") T proxy = (T) Proxy.newProxyInstance( failoverProxyProvider.getInterface().getClassLoader(), new Class[]{xface}, dummyHandler); Text dtService; if (failoverProxyProvider.useLogicalURI()) { dtService = HAUtilClient.buildTokenServiceForLogicalUri(nameNodeUri, HdfsConstants.HDFS_URI_SCHEME); } else { dtService = SecurityUtil.buildTokenService( DFSUtilClient.getNNAddress(nameNodeUri)); } return new ProxyAndInfo<>(proxy, dtService, DFSUtilClient.getNNAddress(nameNodeUri)); } else { LOG.warn("Currently creating proxy using " + "LossyRetryInvocationHandler requires NN HA setup"); return null; } } /** Creates the Failover proxy provider instance*/ @VisibleForTesting public static <T> AbstractNNFailoverProxyProvider<T> createFailoverProxyProvider( Configuration conf, URI nameNodeUri, Class<T> xface, boolean checkPort, AtomicBoolean fallbackToSimpleAuth) throws IOException { return createFailoverProxyProvider(conf, nameNodeUri, xface, checkPort, fallbackToSimpleAuth, new ClientHAProxyFactory<T>()); } protected static <T> AbstractNNFailoverProxyProvider<T> createFailoverProxyProvider( Configuration conf, URI nameNodeUri, Class<T> xface, boolean checkPort, AtomicBoolean fallbackToSimpleAuth, HAProxyFactory<T> proxyFactory) throws IOException { Class<FailoverProxyProvider<T>> failoverProxyProviderClass = null; AbstractNNFailoverProxyProvider<T> providerNN; try { // Obtain the
which
java
elastic__elasticsearch
qa/full-cluster-restart/src/javaRestTest/java/org/elasticsearch/upgrades/ParameterizedFullClusterRestartTestCase.java
{ "start": 1655, "end": 7592 }
class ____ extends ESRestTestCase { protected static final Version MINIMUM_WIRE_COMPATIBLE_VERSION = Version.fromString( System.getProperty("tests.minimum.wire.compatible") ); protected static final String OLD_CLUSTER_VERSION = System.getProperty("tests.old_cluster_version"); private static IndexVersion oldIndexVersion; private static boolean upgradeFailed = false; private static boolean upgraded = false; private static TestFeatureService oldClusterTestFeatureService; private final FullClusterRestartUpgradeStatus requestedUpgradeStatus; public ParameterizedFullClusterRestartTestCase(@Name("cluster") FullClusterRestartUpgradeStatus upgradeStatus) { this.requestedUpgradeStatus = upgradeStatus; } @ParametersFactory public static Iterable<Object[]> parameters() throws Exception { return Arrays.stream(FullClusterRestartUpgradeStatus.values()).map(v -> new Object[] { v }).toList(); } @Before public void retainOldClusterTestFeatureService() { if (upgraded == false && oldClusterTestFeatureService == null) { assert testFeatureServiceInitialized() : "testFeatureService must be initialized, see ESRestTestCase#initClient"; oldClusterTestFeatureService = testFeatureService; } } @Before public void extractOldIndexVersion() throws Exception { if (upgraded == false) { IndexVersion indexVersion = null; // these should all be the same version Request request = new Request("GET", "_nodes"); request.addParameter("filter_path", "nodes.*.index_version,nodes.*.name"); Response response = client().performRequest(request); ObjectPath objectPath = ObjectPath.createFromResponse(response); Map<String, Object> nodeMap = objectPath.evaluate("nodes"); for (String id : nodeMap.keySet()) { Number ix = objectPath.evaluate("nodes." + id + ".index_version"); IndexVersion version; if (ix != null) { version = IndexVersion.fromId(ix.intValue()); } else { // it doesn't have index version (pre 8.11) - just infer it from the release version version = parseLegacyVersion(OLD_CLUSTER_VERSION).map(x -> IndexVersion.fromId(x.id())) .orElse(IndexVersions.MINIMUM_COMPATIBLE); } if (indexVersion == null) { indexVersion = version; } else { String name = objectPath.evaluate("nodes." + id + ".name"); assertThat("Node " + name + " has a different index version to other nodes", version, equalTo(indexVersion)); } } assertThat("Index version could not be read", indexVersion, notNullValue()); oldIndexVersion = indexVersion; } } protected void beforeUpgrade() { if (getOldClusterVersion().endsWith("-SNAPSHOT")) { assumeTrue("rename of pattern_text mapper", oldClusterHasFeature("mapper.pattern_text_rename")); } } @Before public void maybeUpgrade() throws Exception { if (upgraded == false && requestedUpgradeStatus == UPGRADED) { beforeUpgrade(); try { if (getOldClusterTestVersion().before(MINIMUM_WIRE_COMPATIBLE_VERSION)) { // First upgrade to latest wire compatible version getUpgradeCluster().upgradeToVersion(MINIMUM_WIRE_COMPATIBLE_VERSION); } getUpgradeCluster().upgradeToVersion(Version.CURRENT); closeClients(); initClient(); } catch (Exception e) { upgradeFailed = true; throw e; } finally { upgraded = true; } } // Skip remaining tests if upgrade failed assumeFalse("Cluster upgrade failed", upgradeFailed); } @AfterClass public static void resetUpgrade() { upgraded = false; upgradeFailed = false; oldClusterTestFeatureService = null; } public boolean isRunningAgainstOldCluster() { return requestedUpgradeStatus == OLD; } /** * The version of the "old" (initial) cluster. It is an opaque string, do not even think about parsing it for version * comparison. Use (test) cluster features and {@link ParameterizedFullClusterRestartTestCase#oldClusterHasFeature} instead. */ protected static String getOldClusterVersion() { return System.getProperty("tests.bwc.main.version", OLD_CLUSTER_VERSION); } protected static boolean oldClusterHasFeature(String featureId) { assert oldClusterTestFeatureService != null : "testFeatureService of old cluster cannot be accessed before initialization is completed"; return oldClusterTestFeatureService.clusterHasFeature(featureId); } protected static boolean oldClusterHasFeature(NodeFeature feature) { return oldClusterHasFeature(feature.id()); } public static IndexVersion getOldClusterIndexVersion() { assert oldIndexVersion != null; return oldIndexVersion; } public static Version getOldClusterTestVersion() { return Version.fromString(System.getProperty("tests.bwc.main.version", OLD_CLUSTER_VERSION)); } protected abstract ElasticsearchCluster getUpgradeCluster(); @Override protected String getTestRestCluster() { return getUpgradeCluster().getHttpAddresses(); } @Override protected boolean preserveClusterUponCompletion() { return true; } protected String getRootTestName() { return getTestName().split(" ")[0].toLowerCase(Locale.ROOT); } }
ParameterizedFullClusterRestartTestCase
java
netty__netty
example/src/main/java/io/netty/example/spdy/client/SpdyFrameLogger.java
{ "start": 1193, "end": 2516 }
enum ____ { INBOUND, OUTBOUND } protected final InternalLogger logger; private final InternalLogLevel level; public SpdyFrameLogger(InternalLogLevel level) { this.level = ObjectUtil.checkNotNull(level, "level"); this.logger = InternalLoggerFactory.getInstance(getClass()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (acceptMessage(msg)) { log((SpdyFrame) msg, Direction.INBOUND); } ctx.fireChannelRead(msg); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (acceptMessage(msg)) { log((SpdyFrame) msg, Direction.OUTBOUND); } ctx.write(msg, promise); } private static boolean acceptMessage(Object msg) { return msg instanceof SpdyFrame; } private void log(SpdyFrame msg, Direction d) { if (logger.isEnabled(level)) { StringBuilder b = new StringBuilder(200) .append("\n----------------") .append(d.name()) .append("--------------------\n") .append(msg) .append("\n------------------------------------"); logger.log(level, b.toString()); } } }
Direction
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiersTest.java
{ "start": 12575, "end": 12959 }
interface ____ extends Parent { static final FluentLogger logger = FluentLogger.forEnclosingClass(); default void go() { logger.atInfo().log(); } } """) .addOutputLines( "out/Sibling.java", """ import com.google.common.flogger.FluentLogger;
Sibling
java
elastic__elasticsearch
x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeProcessorTests.java
{ "start": 910, "end": 6401 }
class ____ extends AbstractSqlWireSerializingTestCase<DateTimeProcessor> { public static DateTimeProcessor randomDateTimeProcessor() { return new DateTimeProcessor(randomFrom(DateTimeExtractor.values()), randomZone()); } @Override protected DateTimeProcessor createTestInstance() { return randomDateTimeProcessor(); } @Override protected Reader<DateTimeProcessor> instanceReader() { return DateTimeProcessor::new; } @Override protected ZoneId instanceZoneId(DateTimeProcessor instance) { return instance.zoneId(); } @Override protected DateTimeProcessor mutateInstance(DateTimeProcessor instance) { DateTimeExtractor replaced = randomValueOtherThan(instance.extractor(), () -> randomFrom(DateTimeExtractor.values())); return new DateTimeProcessor(replaced, randomZone()); } public void testApply_withTimezoneUTC() { DateTimeProcessor proc = new DateTimeProcessor(DateTimeExtractor.YEAR, UTC); assertEquals(1970, proc.process(dateTime(0L))); assertEquals(2017, proc.process(dateTime(2017, 01, 02, 10, 10))); proc = new DateTimeProcessor(DateTimeExtractor.DAY_OF_MONTH, UTC); assertEquals(1, proc.process(dateTime(0L))); assertEquals(2, proc.process(dateTime(2017, 01, 02, 10, 10))); assertEquals(31, proc.process(dateTime(2017, 01, 31, 10, 10))); // Tested against MS-SQL Server and H2 proc = new DateTimeProcessor(DateTimeExtractor.ISO_WEEK_OF_YEAR, UTC); assertEquals(1, proc.process(dateTime(1988, 1, 5, 0, 0, 0, 0))); assertEquals(5, proc.process(dateTime(2001, 2, 4, 0, 0, 0, 0))); assertEquals(6, proc.process(dateTime(1977, 2, 8, 0, 0, 0, 0))); assertEquals(11, proc.process(dateTime(1974, 3, 17, 0, 0, 0, 0))); assertEquals(16, proc.process(dateTime(1977, 4, 20, 0, 0, 0, 0))); assertEquals(16, proc.process(dateTime(1994, 4, 20, 0, 0, 0, 0))); assertEquals(17, proc.process(dateTime(2002, 4, 27, 0, 0, 0, 0))); assertEquals(18, proc.process(dateTime(1974, 5, 3, 0, 0, 0, 0))); assertEquals(22, proc.process(dateTime(1997, 5, 30, 0, 0, 0, 0))); assertEquals(22, proc.process(dateTime(1995, 6, 4, 0, 0, 0, 0))); assertEquals(28, proc.process(dateTime(1972, 7, 12, 0, 0, 0, 0))); assertEquals(30, proc.process(dateTime(1980, 7, 26, 0, 0, 0, 0))); assertEquals(33, proc.process(dateTime(1998, 8, 12, 0, 0, 0, 0))); assertEquals(35, proc.process(dateTime(1995, 9, 3, 0, 0, 0, 0))); assertEquals(37, proc.process(dateTime(1976, 9, 9, 0, 0, 0, 0))); assertEquals(38, proc.process(dateTime(1997, 9, 19, 0, 0, 0, 0))); assertEquals(45, proc.process(dateTime(1980, 11, 7, 0, 0, 0, 0))); assertEquals(53, proc.process(dateTime(2005, 1, 1, 0, 0, 0, 0))); assertEquals(1, proc.process(dateTime(2007, 12, 31, 0, 0, 0, 0))); assertEquals(1, proc.process(dateTime(2019, 12, 31, 20, 22, 33, 987654321))); } public void testApply_withTimezoneOtherThanUTC() { ZoneId zoneId = ZoneId.of("Etc/GMT-10"); DateTimeProcessor proc = new DateTimeProcessor(DateTimeExtractor.YEAR, zoneId); assertEquals(2018, proc.process(dateTime(2017, 12, 31, 18, 10))); proc = new DateTimeProcessor(DateTimeExtractor.DAY_OF_MONTH, zoneId); assertEquals(1, proc.process(dateTime(2017, 12, 31, 20, 30))); // Tested against MS-SQL Server and H2 proc = new DateTimeProcessor(DateTimeExtractor.ISO_WEEK_OF_YEAR, UTC); assertEquals(1, proc.process(dateTime(1988, 1, 5, 0, 0, 0, 0))); assertEquals(5, proc.process(dateTime(2001, 2, 4, 0, 0, 0, 0))); assertEquals(6, proc.process(dateTime(1977, 2, 8, 0, 0, 0, 0))); assertEquals(11, proc.process(dateTime(1974, 3, 17, 0, 0, 0, 0))); assertEquals(16, proc.process(dateTime(1977, 4, 20, 0, 0, 0, 0))); assertEquals(16, proc.process(dateTime(1994, 4, 20, 0, 0, 0, 0))); assertEquals(17, proc.process(dateTime(2002, 4, 27, 0, 0, 0, 0))); assertEquals(18, proc.process(dateTime(1974, 5, 3, 0, 0, 0, 0))); assertEquals(22, proc.process(dateTime(1997, 5, 30, 0, 0, 0, 0))); assertEquals(22, proc.process(dateTime(1995, 6, 4, 0, 0, 0, 0))); assertEquals(28, proc.process(dateTime(1972, 7, 12, 0, 0, 0, 0))); assertEquals(30, proc.process(dateTime(1980, 7, 26, 0, 0, 0, 0))); assertEquals(33, proc.process(dateTime(1998, 8, 12, 0, 0, 0, 0))); assertEquals(35, proc.process(dateTime(1995, 9, 3, 0, 0, 0, 0))); assertEquals(37, proc.process(dateTime(1976, 9, 9, 0, 0, 0, 0))); assertEquals(38, proc.process(dateTime(1997, 9, 19, 0, 0, 0, 0))); assertEquals(45, proc.process(dateTime(1980, 11, 7, 0, 0, 0, 0))); assertEquals(53, proc.process(dateTime(2005, 1, 1, 0, 0, 0, 0))); assertEquals(1, proc.process(dateTime(2007, 12, 31, 0, 0, 0, 0))); assertEquals(1, proc.process(dateTime(2019, 12, 31, 20, 22, 33, 987654321))); } public void testFailOnTime() { DateTimeProcessor proc = new DateTimeProcessor(DateTimeExtractor.YEAR, UTC); SqlIllegalArgumentException e = expectThrows(SqlIllegalArgumentException.class, () -> { proc.process(OffsetTime.now(UTC)); }); assertThat(e.getMessage(), startsWith("A [date], a [time] or a [datetime] is required; received ")); } }
DateTimeProcessorTests
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/functions/util/CopyingListCollector.java
{ "start": 1185, "end": 1615 }
class ____<T> implements Collector<T> { private final List<T> list; private final TypeSerializer<T> serializer; public CopyingListCollector(List<T> list, TypeSerializer<T> serializer) { this.list = list; this.serializer = serializer; } @Override public void collect(T record) { list.add(serializer.copy(record)); } @Override public void close() {} }
CopyingListCollector
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/Deserializers.java
{ "start": 12028, "end": 14182 }
class ____ and * other information typically needed for building deserializers * @param keyDeserializer Key deserializer use, if it is defined via annotations or other configuration; * null if default key deserializer for key type can be used. * @param elementTypeDeserializer If element type needs polymorphic type handling, this is * the type information deserializer to use; should usually be used as is when constructing * array deserializer. * @param elementDeserializer Deserializer to use for elements, if explicitly defined (by using * annotations, for example). May be null, in which case it will need to be resolved * by deserializer at a later point. * * @return Deserializer to use for the type; or null if this provider does not know how to construct it */ default ValueDeserializer<?> findMapLikeDeserializer(MapLikeType type, DeserializationConfig config, BeanDescription.Supplier beanDescRef, KeyDeserializer keyDeserializer, TypeDeserializer elementTypeDeserializer, ValueDeserializer<?> elementDeserializer) { return null; } /** * Method that may be called to check whether this deserializer provider would provide * deserializer for values of given type, without attempting to construct (and possibly * fail in some cases) actual deserializer. Mostly needed to support validation * of polymorphic type ids. *<p> * Note: implementations should take care NOT to claim supporting types that they do * not recognize as this could to incorrect assumption of safe support by caller. * * @since 3.0 */ boolean hasDeserializerFor(DeserializationConfig config, Class<?> valueType); /* /********************************************************************** /* Helper classes /********************************************************************** */ /** * Basic {@link Deserializers} implementation that implements all methods but provides * no deserializers. Its main purpose is to serve as a base
annotations
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/functions/BiConsumer.java
{ "start": 897, "end": 1215 }
interface ____<@NonNull T1, @NonNull T2> { /** * Performs an operation on the given values. * @param t1 the first value * @param t2 the second value * @throws Throwable if the implementation wishes to throw any type of exception */ void accept(T1 t1, T2 t2) throws Throwable; }
BiConsumer
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/BuiltInAggregateFunctionTestBase.java
{ "start": 18843, "end": 24030 }
class ____ extends SuccessItem { private final List<Expression> selectExpr; private final List<Expression> groupByExpr; public TableApiSqlResultTestItem( List<Expression> selectExpr, @Nullable List<Expression> groupByExpr, @Nullable DataType expectedRowType, @Nullable List<Row> expectedRows) { super(expectedRowType, expectedRows); this.selectExpr = selectExpr; this.groupByExpr = groupByExpr; } @Override protected TableResult getResult(TableEnvironment tEnv, Table sourceTable) { final Table select; if (groupByExpr != null) { select = sourceTable .groupBy(groupByExpr.toArray(new Expression[0])) .select(selectExpr.toArray(new Expression[0])); } else { select = sourceTable.select(selectExpr.toArray(new Expression[0])); } final ProjectQueryOperation projectQueryOperation = (ProjectQueryOperation) select.getQueryOperation(); final AggregateQueryOperation aggQueryOperation = (AggregateQueryOperation) select.getQueryOperation().getChildren().get(0); final List<ResolvedExpression> selectExpr = recreateSelectList(aggQueryOperation, projectQueryOperation); final String selectAsSerializableString = toSerializableExpr(selectExpr); final String groupByAsSerializableString = toSerializableExpr(aggQueryOperation.getGroupingExpressions()); final StringBuilder stringBuilder = new StringBuilder(); stringBuilder .append("SELECT ") .append(selectAsSerializableString) .append(" FROM ") .append(sourceTable); if (!groupByAsSerializableString.isEmpty()) { stringBuilder.append(" GROUP BY ").append(groupByAsSerializableString); } return tEnv.sqlQuery(stringBuilder.toString()).execute(); } private static List<ResolvedExpression> recreateSelectList( AggregateQueryOperation aggQueryOperation, ProjectQueryOperation projectQueryOperation) { final List<String> projectSchemaFields = projectQueryOperation.getResolvedSchema().getColumnNames(); final List<String> aggSchemaFields = aggQueryOperation.getResolvedSchema().getColumnNames(); return IntStream.range(0, projectSchemaFields.size()) .mapToObj( idx -> { final int indexInAgg = aggSchemaFields.indexOf(projectSchemaFields.get(idx)); if (indexInAgg >= 0) { final int groupingExprCount = aggQueryOperation.getGroupingExpressions().size(); if (indexInAgg < groupingExprCount) { return aggQueryOperation .getGroupingExpressions() .get(indexInAgg); } else { return aggQueryOperation .getAggregateExpressions() .get(indexInAgg - groupingExprCount); } } else { return projectQueryOperation.getProjectList().get(idx); } }) .collect(Collectors.toList()); } private static String toSerializableExpr(List<ResolvedExpression> expressions) { return expressions.stream() .map( resolvedExpression -> resolvedExpression.asSerializableString( DefaultSqlFactory.INSTANCE)) .collect(Collectors.joining(", ")); } @Override public String toString() { return String.format( "[API as SQL] select: [%s] groupBy: [%s]", selectExpr.stream() .map(Expression::asSummaryString) .collect(Collectors.joining(", ")), groupByExpr != null ? groupByExpr.stream() .map(Expression::asSummaryString) .collect(Collectors.joining(", ")) : ""); } } // --------------------------------------------------------------------------------------------- private abstract static
TableApiSqlResultTestItem
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng7566JavaPrerequisiteTest.java
{ "start": 1090, "end": 3242 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Verify that builds fail straight when the current Java version doesn't match a plugin's prerequisite. * * @throws Exception in case of failure */ @Test void testitMojoExecution() throws Exception { File testDir = extractResources("/mng-7566"); Verifier verifier = newVerifier(new File(testDir, "test-1").getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.deleteArtifacts("org.apache.maven.its.mng7566"); verifier.addCliArgument("-s"); verifier.addCliArgument("settings.xml"); verifier.filterFile("../settings-template.xml", "settings.xml"); try { verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); fail("Build did not fail despite unsatisfied prerequisite of plugin on Maven version."); } catch (Exception e) { // expected, unsolvable version conflict } } /** * Verify that automatic plugin version resolution automatically skips plugin versions whose prerequisite on * the current Java version isn't satisfied. * * @throws Exception in case of failure */ @Test void testitPluginVersionResolution() throws Exception { File testDir = extractResources("/mng-7566"); Verifier verifier = newVerifier(new File(testDir, "test-2").getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.deleteArtifacts("org.apache.maven.its.mng7566"); verifier.addCliArgument("-s"); verifier.addCliArgument("settings.xml"); verifier.filterFile("../settings-template.xml", "settings.xml"); verifier.addCliArgument("org.apache.maven.its.mng7566:maven-mng7566-plugin:touch"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyFilePresent("target/touch-1.txt"); verifier.verifyFileNotPresent("target/touch-2.txt"); } }
MavenITmng7566JavaPrerequisiteTest
java
google__guava
guava/src/com/google/common/graph/Graphs.java
{ "start": 16986, "end": 25267 }
class ____<N, E> extends ForwardingNetwork<N, E> { private final Network<N, E> network; TransposedNetwork(Network<N, E> network) { this.network = network; } @Override Network<N, E> delegate() { return network; } @Override public Set<N> predecessors(N node) { return delegate().successors(node); // transpose } @Override public Set<N> successors(N node) { return delegate().predecessors(node); // transpose } @Override public int inDegree(N node) { return delegate().outDegree(node); // transpose } @Override public int outDegree(N node) { return delegate().inDegree(node); // transpose } @Override public Set<E> inEdges(N node) { return delegate().outEdges(node); // transpose } @Override public Set<E> outEdges(N node) { return delegate().inEdges(node); // transpose } @Override public EndpointPair<N> incidentNodes(E edge) { EndpointPair<N> endpointPair = delegate().incidentNodes(edge); return EndpointPair.of(network, endpointPair.nodeV(), endpointPair.nodeU()); // transpose } @Override public Set<E> edgesConnecting(N nodeU, N nodeV) { return delegate().edgesConnecting(nodeV, nodeU); // transpose } @Override public Set<E> edgesConnecting(EndpointPair<N> endpoints) { return delegate().edgesConnecting(transpose(endpoints)); } @Override public Optional<E> edgeConnecting(N nodeU, N nodeV) { return delegate().edgeConnecting(nodeV, nodeU); // transpose } @Override public Optional<E> edgeConnecting(EndpointPair<N> endpoints) { return delegate().edgeConnecting(transpose(endpoints)); } @Override public @Nullable E edgeConnectingOrNull(N nodeU, N nodeV) { return delegate().edgeConnectingOrNull(nodeV, nodeU); // transpose } @Override public @Nullable E edgeConnectingOrNull(EndpointPair<N> endpoints) { return delegate().edgeConnectingOrNull(transpose(endpoints)); } @Override public boolean hasEdgeConnecting(N nodeU, N nodeV) { return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose } @Override public boolean hasEdgeConnecting(EndpointPair<N> endpoints) { return delegate().hasEdgeConnecting(transpose(endpoints)); } } // Graph copy methods /** * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges} * from {@code graph} for which both nodes are contained by {@code nodes}. * * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph */ public static <N> MutableGraph<N> inducedSubgraph(Graph<N> graph, Iterable<? extends N> nodes) { MutableGraph<N> subgraph = (nodes instanceof Collection) ? GraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build() : GraphBuilder.from(graph).build(); for (N node : nodes) { subgraph.addNode(node); } for (N node : subgraph.nodes()) { for (N successorNode : graph.successors(node)) { if (subgraph.nodes().contains(successorNode)) { subgraph.putEdge(node, successorNode); } } } return subgraph; } /** * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges} * (and associated edge values) from {@code graph} for which both nodes are contained by {@code * nodes}. * * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph */ public static <N, V> MutableValueGraph<N, V> inducedSubgraph( ValueGraph<N, V> graph, Iterable<? extends N> nodes) { MutableValueGraph<N, V> subgraph = (nodes instanceof Collection) ? ValueGraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build() : ValueGraphBuilder.from(graph).build(); for (N node : nodes) { subgraph.addNode(node); } for (N node : subgraph.nodes()) { for (N successorNode : graph.successors(node)) { if (subgraph.nodes().contains(successorNode)) { // requireNonNull is safe because the endpoint pair comes from the graph. subgraph.putEdgeValue( node, successorNode, requireNonNull(graph.edgeValueOrDefault(node, successorNode, null))); } } } return subgraph; } /** * Returns the subgraph of {@code network} induced by {@code nodes}. This subgraph is a new graph * that contains all of the nodes in {@code nodes}, and all of the {@link Network#edges() edges} * from {@code network} for which the {@link Network#incidentNodes(Object) incident nodes} are * both contained by {@code nodes}. * * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph */ public static <N, E> MutableNetwork<N, E> inducedSubgraph( Network<N, E> network, Iterable<? extends N> nodes) { MutableNetwork<N, E> subgraph = (nodes instanceof Collection) ? NetworkBuilder.from(network).expectedNodeCount(((Collection) nodes).size()).build() : NetworkBuilder.from(network).build(); for (N node : nodes) { subgraph.addNode(node); } for (N node : subgraph.nodes()) { for (E edge : network.outEdges(node)) { N successorNode = network.incidentNodes(edge).adjacentNode(node); if (subgraph.nodes().contains(successorNode)) { subgraph.addEdge(node, successorNode, edge); } } } return subgraph; } /** Creates a mutable copy of {@code graph} with the same nodes and edges. */ public static <N> MutableGraph<N> copyOf(Graph<N> graph) { MutableGraph<N> copy = GraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build(); for (N node : graph.nodes()) { copy.addNode(node); } for (EndpointPair<N> edge : graph.edges()) { copy.putEdge(edge.nodeU(), edge.nodeV()); } return copy; } /** Creates a mutable copy of {@code graph} with the same nodes, edges, and edge values. */ public static <N, V> MutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) { MutableValueGraph<N, V> copy = ValueGraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build(); for (N node : graph.nodes()) { copy.addNode(node); } for (EndpointPair<N> edge : graph.edges()) { // requireNonNull is safe because the endpoint pair comes from the graph. copy.putEdgeValue( edge.nodeU(), edge.nodeV(), requireNonNull(graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null))); } return copy; } /** Creates a mutable copy of {@code network} with the same nodes and edges. */ public static <N, E> MutableNetwork<N, E> copyOf(Network<N, E> network) { MutableNetwork<N, E> copy = NetworkBuilder.from(network) .expectedNodeCount(network.nodes().size()) .expectedEdgeCount(network.edges().size()) .build(); for (N node : network.nodes()) { copy.addNode(node); } for (E edge : network.edges()) { EndpointPair<N> endpointPair = network.incidentNodes(edge); copy.addEdge(endpointPair.nodeU(), endpointPair.nodeV(), edge); } return copy; } @CanIgnoreReturnValue static int checkNonNegative(int value) { checkArgument(value >= 0, "Not true that %s is non-negative.", value); return value; } @CanIgnoreReturnValue static long checkNonNegative(long value) { checkArgument(value >= 0, "Not true that %s is non-negative.", value); return value; } @CanIgnoreReturnValue static int checkPositive(int value) { checkArgument(value > 0, "Not true that %s is positive.", value); return value; } @CanIgnoreReturnValue static long checkPositive(long value) { checkArgument(value > 0, "Not true that %s is positive.", value); return value; } /** * An
TransposedNetwork
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/bytearray/ByteArrayAssert_hasSizeBetween_Test.java
{ "start": 800, "end": 1142 }
class ____ extends ByteArrayAssertBaseTest { @Override protected ByteArrayAssert invoke_api_method() { return assertions.hasSizeBetween(4, 6); } @Override protected void verify_internal_effects() { verify(arrays).assertHasSizeBetween(getInfo(assertions), getActual(assertions), 4, 6); } }
ByteArrayAssert_hasSizeBetween_Test
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/errors/VoterNotFoundException.java
{ "start": 847, "end": 1145 }
class ____ extends ApiException { private static final long serialVersionUID = 1L; public VoterNotFoundException(String message) { super(message); } public VoterNotFoundException(String message, Throwable cause) { super(message, cause); } }
VoterNotFoundException
java
apache__camel
components/camel-twitter/src/main/java/org/apache/camel/component/twitter/TwitterConfiguration.java
{ "start": 1074, "end": 11317 }
class ____ { @UriParam(label = "consumer", defaultValue = "polling", enums = "polling,direct") private EndpointType type = EndpointType.POLLING; @UriParam(label = "security", secret = true) private String accessToken; @UriParam(label = "security", secret = true) private String accessTokenSecret; @UriParam(label = "security", secret = true) private String consumerKey; @UriParam(label = "security", secret = true) private String consumerSecret; @UriParam(label = "consumer,filter") private String userIds; @UriParam(label = "consumer,filter", defaultValue = "true") private boolean filterOld = true; @UriParam(label = "consumer,filter", defaultValue = "1") private long sinceId = 1; @UriParam(label = "consumer,filter") private String lang; @UriParam(label = "consumer,filter", defaultValue = "5") private Integer count = 5; @UriParam(label = "consumer,filter", defaultValue = "1") private Integer numberOfPages = 1; @UriParam(label = "consumer,sort", defaultValue = "true") private boolean sortById = true; @UriParam(label = "proxy") private String httpProxyHost; @UriParam(label = "proxy") private String httpProxyUser; @UriParam(label = "proxy") private String httpProxyPassword; @UriParam(label = "proxy") private Integer httpProxyPort; @UriParam(label = "consumer,advanced") private String locations; @UriParam(label = "consumer,advanced") private Double latitude; @UriParam(label = "consumer,advanced") private Double longitude; @UriParam(label = "consumer,advanced") private Double radius; @UriParam(label = "consumer,advanced", defaultValue = "km", enums = "km,mi") private String distanceMetric; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean extendedMode = true; /** * Singleton, on demand instances of Twitter4J's Twitter. This should not be created by an endpoint's doStart(), * etc., since instances of twitter can be supplied by the route itself. */ private Twitter twitter; /** * Ensures required fields are available. */ public void checkComplete() { if (twitter == null && (ObjectHelper.isEmpty(consumerKey) || ObjectHelper.isEmpty(consumerSecret) || ObjectHelper.isEmpty(accessToken) || ObjectHelper.isEmpty(accessTokenSecret))) { throw new IllegalArgumentException( "twitter or all of consumerKey, consumerSecret, accessToken, and accessTokenSecret must be set!"); } } /** * Builds {@link Twitter} with the current configuration. */ protected Twitter buildTwitter() { checkComplete(); Twitter.TwitterBuilder builder = Twitter.newBuilder() .oAuthConsumer(consumerKey, consumerSecret) .oAuthAccessToken(accessToken, accessTokenSecret) .tweetModeExtended(isExtendedMode()) .httpProxyHost(getHttpProxyHost()) .httpProxyUser(getHttpProxyUser()) .httpProxyPassword(getHttpProxyPassword()); if (getHttpProxyPort() != null) { builder.httpProxyPort(getHttpProxyPort()); } return builder.build(); } public Twitter getTwitter() { if (twitter == null) { twitter = buildTwitter(); } return twitter; } public void setTwitter(Twitter twitter) { this.twitter = twitter; } public String getConsumerKey() { return consumerKey; } /** * The consumer key. Can also be configured on the TwitterComponent level instead. */ public void setConsumerKey(String consumerKey) { this.consumerKey = consumerKey; } public String getConsumerSecret() { return consumerSecret; } /** * The consumer secret. Can also be configured on the TwitterComponent level instead. */ public void setConsumerSecret(String consumerSecret) { this.consumerSecret = consumerSecret; } /** * The access token. Can also be configured on the TwitterComponent level instead. */ public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } /** * The access secret. Can also be configured on the TwitterComponent level instead. */ public String getAccessTokenSecret() { return accessTokenSecret; } public void setAccessTokenSecret(String accessTokenSecret) { this.accessTokenSecret = accessTokenSecret; } public EndpointType getType() { return type; } /** * Endpoint type to use. */ public void setType(EndpointType type) { this.type = type; } public String getLocations() { return locations; } /** * Bounding boxes, created by pairs of lat/lons. Can be used for filter. A pair is defined as lat,lon. And multiple * pairs can be separated by semicolon. */ public void setLocations(String locations) { this.locations = locations; } public String getUserIds() { return userIds; } /** * To filter by user ids for filter. Multiple values can be separated by comma. */ public void setUserIds(String userIds) { this.userIds = userIds; } public boolean isFilterOld() { return filterOld; } /** * Filter out old tweets, that has previously been polled. This state is stored in memory only, and based on last * tweet id. */ public void setFilterOld(boolean filterOld) { this.filterOld = filterOld; } public long getSinceId() { return sinceId; } /** * The last tweet id which will be used for pulling the tweets. It is useful when the camel route is restarted after * a long running. */ public void setSinceId(long sinceId) { this.sinceId = sinceId; } public String getLang() { return lang; } /** * The lang string ISO_639-1 which will be used for searching */ public void setLang(String lang) { this.lang = lang; } public Integer getCount() { return count; } /** * Limiting number of results per page. */ public void setCount(Integer count) { this.count = count; } public Integer getNumberOfPages() { return numberOfPages; } /** * The number of pages result which you want camel-twitter to consume. */ public void setNumberOfPages(Integer numberOfPages) { this.numberOfPages = numberOfPages; } public boolean isSortById() { return sortById; } /** * Sorts by id, so the oldest are first, and newest last. */ public void setSortById(boolean sortById) { this.sortById = sortById; } /** * The http proxy host which can be used for the camel-twitter. Can also be configured on the TwitterComponent level * instead. */ public void setHttpProxyHost(String httpProxyHost) { this.httpProxyHost = httpProxyHost; } public String getHttpProxyHost() { return httpProxyHost; } /** * The http proxy user which can be used for the camel-twitter. Can also be configured on the TwitterComponent level * instead. */ public void setHttpProxyUser(String httpProxyUser) { this.httpProxyUser = httpProxyUser; } public String getHttpProxyUser() { return httpProxyUser; } /** * The http proxy password which can be used for the camel-twitter. Can also be configured on the TwitterComponent * level instead. */ public void setHttpProxyPassword(String httpProxyPassword) { this.httpProxyPassword = httpProxyPassword; } public String getHttpProxyPassword() { return httpProxyPassword; } /** * The http proxy port which can be used for the camel-twitter. Can also be configured on the TwitterComponent level * instead. */ public void setHttpProxyPort(Integer httpProxyPort) { this.httpProxyPort = httpProxyPort; } public Integer getHttpProxyPort() { return httpProxyPort; } public Double getLongitude() { return longitude; } /** * Used by the geography search to search by longitude. * <p/> * You need to configure all the following options: longitude, latitude, radius, and distanceMetric. */ public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getLatitude() { return latitude; } /** * Used by the geography search to search by latitude. * <p/> * You need to configure all the following options: longitude, latitude, radius, and distanceMetric. */ public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getRadius() { return radius; } /** * Used by the geography search to search by radius. * <p/> * You need to configure all the following options: longitude, latitude, radius, and distanceMetric. */ public void setRadius(Double radius) { this.radius = radius; } public String getDistanceMetric() { return distanceMetric; } /** * Used by the geography search, to search by radius using the configured metrics. * <p/> * The unit can either be mi for miles, or km for kilometers. * <p/> * You need to configure all the following options: longitude, latitude, radius, and distanceMetric. */ public void setDistanceMetric(String distanceMetric) { this.distanceMetric = distanceMetric; } /** * Used for enabling full text from twitter (eg receive tweets that contains more than 140 characters). */ public void setExtendedMode(Boolean extendedMode) { this.extendedMode = extendedMode; } public boolean isExtendedMode() { return extendedMode; } }
TwitterConfiguration
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/objectid/ReferentialWithObjectIdTest.java
{ "start": 478, "end": 663 }
class ____ { public AtomicReference<Employee> first; } @JsonIdentityInfo(property="id", generator=ObjectIdGenerators.PropertyGenerator.class) public static
EmployeeList
java
apache__rocketmq
test/src/test/java/org/apache/rocketmq/test/offset/OffsetNotFoundIT.java
{ "start": 1586, "end": 1704 }
class ____ extends BaseConf { private OffsetRpcHook offsetRpcHook = new OffsetRpcHook(); static
OffsetNotFoundIT
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/ValidateTest.java
{ "start": 61437, "end": 62918 }
class ____ { @Test void shouldNotThrowExceptionForValidIndex() { Validate.validIndex("a", 0); } @Test void shouldReturnSameInstance() { final String str = "a"; assertSame(str, Validate.validIndex(str, 0)); } @Test void shouldThrowIndexOutOfBoundsExceptionWithDefaultMessageForIndexOutOfBounds() { final IndexOutOfBoundsException ex = assertIndexOutOfBoundsException(() -> Validate.validIndex("a", 1)); assertEquals("The validated character sequence index is invalid: 1", ex.getMessage()); } @Test void shouldThrowIndexOutOfBoundsExceptionWithDefaultMessageForNegativeIndex() { final IndexOutOfBoundsException ex = assertIndexOutOfBoundsException(() -> Validate.validIndex("a", -1)); assertEquals("The validated character sequence index is invalid: -1", ex.getMessage()); } @Test void shouldThrowNullPointerExceptionWithDefaultForNullString() { final NullPointerException ex = assertNullPointerException(() -> Validate.validIndex((String) null, 1)); assertEquals("chars", ex.getMessage()); } } } @Nested final
WithoutMessage
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/action/TransportUpdateConnectorPipelineAction.java
{ "start": 817, "end": 1828 }
class ____ extends HandledTransportAction< UpdateConnectorPipelineAction.Request, ConnectorUpdateActionResponse> { protected final ConnectorIndexService connectorIndexService; @Inject public TransportUpdateConnectorPipelineAction(TransportService transportService, ActionFilters actionFilters, Client client) { super( UpdateConnectorPipelineAction.NAME, transportService, actionFilters, UpdateConnectorPipelineAction.Request::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.connectorIndexService = new ConnectorIndexService(client); } @Override protected void doExecute( Task task, UpdateConnectorPipelineAction.Request request, ActionListener<ConnectorUpdateActionResponse> listener ) { connectorIndexService.updateConnectorPipeline(request, listener.map(r -> new ConnectorUpdateActionResponse(r.getResult()))); } }
TransportUpdateConnectorPipelineAction
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/TransientOverrideAsPersistentJoinedTests.java
{ "start": 11116, "end": 11638 }
class ____ { private String name; private Employee employee; private String description; public Job(String name) { this(); setName( name ); } @Id public String getName() { return name; } @OneToOne @JoinColumn(name = "employee_name") public Employee getEmployee() { return employee; } protected Job() { // this form used by Hibernate } protected void setName(String name) { this.name = name; } protected void setEmployee(Employee e) { this.employee = e; } } }
Job
java
grpc__grpc-java
examples/src/main/java/io/grpc/examples/retrying/RetryingHelloWorldServer.java
{ "start": 1239, "end": 3175 }
class ____ { private static final Logger logger = Logger.getLogger(RetryingHelloWorldServer.class.getName()); private static final float UNAVAILABLE_PERCENTAGE = 0.5F; private static final Random random = new Random(); private Server server; private void start() throws IOException { /* The port on which the server should run */ int port = 50051; server = Grpc.newServerBuilderForPort(port, InsecureServerCredentials.create()) .addService(new GreeterImpl()) .build() .start(); logger.info("Server started, listening on " + port); DecimalFormat df = new DecimalFormat("#%"); logger.info("Responding as UNAVAILABLE to " + df.format(UNAVAILABLE_PERCENTAGE) + " requests"); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { // Use stderr here since the logger may have been reset by its JVM shutdown hook. System.err.println("*** shutting down gRPC server since JVM is shutting down"); try { RetryingHelloWorldServer.this.stop(); } catch (InterruptedException e) { e.printStackTrace(System.err); } System.err.println("*** server shut down"); } }); } private void stop() throws InterruptedException { if (server != null) { server.shutdown().awaitTermination(30, TimeUnit.SECONDS); } } /** * Await termination on the main thread since the grpc library uses daemon threads. */ private void blockUntilShutdown() throws InterruptedException { if (server != null) { server.awaitTermination(); } } /** * Main launches the server from the command line. */ public static void main(String[] args) throws IOException, InterruptedException { final RetryingHelloWorldServer server = new RetryingHelloWorldServer(); server.start(); server.blockUntilShutdown(); } static
RetryingHelloWorldServer
java
elastic__elasticsearch
x-pack/plugin/ml-package-loader/src/test/java/org/elasticsearch/xpack/ml/packageloader/action/TransportLoadTrainedModelPackageTests.java
{ "start": 2244, "end": 11513 }
class ____ extends ESTestCase { private static final String MODEL_IMPORT_FAILURE_MSG_FORMAT = "Model importing failed due to %s [%s]"; public void testSendsFinishedUploadNotification() { var uploader = createUploader(null); var taskManager = mock(TaskManager.class); var task = mock(ModelDownloadTask.class); var client = mock(Client.class); TransportLoadTrainedModelPackage.importModel(client, () -> {}, createRequestWithWaiting(), uploader, task, ActionListener.noop()); var notificationArg = ArgumentCaptor.forClass(AuditMlNotificationAction.Request.class); // 2 notifications- the start and finish messages verify(client, times(2)).execute(eq(AuditMlNotificationAction.INSTANCE), notificationArg.capture(), any()); // Only the last message is captured assertThat(notificationArg.getValue().getMessage(), CoreMatchers.containsString("finished model import after")); } public void testSendsErrorNotificationForInternalError() throws Exception { ElasticsearchStatusException exception = new ElasticsearchStatusException("exception", RestStatus.INTERNAL_SERVER_ERROR); String message = format("Model importing failed due to [%s]", exception.toString()); assertUploadCallsOnFailure(exception, message, Level.ERROR); } public void testSendsErrorNotificationForMalformedURL() throws Exception { MalformedURLException exception = new MalformedURLException("exception"); String message = format(MODEL_IMPORT_FAILURE_MSG_FORMAT, "an invalid URL", exception.toString()); assertUploadCallsOnFailure(exception, message, RestStatus.BAD_REQUEST, Level.ERROR); } public void testSendsErrorNotificationForURISyntax() throws Exception { URISyntaxException exception = mock(URISyntaxException.class); String message = format(MODEL_IMPORT_FAILURE_MSG_FORMAT, "an invalid URL syntax", exception.toString()); assertUploadCallsOnFailure(exception, message, RestStatus.BAD_REQUEST, Level.ERROR); } public void testSendsErrorNotificationForIOException() throws Exception { IOException exception = mock(IOException.class); String message = format(MODEL_IMPORT_FAILURE_MSG_FORMAT, "an IOException", exception.toString()); assertUploadCallsOnFailure(exception, message, RestStatus.SERVICE_UNAVAILABLE, Level.ERROR); } public void testSendsErrorNotificationForException() throws Exception { RuntimeException exception = mock(RuntimeException.class); String message = format(MODEL_IMPORT_FAILURE_MSG_FORMAT, "an Exception", exception.toString()); assertUploadCallsOnFailure(exception, message, RestStatus.INTERNAL_SERVER_ERROR, Level.ERROR); } public void testSendsWarningNotificationForTaskCancelledException() throws Exception { TaskCancelledException exception = new TaskCancelledException("cancelled"); String message = format("Model importing failed due to [%s]", exception.toString()); assertUploadCallsOnFailure(exception, message, Level.WARNING); } public void testCallsOnResponseWithAcknowledgedResponse() throws Exception { var client = mock(Client.class); var taskManager = mock(TaskManager.class); var task = mock(ModelDownloadTask.class); ModelImporter uploader = createUploader(null); var responseRef = new AtomicReference<AcknowledgedResponse>(); var listener = ActionListener.wrap(responseRef::set, e -> fail("received an exception: " + e.getMessage())); TransportLoadTrainedModelPackage.importModel(client, () -> {}, createRequestWithWaiting(), uploader, task, listener); assertThat(responseRef.get(), is(AcknowledgedResponse.TRUE)); } public void testDoesNotCallListenerWhenNotWaitingForCompletion() { var uploader = mock(ModelImporter.class); var client = mock(Client.class); var task = mock(ModelDownloadTask.class); TransportLoadTrainedModelPackage.importModel( client, () -> {}, createRequestWithoutWaiting(), uploader, task, ActionListener.running(ESTestCase::fail) ); } public void testWaitForExistingDownload() { var taskManager = mock(TaskManager.class); var modelId = "foo"; var task = new ModelDownloadTask(1L, MODEL_IMPORT_TASK_TYPE, MODEL_IMPORT_TASK_ACTION, modelId, new TaskId("node", 1L), Map.of()); when(taskManager.getCancellableTasks()).thenReturn(Map.of(1L, task)); var transportService = mock(TransportService.class); when(transportService.getTaskManager()).thenReturn(taskManager); var action = new TransportLoadTrainedModelPackage( transportService, mock(ClusterService.class), mock(ThreadPool.class), mock(ActionFilters.class), mock(Client.class), mock(CircuitBreakerService.class) ); assertTrue(action.handleDownloadInProgress(modelId, true, ActionListener.noop())); verify(taskManager).registerRemovedTaskListener(any()); assertThat(action.taskRemovedListenersByModelId.entrySet(), hasSize(1)); assertThat(action.taskRemovedListenersByModelId.get(modelId), hasSize(1)); // With wait for completion == false no new removed listener will be added assertTrue(action.handleDownloadInProgress(modelId, false, ActionListener.noop())); verify(taskManager, times(1)).registerRemovedTaskListener(any()); assertThat(action.taskRemovedListenersByModelId.entrySet(), hasSize(1)); assertThat(action.taskRemovedListenersByModelId.get(modelId), hasSize(1)); assertFalse(action.handleDownloadInProgress("no-task-for-this-one", randomBoolean(), ActionListener.noop())); } private void assertUploadCallsOnFailure(Exception exception, String message, RestStatus status, Level level) throws Exception { var esStatusException = new ElasticsearchStatusException(message, status, exception); assertNotificationAndOnFailure(exception, esStatusException, message, level); } private void assertUploadCallsOnFailure(ElasticsearchException exception, String message, Level level) throws Exception { assertNotificationAndOnFailure(exception, exception, message, level); } private void assertNotificationAndOnFailure( Exception thrownException, ElasticsearchException onFailureException, String message, Level level ) throws Exception { var client = mock(Client.class); var taskManager = mock(TaskManager.class); var task = mock(ModelDownloadTask.class); ModelImporter uploader = createUploader(thrownException); var failureRef = new AtomicReference<Exception>(); var listener = ActionListener.wrap( (AcknowledgedResponse response) -> { fail("received a acknowledged response: " + response.toString()); }, failureRef::set ); TransportLoadTrainedModelPackage.importModel( client, () -> taskManager.unregister(task), createRequestWithWaiting(), uploader, task, listener ); var notificationArg = ArgumentCaptor.forClass(AuditMlNotificationAction.Request.class); // 2 notifications- the starting message and the failure verify(client, times(2)).execute(eq(AuditMlNotificationAction.INSTANCE), notificationArg.capture(), any()); var notification = notificationArg.getValue(); assertThat(notification.getMessage(), is(message)); // the last message is captured assertThat(notification.getLevel(), is(level)); // the last message is captured var receivedException = (ElasticsearchException) failureRef.get(); assertThat(receivedException.toString(), is(onFailureException.toString())); assertThat(receivedException.status(), is(onFailureException.status())); assertThat(receivedException.getCause(), is(onFailureException.getCause())); verify(taskManager).unregister(task); } @SuppressWarnings("unchecked") private ModelImporter createUploader(Exception exception) { ModelImporter uploader = mock(ModelImporter.class); doAnswer(invocation -> { ActionListener<AcknowledgedResponse> listener = (ActionListener<AcknowledgedResponse>) invocation.getArguments()[0]; if (exception != null) { listener.onFailure(exception); } else { listener.onResponse(AcknowledgedResponse.TRUE); } return null; }).when(uploader).doImport(any(ActionListener.class)); return uploader; } private LoadTrainedModelPackageAction.Request createRequestWithWaiting() { return new LoadTrainedModelPackageAction.Request("id", mock(ModelPackageConfig.class), true); } private LoadTrainedModelPackageAction.Request createRequestWithoutWaiting() { return new LoadTrainedModelPackageAction.Request("id", mock(ModelPackageConfig.class), false); } }
TransportLoadTrainedModelPackageTests
java
quarkusio__quarkus
core/deployment/src/test/java/io/quarkus/deployment/conditionaldeps/CascadingConditionalDependenciesTest.java
{ "start": 650, "end": 4043 }
class ____ extends BootstrapFromOriginalJarTestBase { @Override protected TsArtifact composeApplication() { final TsQuarkusExt extA = new TsQuarkusExt("ext-a"); final TsQuarkusExt extB = new TsQuarkusExt("ext-b"); final TsQuarkusExt extC = new TsQuarkusExt("ext-c"); final TsQuarkusExt extD = new TsQuarkusExt("ext-d"); final TsQuarkusExt extE = new TsQuarkusExt("ext-e"); final TsQuarkusExt extF = new TsQuarkusExt("ext-f"); final TsQuarkusExt extG = new TsQuarkusExt("ext-g"); final TsQuarkusExt extH = new TsQuarkusExt("ext-h"); extA.setConditionalDeps(extB, extF); extB.setDependencyCondition(extC); extB.setConditionalDeps(extD); extD.setDependencyCondition(extE); extE.addDependency(extC); extE.setDependencyCondition(extA); extE.setDependencyCondition(extG); extF.setDependencyCondition(extD); extG.setDependencyCondition(extH); addToExpectedLib(extA.getRuntime()); addToExpectedLib(extB.getRuntime()); addToExpectedLib(extC.getRuntime()); addToExpectedLib(extD.getRuntime()); addToExpectedLib(extE.getRuntime()); addToExpectedLib(extF.getRuntime()); install(extA); install(extB); install(extC); install(extD); install(extE); install(extF); install(extG); install(extH); return TsArtifact.jar("app") .addManagedDependency(platformDescriptor()) .addManagedDependency(platformProperties()) .addDependency(extA) .addDependency(extE); } @Override protected void assertAppModel(ApplicationModel model) throws Exception { final Set<Dependency> expected = new HashSet<>(); expected.add(new ArtifactDependency( ArtifactCoords.jar(TsArtifact.DEFAULT_GROUP_ID, "ext-c-deployment", TsArtifact.DEFAULT_VERSION), JavaScopes.COMPILE, DependencyFlags.DEPLOYMENT_CP)); expected.add(new ArtifactDependency( ArtifactCoords.jar(TsArtifact.DEFAULT_GROUP_ID, "ext-a-deployment", TsArtifact.DEFAULT_VERSION), JavaScopes.COMPILE, DependencyFlags.DEPLOYMENT_CP)); expected.add(new ArtifactDependency( ArtifactCoords.jar(TsArtifact.DEFAULT_GROUP_ID, "ext-b-deployment", TsArtifact.DEFAULT_VERSION), JavaScopes.COMPILE, DependencyFlags.DEPLOYMENT_CP)); expected.add(new ArtifactDependency( ArtifactCoords.jar(TsArtifact.DEFAULT_GROUP_ID, "ext-d-deployment", TsArtifact.DEFAULT_VERSION), JavaScopes.COMPILE, DependencyFlags.DEPLOYMENT_CP)); expected.add(new ArtifactDependency( ArtifactCoords.jar(TsArtifact.DEFAULT_GROUP_ID, "ext-e-deployment", TsArtifact.DEFAULT_VERSION), JavaScopes.COMPILE, DependencyFlags.DEPLOYMENT_CP)); expected.add(new ArtifactDependency( ArtifactCoords.jar(TsArtifact.DEFAULT_GROUP_ID, "ext-f-deployment", TsArtifact.DEFAULT_VERSION), JavaScopes.COMPILE, DependencyFlags.DEPLOYMENT_CP)); assertEquals(expected, getDeploymentOnlyDeps(model)); } }
CascadingConditionalDependenciesTest
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/TaskExecutorConfigurations.java
{ "start": 5435, "end": 7496 }
class ____ { private final TaskExecutionProperties properties; private final ObjectProvider<SimpleAsyncTaskExecutorCustomizer> taskExecutorCustomizers; private final ObjectProvider<TaskDecorator> taskDecorator; SimpleAsyncTaskExecutorBuilderConfiguration(TaskExecutionProperties properties, ObjectProvider<SimpleAsyncTaskExecutorCustomizer> taskExecutorCustomizers, ObjectProvider<TaskDecorator> taskDecorator) { this.properties = properties; this.taskExecutorCustomizers = taskExecutorCustomizers; this.taskDecorator = taskDecorator; } @Bean @ConditionalOnMissingBean @ConditionalOnThreading(Threading.PLATFORM) SimpleAsyncTaskExecutorBuilder simpleAsyncTaskExecutorBuilder() { return builder(); } @Bean(name = "simpleAsyncTaskExecutorBuilder") @ConditionalOnMissingBean @ConditionalOnThreading(Threading.VIRTUAL) SimpleAsyncTaskExecutorBuilder simpleAsyncTaskExecutorBuilderVirtualThreads() { return builder().virtualThreads(true); } private SimpleAsyncTaskExecutorBuilder builder() { SimpleAsyncTaskExecutorBuilder builder = new SimpleAsyncTaskExecutorBuilder(); builder = builder.threadNamePrefix(this.properties.getThreadNamePrefix()); builder = builder.customizers(this.taskExecutorCustomizers.orderedStream()::iterator); builder = builder.taskDecorator(getTaskDecorator(this.taskDecorator)); TaskExecutionProperties.Simple simple = this.properties.getSimple(); builder = builder.cancelRemainingTasksOnClose(simple.isCancelRemainingTasksOnClose()); builder = builder.rejectTasksWhenLimitReached(simple.isRejectTasksWhenLimitReached()); builder = builder.concurrencyLimit(simple.getConcurrencyLimit()); TaskExecutionProperties.Shutdown shutdown = this.properties.getShutdown(); if (shutdown.isAwaitTermination()) { builder = builder.taskTerminationTimeout(shutdown.getAwaitTerminationPeriod()); } return builder; } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(AsyncConfigurer.class) static
SimpleAsyncTaskExecutorBuilderConfiguration
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/RecipientListErrorHandlingIssueTest.java
{ "start": 1039, "end": 3586 }
class ____ extends ContextTestSupport { @Override public boolean isUseRouteBuilder() { return false; } @Test public void testUsingInterceptor() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { onException(Exception.class).handled(true).to("mock:error"); interceptSendToEndpoint("direct:*").process(new Processor() { public void process(Exchange exchange) { String target = exchange.getProperty(Exchange.INTERCEPTED_ENDPOINT, String.class); exchange.getIn().setHeader("target", target); } }); from("direct:start").recipientList(header("foo")); from("direct:foo").setBody(constant("Bye World")).to("mock:foo"); from("direct:kaboom").throwException(new IllegalArgumentException("Damn")); } }); context.start(); getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:error").expectedMessageCount(1); getMockEndpoint("mock:error").message(0).header("target").isEqualTo("direct://kaboom"); String foo = "direct:foo,direct:kaboom"; template.sendBodyAndHeader("direct:start", "Hello World", "foo", foo); assertMockEndpointsSatisfied(); } @Test public void testUsingExistingHeaders() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { onException(Exception.class).handled(true).to("mock:error"); from("direct:start").recipientList(header("foo")); from("direct:foo").setBody(constant("Bye World")).to("mock:foo"); from("direct:kaboom").throwException(new IllegalArgumentException("Damn")); } }); context.start(); getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:foo").message(0).exchangeProperty(Exchange.TO_ENDPOINT).isEqualTo("mock://foo"); getMockEndpoint("mock:error").expectedMessageCount(1); getMockEndpoint("mock:error").message(0).exchangeProperty(Exchange.FAILURE_ENDPOINT).isEqualTo("direct://kaboom"); String foo = "direct:foo,direct:kaboom"; template.sendBodyAndHeader("direct:start", "Hello World", "foo", foo); assertMockEndpointsSatisfied(); } }
RecipientListErrorHandlingIssueTest
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/window/utils/WindowJoinHelper.java
{ "start": 8248, "end": 8421 }
interface ____ { void doJoin( @Nullable Iterable<RowData> leftRecords, @Nullable Iterable<RowData> rightRecords); } private
WindowJoinProcessor
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/array/OracleArrayLengthFunction.java
{ "start": 724, "end": 1832 }
class ____ extends AbstractSqmSelfRenderingFunctionDescriptor { public OracleArrayLengthFunction(TypeConfiguration typeConfiguration) { super( "array_length", StandardArgumentsValidators.composite( StandardArgumentsValidators.exactly( 1 ), ArrayArgumentValidator.DEFAULT_INSTANCE ), StandardFunctionReturnTypeResolvers.invariant( typeConfiguration.standardBasicTypeForJavaType( Integer.class ) ), null ); } @Override public void render( SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, ReturnableType<?> returnType, SqlAstTranslator<?> walker) { final Expression arrayExpression = (Expression) sqlAstArguments.get( 0 ); final String arrayTypeName = DdlTypeHelper.getTypeName( arrayExpression.getExpressionType(), walker.getSessionFactory().getTypeConfiguration() ); sqlAppender.appendSql( arrayTypeName ); sqlAppender.append( "_length(" ); arrayExpression.accept( walker ); sqlAppender.append( ')' ); } @Override public String getArgumentListSignature() { return "(ARRAY array)"; } }
OracleArrayLengthFunction
java
apache__rocketmq
proxy/src/main/java/org/apache/rocketmq/proxy/service/route/AddressableMessageQueue.java
{ "start": 985, "end": 2529 }
class ____ implements Comparable<AddressableMessageQueue> { private final MessageQueue messageQueue; private final String brokerAddr; public AddressableMessageQueue(MessageQueue messageQueue, String brokerAddr) { this.messageQueue = messageQueue; this.brokerAddr = brokerAddr; } @Override public int compareTo(AddressableMessageQueue o) { return messageQueue.compareTo(o.messageQueue); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AddressableMessageQueue)) { return false; } AddressableMessageQueue queue = (AddressableMessageQueue) o; return Objects.equals(messageQueue, queue.messageQueue); } @Override public int hashCode() { return messageQueue == null ? 1 : messageQueue.hashCode(); } public int getQueueId() { return this.messageQueue.getQueueId(); } public String getBrokerName() { return this.messageQueue.getBrokerName(); } public String getTopic() { return messageQueue.getTopic(); } public MessageQueue getMessageQueue() { return messageQueue; } public String getBrokerAddr() { return brokerAddr; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("messageQueue", messageQueue) .add("brokerAddr", brokerAddr) .toString(); } }
AddressableMessageQueue
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireContextTests.java
{ "start": 29735, "end": 29901 }
class ____ { @Autowired @TestQualifier private Person person; public Person getPerson() { return this.person; } } private static
QualifiedFieldTestBean
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/struct/FormatFeatureAcceptSingleTest.java
{ "start": 2922, "end": 3075 }
class ____ { @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) public EnumSet<ABC> values; } static
EnumSetWrapper
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/message/LocalizedMessageFactory.java
{ "start": 1338, "end": 3811 }
class ____ extends AbstractMessageFactory { private static final long serialVersionUID = -1996295808703146741L; @Nullable // FIXME: cannot use ResourceBundle name for serialization until Java 8 private final transient ResourceBundle resourceBundle; @Nullable private final String baseName; public LocalizedMessageFactory(final ResourceBundle resourceBundle) { this.resourceBundle = resourceBundle; this.baseName = null; } public LocalizedMessageFactory(final String baseName) { this.resourceBundle = null; this.baseName = baseName; } /** * Gets the resource bundle base name if set. * * @return the resource bundle base name if set. May be null. */ public String getBaseName() { return this.baseName; } /** * Gets the resource bundle if set. * * @return the resource bundle if set. May be null. */ public ResourceBundle getResourceBundle() { return this.resourceBundle; } /** * @since 2.8 */ @Override public Message newMessage(final String key) { if (resourceBundle == null) { return new LocalizedMessage(baseName, key); } return new LocalizedMessage(resourceBundle, key); } /** * Creates {@link LocalizedMessage} instances. * * @param key The key String, used as a message if the key is absent. * @param params The parameters for the message at the given key. * @return The LocalizedMessage. * * @see org.apache.logging.log4j.message.MessageFactory#newMessage(String, Object...) */ @Override public Message newMessage(final String key, final Object... params) { if (resourceBundle == null) { return new LocalizedMessage(baseName, key, params); } return new LocalizedMessage(resourceBundle, key, params); } @Override public boolean equals(final Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } final LocalizedMessageFactory that = (LocalizedMessageFactory) object; return Objects.equals(resourceBundle, that.resourceBundle) && Objects.equals(baseName, that.baseName); } @Override public int hashCode() { return Objects.hash(resourceBundle, baseName); } }
LocalizedMessageFactory
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/floatarrays/FloatArrays_assertHasSameSizeAs_with_Array_Test.java
{ "start": 1437, "end": 2470 }
class ____ extends FloatArraysBaseTest { @Test void should_fail_if_actual_is_null() { // GIVEN actual = null; // WHEN ThrowingCallable code = () -> arrays.assertHasSameSizeAs(someInfo(), actual, array("Solo", "Leia", "Luke")); // THEN assertThatAssertionErrorIsThrownBy(code).withMessage(actualIsNull()); } @Test void should_fail_if_size_of_actual_is_not_equal_to_expected_size() { // GIVEN AssertionInfo info = someInfo(); String[] other = array("Solo", "Leia", "Yoda", "Luke"); // WHEN ThrowingCallable code = () -> arrays.assertHasSameSizeAs(info, actual, other); // THEN String error = shouldHaveSameSizeAs(actual, other, actual.length, other.length).create(null, info.representation()); assertThatAssertionErrorIsThrownBy(code).withMessage(error); } @Test void should_pass_if_size_of_actual_is_equal_to_expected_size() { arrays.assertHasSameSizeAs(someInfo(), actual, array("Solo", "Leia", "Luke")); } }
FloatArrays_assertHasSameSizeAs_with_Array_Test
java
netty__netty
codec-compression/src/main/java/io/netty/handler/codec/compression/BrotliDecoder.java
{ "start": 1178, "end": 5469 }
enum ____ { DONE, NEEDS_MORE_INPUT, ERROR } static { try { Brotli.ensureAvailability(); } catch (Throwable throwable) { throw new ExceptionInInitializerError(throwable); } } private final int inputBufferSize; private DecoderJNI.Wrapper decoder; private boolean destroyed; private boolean needsRead; /** * Creates a new BrotliDecoder with a default 8kB input buffer */ public BrotliDecoder() { this(8 * 1024); } /** * Creates a new BrotliDecoder * @param inputBufferSize desired size of the input buffer in bytes */ public BrotliDecoder(int inputBufferSize) { this.inputBufferSize = ObjectUtil.checkPositive(inputBufferSize, "inputBufferSize"); } private void forwardOutput(ChannelHandlerContext ctx) { ByteBuffer nativeBuffer = decoder.pull(); // nativeBuffer actually wraps brotli's internal buffer so we need to copy its content ByteBuf copy = ctx.alloc().buffer(nativeBuffer.remaining()); copy.writeBytes(nativeBuffer); needsRead = false; ctx.fireChannelRead(copy); } private State decompress(ChannelHandlerContext ctx, ByteBuf input) { for (;;) { switch (decoder.getStatus()) { case DONE: return State.DONE; case OK: decoder.push(0); break; case NEEDS_MORE_INPUT: if (decoder.hasOutput()) { forwardOutput(ctx); } if (!input.isReadable()) { return State.NEEDS_MORE_INPUT; } ByteBuffer decoderInputBuffer = decoder.getInputBuffer(); decoderInputBuffer.clear(); int readBytes = readBytes(input, decoderInputBuffer); decoder.push(readBytes); break; case NEEDS_MORE_OUTPUT: forwardOutput(ctx); break; default: return State.ERROR; } } } private static int readBytes(ByteBuf in, ByteBuffer dest) { int limit = Math.min(in.readableBytes(), dest.remaining()); ByteBuffer slice = dest.slice(); slice.limit(limit); in.readBytes(slice); dest.position(dest.position() + limit); return limit; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { decoder = new DecoderJNI.Wrapper(inputBufferSize); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { needsRead = true; if (destroyed) { // Skip data received after finished. in.skipBytes(in.readableBytes()); return; } if (!in.isReadable()) { return; } try { State state = decompress(ctx, in); if (state == State.DONE) { destroy(); } else if (state == State.ERROR) { throw new DecompressionException("Brotli stream corrupted"); } } catch (Exception e) { destroy(); throw e; } } private void destroy() { if (!destroyed) { destroyed = true; decoder.destroy(); } } @Override protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception { try { destroy(); } finally { super.handlerRemoved0(ctx); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { try { destroy(); } finally { super.channelInactive(ctx); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // Discard bytes of the cumulation buffer if needed. discardSomeReadBytes(); if (needsRead && !ctx.channel().config().isAutoRead()) { ctx.read(); } ctx.fireChannelReadComplete(); } }
State
java
dropwizard__dropwizard
dropwizard-lifecycle/src/main/java/io/dropwizard/lifecycle/JettyManaged.java
{ "start": 234, "end": 903 }
class ____ extends AbstractLifeCycle implements Managed { private final Managed managed; /** * Creates a new JettyManaged wrapping {@code managed}. * * @param managed a {@link Managed} instance to be wrapped */ public JettyManaged(Managed managed) { this.managed = managed; } public Managed getManaged() { return managed; } @Override protected void doStart() throws Exception { managed.start(); } @Override protected void doStop() throws Exception { managed.stop(); } @Override public String toString() { return managed.toString(); } }
JettyManaged
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/TargetColumnAdapter.java
{ "start": 176, "end": 712 }
interface ____ { void setName(String value); void setTable(String value); void setNullable(Boolean value); void setUnique(Boolean value); void setColumnDefinition(String value); void setLength(Integer value); void setPrecision(Integer value); void setScale(Integer value); void setDefault(String value); void setCheck(String value); void setComment(String value); void setRead(String value); void setWrite(String value); void setInsertable(Boolean value); void setUpdatable(Boolean value); }
TargetColumnAdapter
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/heap/HeapPriorityQueueSetTest.java
{ "start": 894, "end": 1433 }
class ____ extends HeapPriorityQueueTest { @Override protected HeapPriorityQueueSet<TestElement> newPriorityQueue(int initialCapacity) { return new HeapPriorityQueueSet<>( TEST_ELEMENT_PRIORITY_COMPARATOR, KEY_EXTRACTOR_FUNCTION, initialCapacity, KEY_GROUP_RANGE, KEY_GROUP_RANGE.getNumberOfKeyGroups()); } @Override protected boolean testSetSemanticsAgainstDuplicateElements() { return true; } }
HeapPriorityQueueSetTest
java
google__truth
extensions/proto/src/test/java/com/google/common/truth/extensions/proto/ProtoSubjectTestBase.java
{ "start": 2197, "end": 10331 }
enum ____ { IMMUTABLE_PROTO2(TestMessage2.getDefaultInstance()), PROTO3(TestMessage3.getDefaultInstance()); private final Message defaultInstance; TestType(Message defaultInstance) { this.defaultInstance = defaultInstance; } public Message defaultInstance() { return defaultInstance; } public boolean isProto3() { return this == PROTO3; } } private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder() .add(TestMessage3.getDescriptor()) .add(TestMessage2.getDescriptor()) .build(); private static final TextFormat.Parser PARSER = TextFormat.Parser.newBuilder() .setSingularOverwritePolicy( TextFormat.Parser.SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES) .setTypeRegistry(typeRegistry) .build(); private static final ExtensionRegistry extensionRegistry = getEmptyRegistry(); // For Parameterized testing. protected static Collection<Object[]> parameters() { ImmutableList.Builder<Object[]> builder = ImmutableList.builder(); for (TestType testType : TestType.values()) { builder.add(new Object[] {testType}); } return builder.build(); } @Rule public final Expect expect = Expect.create(); // Hackhackhack: 'ExpectFailure' does not support more than one call per test, but we have many // tests which require it. So, we create an arbitrary number of these rules, and dole them out // in order on demand. // TODO(user): See if 'expectFailure.enterRuleContext()' could be made public, or a '.reset()' // function could be added to mitigate the need for this. Alternatively, if & when Truth moves // to Java 8, we can use the static API with lambdas instead. @Rule public final MultiExpectFailure multiExpectFailure = new MultiExpectFailure(/* size= */ 20); private final Message defaultInstance; private final boolean isProto3; protected ProtoSubjectTestBase(TestType testType) { this.defaultInstance = testType.defaultInstance(); this.isProto3 = testType.isProto3(); } protected final Message fromUnknownFields(UnknownFieldSet unknownFieldSet) throws InvalidProtocolBufferException { return defaultInstance.getParserForType().parseFrom(unknownFieldSet.toByteArray()); } protected final String fullMessageName() { return defaultInstance.getDescriptorForType().getFullName(); } protected final FieldDescriptor getFieldDescriptor(String fieldName) { FieldDescriptor fieldDescriptor = defaultInstance.getDescriptorForType().findFieldByName(fieldName); checkArgument(fieldDescriptor != null, "No field named %s.", fieldName); return fieldDescriptor; } protected final int getFieldNumber(String fieldName) { return getFieldDescriptor(fieldName).getNumber(); } protected final TypeRegistry getTypeRegistry() { return typeRegistry; } protected final ExtensionRegistry getExtensionRegistry() { return extensionRegistry; } protected final Message clone(Message in) { return in.toBuilder().build(); } protected Message parse(String textProto) { try { Message.Builder builder = defaultInstance.toBuilder(); PARSER.merge(textProto, builder); return builder.build(); } catch (ParseException e) { throw new RuntimeException(e); } } protected final Message parsePartial(String textProto) { try { Message.Builder builder = defaultInstance.toBuilder(); PARSER.merge(textProto, builder); return builder.buildPartial(); } catch (ParseException e) { throw new RuntimeException(e); } } protected final boolean isProto3() { return isProto3; } /** * Some tests don't vary across the different proto types, and should only be run once. * * <p>This method returns true for exactly one {@link TestType}, and false for all the others, and * so can be used to ensure tests are only run once. */ protected final boolean testIsRunOnce() { return isProto3; } protected final ProtoSubjectBuilder expectFailureWhenTesting() { return multiExpectFailure.whenTesting().about(ProtoTruth.protos()); } protected final TruthFailureSubject expectThatFailure() { return expect.about(truthFailures()).that(multiExpectFailure.getFailure()); } protected final ProtoSubject expectThat(@Nullable Message message) { return expect.about(ProtoTruth.protos()).that(message); } protected final <M extends Message> IterableOfProtosSubject<M> expectThat(Iterable<M> messages) { return expect.about(ProtoTruth.protos()).that(messages); } protected final <M extends Message> MapWithProtoValuesSubject<M> expectThat(Map<?, M> map) { return expect.about(ProtoTruth.protos()).that(map); } protected final <M extends Message> MultimapWithProtoValuesSubject<M> expectThat( Multimap<?, M> multimap) { return expect.about(ProtoTruth.protos()).that(multimap); } protected final ProtoSubject expectThatWithMessage(String msg, @Nullable Message message) { return expect.withMessage(msg).about(ProtoTruth.protos()).that(message); } protected final void expectIsEqualToFailed() { expectFailureMatches( "Not true that messages compare equal\\.\\s*" + "(Differences were found:\\n.*|No differences were reported\\..*)"); } protected final void expectIsNotEqualToFailed() { expectFailureMatches( "Not true that messages compare not equal\\.\\s*" + "(Only ignorable differences were found:\\n.*|" + "No differences were found\\..*)"); } /** * Expects the current {@link ExpectFailure} failure message to match the provided regex, using * {@code Pattern.DOTALL} to match newlines. */ protected final void expectFailureMatches(String regex) { expectThatFailure().hasMessageThat().matches(Pattern.compile(regex, Pattern.DOTALL)); } /** * Expects the current {@link ExpectFailure} failure message to NOT match the provided regex, * using {@code Pattern.DOTALL} to match newlines. */ protected final void expectNoRegex(Throwable t, String regex) { expectThatFailure().hasMessageThat().doesNotMatch(Pattern.compile(regex, Pattern.DOTALL)); } protected static final <T> ImmutableList<T> listOf(T... elements) { return ImmutableList.copyOf(elements); } protected static final <T> T[] arrayOf(T... elements) { return elements; } @SuppressWarnings("unchecked") protected static final <K, V> ImmutableMap<K, V> mapOf(K k0, V v0, Object... rest) { Preconditions.checkArgument(rest.length % 2 == 0, "Uneven args: %s", rest.length); ImmutableMap.Builder<K, V> builder = new ImmutableMap.Builder<>(); builder.put(k0, v0); for (int i = 0; i < rest.length; i += 2) { builder.put((K) rest[i], (V) rest[i + 1]); } return builder.buildOrThrow(); } @SuppressWarnings("unchecked") protected static final <K, V> ImmutableMultimap<K, V> multimapOf(K k0, V v0, Object... rest) { Preconditions.checkArgument(rest.length % 2 == 0, "Uneven args: %s", rest.length); ImmutableMultimap.Builder<K, V> builder = new ImmutableMultimap.Builder<>(); builder.put(k0, v0); for (int i = 0; i < rest.length; i += 2) { builder.put((K) rest[i], (V) rest[i + 1]); } return builder.build(); } final void checkMethodNamesEndWithForValues( Class<?> clazz, Class<? extends Subject> pseudoSuperclass) { // Don't run this test twice. if (!testIsRunOnce()) { return; } Set<String> diff = Sets.difference(getMethodNames(clazz), getMethodNames(pseudoSuperclass)); assertWithMessage("Found no methods to test. Bug in test?").that(diff).isNotEmpty(); for (String methodName : diff) { assertThat(methodName).endsWith("ForValues"); } } private static ImmutableSet<String> getMethodNames(Class<?> clazz) { ImmutableSet.Builder<String> names = ImmutableSet.builder(); for (Method method : clazz.getMethods()) { names.add(method.getName()); } return names.build(); } }
TestType
java
apache__camel
components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/SpringAiChatPromptTemplateIT.java
{ "start": 1305, "end": 3425 }
class ____ extends OllamaTestSupport { @Test public void testPromptTemplateWithVariables() { String template = "What is the capital of {country}? Answer in one word."; Map<String, Object> variables = new HashMap<>(); variables.put("country", "France"); var exchange = template().request("direct:prompt", e -> { e.getIn().setBody(variables); e.getIn().setHeader(SpringAiChatConstants.PROMPT_TEMPLATE, template); }); String response = exchange.getMessage().getBody(String.class); assertThat(response).isNotNull(); assertThat(response).isNotEmpty(); assertThat(response.toLowerCase()).contains("paris"); } @Test public void testPromptTemplateWithMultipleVariables() { String template = "Write a {length} sentence about {subject} in {language}."; Map<String, Object> variables = new HashMap<>(); variables.put("length", "short"); variables.put("subject", "technology"); variables.put("language", "English"); var exchange = template().request("direct:prompt", e -> { e.getIn().setBody(variables); e.getIn().setHeader(SpringAiChatConstants.PROMPT_TEMPLATE, template); }); String response = exchange.getMessage().getBody(String.class); assertThat(response).isNotNull(); assertThat(response).isNotEmpty(); // Verify token usage is tracked Integer totalTokens = exchange.getMessage().getHeader(SpringAiChatConstants.TOTAL_TOKEN_COUNT, Integer.class); assertThat(totalTokens).isNotNull().isGreaterThan(0); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { bindChatModel(this.getCamelContext()); from("direct:prompt") .to("spring-ai-chat:prompt?chatModel=#chatModel&chatOperation=CHAT_SINGLE_MESSAGE_WITH_PROMPT"); } }; } }
SpringAiChatPromptTemplateIT
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/throttle/SpringThrottlerThreadPoolProfileTest.java
{ "start": 1069, "end": 1378 }
class ____ extends ThrottlerThreadPoolProfileTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/ThrottlerThreadPoolProfileTest.xml"); } }
SpringThrottlerThreadPoolProfileTest
java
google__dagger
javatests/dagger/internal/codegen/ComponentCreatorTest.java
{ "start": 29809, "end": 30131 }
interface ____ {", " SimpleComponent build();", " void abstractModule(AbstractModule abstractModule);", " void other(String s);", " }") .addLinesIf( FACTORY, " @Component.Factory", "
Builder
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/processor/ReplyMessageProcessor.java
{ "start": 2970, "end": 18327 }
class ____ extends AbstractSendMessageProcessor { private static final Logger log = LoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME); public ReplyMessageProcessor(final BrokerController brokerController) { super(brokerController); } @Override public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { SendMessageContext mqtraceContext = null; SendMessageRequestHeader requestHeader = parseRequestHeader(request); if (requestHeader == null) { return null; } mqtraceContext = buildMsgContext(ctx, requestHeader, request); this.executeSendMessageHookBefore(mqtraceContext); RemotingCommand response = this.processReplyMessageRequest(ctx, request, mqtraceContext, requestHeader); this.executeSendMessageHookAfter(response, mqtraceContext); return response; } @Override protected SendMessageRequestHeader parseRequestHeader(RemotingCommand request) throws RemotingCommandException { SendMessageRequestHeaderV2 requestHeaderV2 = null; SendMessageRequestHeader requestHeader = null; switch (request.getCode()) { case RequestCode.SEND_REPLY_MESSAGE_V2: requestHeaderV2 = (SendMessageRequestHeaderV2) request .decodeCommandCustomHeader(SendMessageRequestHeaderV2.class); case RequestCode.SEND_REPLY_MESSAGE: if (null == requestHeaderV2) { requestHeader = (SendMessageRequestHeader) request .decodeCommandCustomHeader(SendMessageRequestHeader.class); } else { requestHeader = SendMessageRequestHeaderV2.createSendMessageRequestHeaderV1(requestHeaderV2); } default: break; } return requestHeader; } private RemotingCommand processReplyMessageRequest(final ChannelHandlerContext ctx, final RemotingCommand request, final SendMessageContext sendMessageContext, final SendMessageRequestHeader requestHeader) { final RemotingCommand response = RemotingCommand.createResponseCommand(SendMessageResponseHeader.class); final SendMessageResponseHeader responseHeader = (SendMessageResponseHeader) response.readCustomHeader(); response.setOpaque(request.getOpaque()); response.addExtField(MessageConst.PROPERTY_MSG_REGION, this.brokerController.getBrokerConfig().getRegionId()); response.addExtField(MessageConst.PROPERTY_TRACE_SWITCH, String.valueOf(this.brokerController.getBrokerConfig().isTraceOn())); log.debug("receive SendReplyMessage request command, {}", request); final long startTimestamp = this.brokerController.getBrokerConfig().getStartAcceptSendRequestTimeStamp(); if (this.brokerController.getMessageStore().now() < startTimestamp) { response.setCode(ResponseCode.SYSTEM_ERROR); response.setRemark(String.format("broker unable to service, until %s", UtilAll.timeMillisToHumanString2(startTimestamp))); return response; } response.setCode(-1); super.msgCheck(ctx, requestHeader, request, response); if (response.getCode() != -1) { return response; } final byte[] body = request.getBody(); int queueIdInt = requestHeader.getQueueId(); TopicConfig topicConfig = this.brokerController.getTopicConfigManager().selectTopicConfig(requestHeader.getTopic()); if (queueIdInt < 0) { queueIdInt = ThreadLocalRandom.current().nextInt(99999999) % topicConfig.getWriteQueueNums(); } MessageExtBrokerInner msgInner = new MessageExtBrokerInner(); msgInner.setTopic(requestHeader.getTopic()); msgInner.setQueueId(queueIdInt); msgInner.setBody(body); msgInner.setFlag(requestHeader.getFlag()); MessageAccessor.setProperties(msgInner, MessageDecoder.string2messageProperties(requestHeader.getProperties())); msgInner.setPropertiesString(requestHeader.getProperties()); msgInner.setBornTimestamp(requestHeader.getBornTimestamp()); msgInner.setBornHost(ctx.channel().remoteAddress()); msgInner.setStoreHost(this.getStoreHost()); msgInner.setReconsumeTimes(requestHeader.getReconsumeTimes() == null ? 0 : requestHeader.getReconsumeTimes()); PushReplyResult pushReplyResult = this.pushReplyMessage(ctx, requestHeader, msgInner); this.handlePushReplyResult(pushReplyResult, response, responseHeader, queueIdInt); if (this.brokerController.getBrokerConfig().isStoreReplyMessageEnable()) { PutMessageResult putMessageResult = this.brokerController.getMessageStore().putMessage(msgInner); this.handlePutMessageResult(putMessageResult, request, msgInner, responseHeader, sendMessageContext, queueIdInt, BrokerMetricsManager.getMessageType(requestHeader)); } return response; } private PushReplyResult pushReplyMessage(final ChannelHandlerContext ctx, final SendMessageRequestHeader requestHeader, final Message msg) { ReplyMessageRequestHeader replyMessageRequestHeader = new ReplyMessageRequestHeader(); InetSocketAddress bornAddress = (InetSocketAddress)(ctx.channel().remoteAddress()); replyMessageRequestHeader.setBornHost(bornAddress.getAddress().getHostAddress() + ":" + bornAddress.getPort()); InetSocketAddress storeAddress = (InetSocketAddress)(this.getStoreHost()); replyMessageRequestHeader.setStoreHost(storeAddress.getAddress().getHostAddress() + ":" + storeAddress.getPort()); replyMessageRequestHeader.setStoreTimestamp(System.currentTimeMillis()); replyMessageRequestHeader.setProducerGroup(requestHeader.getProducerGroup()); replyMessageRequestHeader.setTopic(requestHeader.getTopic()); replyMessageRequestHeader.setDefaultTopic(requestHeader.getDefaultTopic()); replyMessageRequestHeader.setDefaultTopicQueueNums(requestHeader.getDefaultTopicQueueNums()); replyMessageRequestHeader.setQueueId(requestHeader.getQueueId()); replyMessageRequestHeader.setSysFlag(requestHeader.getSysFlag()); replyMessageRequestHeader.setBornTimestamp(requestHeader.getBornTimestamp()); replyMessageRequestHeader.setFlag(requestHeader.getFlag()); replyMessageRequestHeader.setProperties(requestHeader.getProperties()); replyMessageRequestHeader.setReconsumeTimes(requestHeader.getReconsumeTimes()); replyMessageRequestHeader.setUnitMode(requestHeader.isUnitMode()); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.PUSH_REPLY_MESSAGE_TO_CLIENT, replyMessageRequestHeader); request.setBody(msg.getBody()); String senderId = msg.getProperties().get(MessageConst.PROPERTY_MESSAGE_REPLY_TO_CLIENT); PushReplyResult pushReplyResult = new PushReplyResult(false); if (senderId != null) { Channel channel = this.brokerController.getProducerManager().findChannel(senderId); if (channel != null) { msg.getProperties().put(MessageConst.PROPERTY_PUSH_REPLY_TIME, String.valueOf(System.currentTimeMillis())); replyMessageRequestHeader.setProperties(MessageDecoder.messageProperties2String(msg.getProperties())); try { RemotingCommand pushResponse = this.brokerController.getBroker2Client().callClient(channel, request); assert pushResponse != null; switch (pushResponse.getCode()) { case ResponseCode.SUCCESS: { pushReplyResult.setPushOk(true); break; } default: { pushReplyResult.setPushOk(false); pushReplyResult.setRemark("push reply message to " + senderId + "fail."); log.warn("push reply message to <{}> return fail, response remark: {}", senderId, pushResponse.getRemark()); } } } catch (RemotingException | InterruptedException e) { pushReplyResult.setPushOk(false); pushReplyResult.setRemark("push reply message to " + senderId + "fail."); log.warn("push reply message to <{}> fail. {}", senderId, channel, e); } } else { pushReplyResult.setPushOk(false); pushReplyResult.setRemark("push reply message fail, channel of <" + senderId + "> not found."); log.warn(pushReplyResult.getRemark()); } } else { log.warn(MessageConst.PROPERTY_MESSAGE_REPLY_TO_CLIENT + " is null, can not reply message"); pushReplyResult.setPushOk(false); pushReplyResult.setRemark("reply message properties[" + MessageConst.PROPERTY_MESSAGE_REPLY_TO_CLIENT + "] is null"); } return pushReplyResult; } private void handlePushReplyResult(PushReplyResult pushReplyResult, final RemotingCommand response, final SendMessageResponseHeader responseHeader, int queueIdInt) { if (!pushReplyResult.isPushOk()) { response.setCode(ResponseCode.SYSTEM_ERROR); response.setRemark(pushReplyResult.getRemark()); } else { response.setCode(ResponseCode.SUCCESS); response.setRemark(null); //set to zero to avoid client decoding exception responseHeader.setMsgId("0"); responseHeader.setQueueId(queueIdInt); responseHeader.setQueueOffset(0L); } } private void handlePutMessageResult(PutMessageResult putMessageResult, final RemotingCommand request, final MessageExt msg, final SendMessageResponseHeader responseHeader, SendMessageContext sendMessageContext, int queueIdInt, TopicMessageType messageType) { if (putMessageResult == null) { log.warn("process reply message, store putMessage return null"); return; } boolean putOk = false; switch (putMessageResult.getPutMessageStatus()) { // Success case PUT_OK: case FLUSH_DISK_TIMEOUT: case FLUSH_SLAVE_TIMEOUT: case SLAVE_NOT_AVAILABLE: putOk = true; break; // Failed case CREATE_MAPPED_FILE_FAILED: log.warn("create mapped file failed, server is busy or broken."); break; case MESSAGE_ILLEGAL: log.warn( "the message is illegal, maybe msg body or properties length not matched. msg body length limit {}B.", this.brokerController.getMessageStoreConfig().getMaxMessageSize()); break; case PROPERTIES_SIZE_EXCEEDED: log.warn( "the message is illegal, maybe msg properties length limit 32KB."); break; case SERVICE_NOT_AVAILABLE: log.warn( "service not available now. It may be caused by one of the following reasons: " + "the broker's disk is full, messages are put to the slave, message store has been shut down, etc."); break; case OS_PAGE_CACHE_BUSY: log.warn("[PC_SYNCHRONIZED]broker busy, start flow control for a while"); break; case UNKNOWN_ERROR: log.warn("UNKNOWN_ERROR"); break; default: log.warn("UNKNOWN_ERROR DEFAULT"); break; } String owner = request.getExtFields().get(BrokerStatsManager.COMMERCIAL_OWNER); int commercialSizePerMsg = brokerController.getBrokerConfig().getCommercialSizePerMsg(); if (putOk) { this.brokerController.getBrokerStatsManager().incTopicPutNums(msg.getTopic(), putMessageResult.getAppendMessageResult().getMsgNum(), 1); this.brokerController.getBrokerStatsManager().incTopicPutSize(msg.getTopic(), putMessageResult.getAppendMessageResult().getWroteBytes()); this.brokerController.getBrokerStatsManager().incBrokerPutNums(msg.getTopic(), putMessageResult.getAppendMessageResult().getMsgNum()); if (!BrokerMetricsManager.isRetryOrDlqTopic(msg.getTopic())) { Attributes attributes = this.brokerController.getBrokerMetricsManager().newAttributesBuilder() .put(LABEL_TOPIC, msg.getTopic()) .put(LABEL_MESSAGE_TYPE, messageType.getMetricsValue()) .put(LABEL_IS_SYSTEM, TopicValidator.isSystemTopic(msg.getTopic())) .build(); this.brokerController.getBrokerMetricsManager().getMessagesInTotal().add(putMessageResult.getAppendMessageResult().getMsgNum(), attributes); this.brokerController.getBrokerMetricsManager().getThroughputInTotal().add(putMessageResult.getAppendMessageResult().getWroteBytes(), attributes); this.brokerController.getBrokerMetricsManager().getMessageSize().record(putMessageResult.getAppendMessageResult().getWroteBytes() / putMessageResult.getAppendMessageResult().getMsgNum(), attributes); } responseHeader.setMsgId(putMessageResult.getAppendMessageResult().getMsgId()); responseHeader.setQueueId(queueIdInt); responseHeader.setQueueOffset(putMessageResult.getAppendMessageResult().getLogicsOffset()); if (hasSendMessageHook()) { sendMessageContext.setMsgId(responseHeader.getMsgId()); sendMessageContext.setQueueId(responseHeader.getQueueId()); sendMessageContext.setQueueOffset(responseHeader.getQueueOffset()); int commercialBaseCount = brokerController.getBrokerConfig().getCommercialBaseCount(); int wroteSize = putMessageResult.getAppendMessageResult().getWroteBytes(); int incValue = (int) Math.ceil(wroteSize * 1.0 / commercialSizePerMsg) * commercialBaseCount; sendMessageContext.setCommercialSendStats(BrokerStatsManager.StatsType.SEND_SUCCESS); sendMessageContext.setCommercialSendTimes(incValue); sendMessageContext.setCommercialSendSize(wroteSize); sendMessageContext.setCommercialOwner(owner); } } else { if (hasSendMessageHook()) { int wroteSize = request.getBody().length; int incValue = (int) Math.ceil(wroteSize * 1.0 / commercialSizePerMsg); sendMessageContext.setCommercialSendStats(BrokerStatsManager.StatsType.SEND_FAILURE); sendMessageContext.setCommercialSendTimes(incValue); sendMessageContext.setCommercialSendSize(wroteSize); sendMessageContext.setCommercialOwner(owner); } } }
ReplyMessageProcessor
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/ibmwatsonx/IbmWatsonxServiceTests.java
{ "start": 47731, "end": 48320 }
class ____ extends IbmWatsonxActionCreator { IbmWatsonxActionCreatorWithoutAuth(Sender sender, ServiceComponents serviceComponents) { super(sender, serviceComponents); } @Override protected IbmWatsonxEmbeddingsRequestManager getEmbeddingsRequestManager( IbmWatsonxEmbeddingsModel model, Truncator truncator, ThreadPool threadPool ) { return new IbmWatsonxEmbeddingsRequestManagerWithoutAuth(model, truncator, threadPool); } } private static
IbmWatsonxActionCreatorWithoutAuth
java
quarkusio__quarkus
independent-projects/qute/debug/src/test/java/io/quarkus/qute/debug/client/TracingMessageConsumer.java
{ "start": 1713, "end": 9841 }
class ____ { private final Map<String, RequestMetadata> sentRequests; private final Map<String, RequestMetadata> receivedRequests; private final Clock clock; private final DateTimeFormatter dateTimeFormatter; public TracingMessageConsumer() { this.sentRequests = new ConcurrentHashMap<>(); this.receivedRequests = new ConcurrentHashMap<>(); this.clock = Clock.systemDefaultZone(); this.dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(clock.getZone()); } /** * Constructs a log string for a given {@link Message}. The type of the {@link MessageConsumer} * determines if we're sending or receiving a message. The type of the @{link Message} determines * if it is a request, response, or notification. */ public String log(Message message, MessageConsumer messageConsumer, ServerTrace serverTrace) throws MessageIssueException, JsonRpcException { final Instant now = clock.instant(); final String date = dateTimeFormatter.format(now); if (messageConsumer instanceof StreamMessageConsumer) { return consumeMessageSending(message, now, date, serverTrace); } else if (messageConsumer instanceof RemoteEndpoint) { return consumeMessageReceiving(message, now, date, serverTrace); } else { return String.format("Unknown MessageConsumer type: %s", messageConsumer); } } private String consumeMessageSending(Message message, Instant now, String date, ServerTrace serverTrace) { if (message instanceof RequestMessage) { RequestMessage requestMessage = (RequestMessage) message; String id = requestMessage.getId(); String method = requestMessage.getMethod(); RequestMetadata requestMetadata = new RequestMetadata(method, now); sentRequests.put(id, requestMetadata); if (serverTrace == ServerTrace.messages) { String format = "[Trace - %s] Sending request '%s - (%s)'.\n"; return String.format(format, date, method, id); } Object params = requestMessage.getParams(); String paramsJson = MessageJsonHandler.toString(params); String format = "[Trace - %s] Sending request '%s - (%s)'.\nParams: %s\n\n\n"; return String.format(format, date, method, id, paramsJson); } else if (message instanceof ResponseMessage) { ResponseMessage responseMessage = (ResponseMessage) message; String id = responseMessage.getId(); RequestMetadata requestMetadata = receivedRequests.remove(id); String method = getMethod(requestMetadata); String latencyMillis = getLatencyMillis(requestMetadata, now); if (serverTrace == ServerTrace.messages) { String format = "[Trace - %s] Sending response '%s - (%s)'. Processing request took %sms\n"; return String.format(format, date, method, id, latencyMillis); } Object result = responseMessage.getResult(); String resultJson = MessageJsonHandler.toString(result); String resultTrace = getResultTrace(resultJson, null); String format = "[Trace - %s] Sending response '%s - (%s)'. Processing request took %sms\n%s\n\n\n"; return String.format(format, date, method, id, latencyMillis, resultTrace); } else if (message instanceof NotificationMessage) { NotificationMessage notificationMessage = (NotificationMessage) message; String method = notificationMessage.getMethod(); if (serverTrace == ServerTrace.messages) { String format = "[Trace - %s] Sending notification '%s'\n"; return String.format(format, date, method); } Object params = notificationMessage.getParams(); String paramsJson = MessageJsonHandler.toString(params); String format = "[Trace - %s] Sending notification '%s'\nParams: %s\n\n\n"; return String.format(format, date, method, paramsJson); } else { return String.format("Unknown message type: %s", message); } } private String consumeMessageReceiving(Message message, Instant now, String date, ServerTrace serverTrace) { if (message instanceof RequestMessage) { RequestMessage requestMessage = (RequestMessage) message; String method = requestMessage.getMethod(); String id = requestMessage.getId(); RequestMetadata requestMetadata = new RequestMetadata(method, now); receivedRequests.put(id, requestMetadata); if (serverTrace == ServerTrace.messages) { String format = "[Trace - %s] Received request '%s - (%s)'.\n"; return String.format(format, date, method, id); } Object params = requestMessage.getParams(); String paramsJson = MessageJsonHandler.toString(params); String format = "[Trace - %s] Received request '%s - (%s)'\nParams: %s\n\n\n"; return String.format(format, date, method, id, paramsJson); } else if (message instanceof ResponseMessage) { ResponseMessage responseMessage = (ResponseMessage) message; String id = responseMessage.getId(); RequestMetadata requestMetadata = sentRequests.remove(id); String method = getMethod(requestMetadata); String latencyMillis = getLatencyMillis(requestMetadata, now); if (serverTrace == ServerTrace.messages) { String format = "[Trace - %s] Received response '%s - (%s)' in %sms.\n"; return String.format(format, date, method, id, latencyMillis); } Object result = responseMessage.getResult(); String resultJson = MessageJsonHandler.toString(result); Object error = responseMessage.getError(); String errorJson = MessageJsonHandler.toString(error); String resultTrace = getResultTrace(resultJson, errorJson); String format = "[Trace - %s] Received response '%s - (%s)' in %sms.\n%s\n\n\n"; return String.format(format, date, method, id, latencyMillis, resultTrace); } else if (message instanceof NotificationMessage) { NotificationMessage notificationMessage = (NotificationMessage) message; String method = notificationMessage.getMethod(); if (serverTrace == ServerTrace.messages) { String format = "[Trace - %s] Received notification '%s'\n"; return String.format(format, date, method); } Object params = notificationMessage.getParams(); String paramsJson = MessageJsonHandler.toString(params); String format = "[Trace - %s] Received notification '%s'\nParams: %s\n\n\n"; return String.format(format, date, method, paramsJson); } else { return String.format("Unknown message type: %s", message); } } private static String getResultTrace(String resultJson, String errorJson) { StringBuilder result = new StringBuilder(); if (resultJson != null && !"null".equals(resultJson)) { result.append("Result: "); result.append(resultJson); } else { result.append("No response returned."); } if (errorJson != null && !"null".equals(errorJson)) { result.append("\nError: "); result.append(errorJson); } return result.toString(); } private static String getMethod(RequestMetadata requestMetadata) { return requestMetadata != null ? requestMetadata.method : "<unknown>"; } private static String getLatencyMillis(RequestMetadata requestMetadata, Instant now) { return requestMetadata != null ? String.valueOf(now.toEpochMilli() - requestMetadata.start.toEpochMilli()) : "?"; } /** * Data
TracingMessageConsumer
java
quarkusio__quarkus
integration-tests/maven/src/test/resources-filtered/projects/test-test-conditions/src/test/java/org/acme/AlwaysEnabledCondition.java
{ "start": 264, "end": 583 }
class ____ implements ExecutionCondition { @Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { String os = ConfigProvider.getConfig().getValue("os.name", String.class); return ConditionEvaluationResult.enabled("enabled"); } }
AlwaysEnabledCondition
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByCheckerTest.java
{ "start": 19143, "end": 19298 }
class ____ { final Object lock = new Object(); @GuardedBy("lock") boolean flag = false; }
A
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java
{ "start": 1994, "end": 10645 }
class ____ { private @Nullable ConfigurableApplicationContext context; private final ConfigurableEnvironment environment = new StandardEnvironment(); @AfterEach void tearDown() { if (this.context != null) { this.context.close(); } } @Test void allPropertiesAreDefined() { load(MultiplePropertiesRequiredConfiguration.class, "property1=value1", "property2=value2"); assertThat(containsBean()).isTrue(); } @Test void notAllPropertiesAreDefined() { load(MultiplePropertiesRequiredConfiguration.class, "property1=value1"); assertThat(containsBean()).isFalse(); } @Test void propertyValueEqualsFalse() { load(MultiplePropertiesRequiredConfiguration.class, "property1=false", "property2=value2"); assertThat(containsBean()).isFalse(); } @Test void propertyValueEqualsFALSE() { load(MultiplePropertiesRequiredConfiguration.class, "property1=FALSE", "property2=value2"); assertThat(containsBean()).isFalse(); } @Test void relaxedName() { load(RelaxedPropertiesRequiredConfiguration.class, "spring.theRelaxedProperty=value1"); assertThat(containsBean()).isTrue(); } @Test void prefixWithoutPeriod() { load(RelaxedPropertiesRequiredConfigurationWithShortPrefix.class, "spring.property=value1"); assertThat(containsBean()).isTrue(); } @Test // Enabled by default void enabledIfNotConfiguredOtherwise() { load(EnabledIfNotConfiguredOtherwiseConfig.class); assertThat(containsBean()).isTrue(); } @Test void enabledIfNotConfiguredOtherwiseWithConfig() { load(EnabledIfNotConfiguredOtherwiseConfig.class, "simple.myProperty:false"); assertThat(containsBean()).isFalse(); } @Test void enabledIfNotConfiguredOtherwiseWithConfigDifferentCase() { load(EnabledIfNotConfiguredOtherwiseConfig.class, "simple.my-property:FALSE"); assertThat(containsBean()).isFalse(); } @Test // Disabled by default void disableIfNotConfiguredOtherwise() { load(DisabledIfNotConfiguredOtherwiseConfig.class); assertThat(containsBean()).isFalse(); } @Test void disableIfNotConfiguredOtherwiseWithConfig() { load(DisabledIfNotConfiguredOtherwiseConfig.class, "simple.myProperty:true"); assertThat(containsBean()).isTrue(); } @Test void disableIfNotConfiguredOtherwiseWithConfigDifferentCase() { load(DisabledIfNotConfiguredOtherwiseConfig.class, "simple.myproperty:TrUe"); assertThat(containsBean()).isTrue(); } @Test void simpleValueIsSet() { load(SimpleValueConfig.class, "simple.myProperty:bar"); assertThat(containsBean()).isTrue(); } @Test void caseInsensitive() { load(SimpleValueConfig.class, "simple.myProperty:BaR"); assertThat(containsBean()).isTrue(); } @Test void defaultValueIsSet() { load(DefaultValueConfig.class, "simple.myProperty:bar"); assertThat(containsBean()).isTrue(); } @Test void defaultValueIsNotSet() { load(DefaultValueConfig.class); assertThat(containsBean()).isTrue(); } @Test void defaultValueIsSetDifferentValue() { load(DefaultValueConfig.class, "simple.myProperty:another"); assertThat(containsBean()).isFalse(); } @Test void prefix() { load(PrefixValueConfig.class, "simple.myProperty:bar"); assertThat(containsBean()).isTrue(); } @Test void relaxedEnabledByDefault() { load(PrefixValueConfig.class, "simple.myProperty:bar"); assertThat(containsBean()).isTrue(); } @Test void multiValuesAllSet() { load(MultiValuesConfig.class, "simple.my-property:bar", "simple.my-another-property:bar"); assertThat(containsBean()).isTrue(); } @Test void multiValuesOnlyOneSet() { load(MultiValuesConfig.class, "simple.my-property:bar"); assertThat(containsBean()).isFalse(); } @Test void usingValueAttribute() { load(ValueAttribute.class, "some.property"); assertThat(containsBean()).isTrue(); } private boolean containsBean() { assertThat(this.context).isNotNull(); return this.context.containsBean("foo"); } @Test void nameOrValueMustBeSpecified() { assertThatIllegalStateException().isThrownBy(() -> load(NoNameOrValueAttribute.class, "some.property")) .satisfies( causeMessageContaining("The name or value attribute of @ConditionalOnProperty must be specified")); } @Test void nameAndValueMustNotBeSpecified() { assertThatIllegalStateException().isThrownBy(() -> load(NameAndValueAttribute.class, "some.property")) .satisfies(causeMessageContaining("The name and value attributes of @ConditionalOnProperty are exclusive")); } private <T extends Exception> Consumer<T> causeMessageContaining(String message) { return (ex) -> assertThat(ex.getCause()).hasMessageContaining(message); } @Test void metaAnnotationConditionMatchesWhenPropertyIsSet() { load(MetaAnnotation.class, "my.feature.enabled=true"); assertThat(containsBean()).isTrue(); } @Test void metaAnnotationConditionDoesNotMatchWhenPropertyIsNotSet() { load(MetaAnnotation.class); assertThat(containsBean()).isFalse(); } @Test void metaAndDirectAnnotationConditionDoesNotMatchWhenOnlyDirectPropertyIsSet() { load(MetaAnnotationAndDirectAnnotation.class, "my.other.feature.enabled=true"); assertThat(containsBean()).isFalse(); } @Test void metaAndDirectAnnotationConditionDoesNotMatchWhenOnlyMetaPropertyIsSet() { load(MetaAnnotationAndDirectAnnotation.class, "my.feature.enabled=true"); assertThat(containsBean()).isFalse(); } @Test void metaAndDirectAnnotationConditionDoesNotMatchWhenNeitherPropertyIsSet() { load(MetaAnnotationAndDirectAnnotation.class); assertThat(containsBean()).isFalse(); } @Test void metaAndDirectAnnotationConditionMatchesWhenBothPropertiesAreSet() { load(MetaAnnotationAndDirectAnnotation.class, "my.feature.enabled=true", "my.other.feature.enabled=true"); assertThat(containsBean()).isTrue(); } @Test void metaAnnotationWithAliasConditionMatchesWhenPropertyIsSet() { load(MetaAnnotationWithAlias.class, "my.feature.enabled=true"); assertThat(containsBean()).isTrue(); } @Test void metaAndDirectAnnotationWithAliasConditionDoesNotMatchWhenOnlyMetaPropertyIsSet() { load(MetaAnnotationAndDirectAnnotationWithAlias.class, "my.feature.enabled=true"); assertThat(containsBean()).isFalse(); } @Test void metaAndDirectAnnotationWithAliasConditionDoesNotMatchWhenOnlyDirectPropertyIsSet() { load(MetaAnnotationAndDirectAnnotationWithAlias.class, "my.other.feature.enabled=true"); assertThat(containsBean()).isFalse(); } @Test void metaAndDirectAnnotationWithAliasConditionMatchesWhenBothPropertiesAreSet() { load(MetaAnnotationAndDirectAnnotationWithAlias.class, "my.feature.enabled=true", "my.other.feature.enabled=true"); assertThat(containsBean()).isTrue(); } @Test void multiplePropertiesConditionReportWhenMatched() { load(MultiplePropertiesRequiredConfiguration.class, "property1=value1", "property2=value2"); assertThat(containsBean()).isTrue(); assertThat(getConditionEvaluationReport()).contains("@ConditionalOnProperty ([property1,property2]) matched"); } @Test void multiplePropertiesConditionReportWhenDoesNotMatch() { load(MultiplePropertiesRequiredConfiguration.class, "property1=value1"); assertThat(getConditionEvaluationReport()) .contains("@ConditionalOnProperty ([property1,property2]) did not find property 'property2'"); } @Test void repeatablePropertiesConditionReportWhenMatched() { load(RepeatablePropertiesRequiredConfiguration.class, "property1=value1", "property2=value2"); assertThat(containsBean()).isTrue(); String report = getConditionEvaluationReport(); assertThat(report).contains("@ConditionalOnProperty (property1) matched"); assertThat(report).contains("@ConditionalOnProperty (property2) matched"); } @Test void repeatablePropertiesConditionReportWhenDoesNotMatch() { load(RepeatablePropertiesRequiredConfiguration.class, "property1=value1"); assertThat(getConditionEvaluationReport()) .contains("@ConditionalOnProperty (property2) did not find property 'property2'"); } private void load(Class<?> config, String... environment) { TestPropertyValues.of(environment).applyTo(this.environment); this.context = new SpringApplicationBuilder(config).environment(this.environment) .web(WebApplicationType.NONE) .run(); } private String getConditionEvaluationReport() { assertThat(this.context).isNotNull(); return ConditionEvaluationReport.get(this.context.getBeanFactory()) .getConditionAndOutcomesBySource() .values() .stream() .flatMap(ConditionAndOutcomes::stream) .map(Object::toString) .collect(Collectors.joining("\n")); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(name = { "property1", "property2" }) static
ConditionalOnPropertyTests
java
spring-projects__spring-boot
module/spring-boot-webflux/src/test/java/org/springframework/boot/webflux/actuate/web/exchanges/HttpExchangesWebFilterTests.java
{ "start": 1653, "end": 4097 }
class ____ { private final InMemoryHttpExchangeRepository repository = new InMemoryHttpExchangeRepository(); private final HttpExchangesWebFilter filter = new HttpExchangesWebFilter(this.repository, EnumSet.allOf(Include.class)); @Test void filterRecordsExchange() { executeFilter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), (exchange) -> Mono.empty()); assertThat(this.repository.findAll()).hasSize(1); } @Test void filterRecordsSessionIdWhenSessionIsUsed() { executeFilter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), (exchange) -> exchange.getSession() .doOnNext((session) -> session.getAttributes().put("a", "alpha")) .then()); assertThat(this.repository.findAll()).hasSize(1); Session session = this.repository.findAll().get(0).getSession(); assertThat(session).isNotNull(); assertThat(session.getId()).isNotNull(); } @Test void filterDoesNotRecordIdOfUnusedSession() { executeFilter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), (exchange) -> exchange.getSession().then()); assertThat(this.repository.findAll()).hasSize(1); Session session = this.repository.findAll().get(0).getSession(); assertThat(session).isNull(); } @Test void filterRecordsPrincipal() { Principal principal = mock(Principal.class); given(principal.getName()).willReturn("alice"); executeFilter(new ServerWebExchangeDecorator( MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com"))) { @SuppressWarnings("unchecked") @Override public <T extends Principal> Mono<T> getPrincipal() { return Mono.just((T) principal); } }, (exchange) -> exchange.getSession().doOnNext((session) -> session.getAttributes().put("a", "alpha")).then()); assertThat(this.repository.findAll()).hasSize(1); org.springframework.boot.actuate.web.exchanges.HttpExchange.Principal recordedPrincipal = this.repository .findAll() .get(0) .getPrincipal(); assertThat(recordedPrincipal).isNotNull(); assertThat(recordedPrincipal.getName()).isEqualTo("alice"); } private void executeFilter(ServerWebExchange exchange, WebFilterChain chain) { StepVerifier .create(this.filter.filter(exchange, chain).then(Mono.defer(() -> exchange.getResponse().setComplete()))) .expectComplete() .verify(Duration.ofSeconds(30)); } }
HttpExchangesWebFilterTests
java
quarkusio__quarkus
extensions/micrometer/runtime/src/main/java/io/quarkus/micrometer/runtime/config/runtime/HttpServerConfig.java
{ "start": 402, "end": 2418 }
interface ____ { /** * Comma-separated list of regular expressions used to specify uri * labels in http metrics. * * Vertx instrumentation will attempt to transform parameterized * resource paths, `/item/123`, into a generic form, `/item/{id}`, * to reduce the cardinality of uri label values. * * Patterns specified here will take precedence over those computed * values. * * For example, if `/item/\\\\d+=/item/custom` or * `/item/[0-9]+=/item/custom` is specified in this list, * a request to a matching path (`/item/123`) will use the specified * replacement value (`/item/custom`) as the value for the uri label. * Note that backslashes must be double escaped as `\\\\`. * * @asciidoclet */ Optional<List<String>> matchPatterns(); /** * Comma-separated list of regular expressions defining uri paths * that should be ignored (not measured). */ Optional<List<String>> ignorePatterns(); /** * Suppress non-application uris from metrics collection. * This will suppress all metrics for non-application endpoints using * `${quarkus.http.root-path}/${quarkus.http.non-application-root-path}`. * * Suppressing non-application uris is enabled by default. * * @asciidoclet */ @WithDefault("true") boolean suppressNonApplicationUris(); /** * Suppress 4xx errors from metrics collection for unmatched templates. * This configuration exists to limit cardinality explosion from caller side error. Does not apply to 404 errors. * * Suppressing 4xx errors is disabled by default. * * @asciidoclet */ @WithDefault("false") boolean suppress4xxErrors(); /** * Maximum number of unique URI tag values allowed. After the max number of * tag values is reached, metrics with additional tag values are denied by * filter. */ @WithDefault("100") int maxUriTags(); }
HttpServerConfig
java
quarkusio__quarkus
test-framework/kafka-companion/src/main/java/io/quarkus/test/kafka/KafkaCompanionResource.java
{ "start": 410, "end": 3836 }
class ____ implements QuarkusTestResourceLifecycleManager, DevServicesContext.ContextAware { public static String STRIMZI_KAFKA_IMAGE_KEY = "strimzi.kafka.image"; public static String KAFKA_PORT_KEY = "kafka.port"; protected String strimziKafkaContainerImage; protected Integer kafkaPort; protected boolean kraft; protected StrimziKafkaContainer kafka; protected KafkaCompanion kafkaCompanion; @Override public void setIntegrationTestContext(DevServicesContext context) { Map<String, String> devServicesProperties = context.devServicesProperties(); String bootstrapServers = devServicesProperties.get("kafka.bootstrap.servers"); if (bootstrapServers != null) { kafkaCompanion = new KafkaCompanion(bootstrapServers); String apicurioUrl = devServicesProperties.get("mp.messaging.connector.smallrye-kafka.apicurio.registry.url"); if (apicurioUrl != null) { // normally, the processor will set both property so it's safe to unconditionally load the confluent URL String confluentUrl = devServicesProperties.get("mp.messaging.connector.smallrye-kafka.schema.registry.url"); kafkaCompanion.setCommonClientConfig(Map.of( "apicurio.registry.url", apicurioUrl, "apicurio.registry.auto-register", "true", "schema.registry.url", confluentUrl)); } } } protected StrimziKafkaContainer createContainer(String imageName) { if (imageName == null) { return new StrimziKafkaContainer(); } else { return new StrimziKafkaContainer(imageName); } } @Override public void init(Map<String, String> initArgs) { if (kafkaCompanion == null) { strimziKafkaContainerImage = initArgs.get(STRIMZI_KAFKA_IMAGE_KEY); String portString = initArgs.get(KAFKA_PORT_KEY); kafkaPort = portString == null ? null : Integer.parseInt(portString); kafka = createContainer(strimziKafkaContainerImage) .withNodeId(1) .withBrokerId(1); if (kafkaPort != null) { kafka.withPort(kafkaPort); } Map<String, String> configMap = new HashMap<>(initArgs); configMap.remove(STRIMZI_KAFKA_IMAGE_KEY); configMap.remove(KAFKA_PORT_KEY); kafka.withKafkaConfigurationMap(configMap); } } @Override public Map<String, String> start() { if (kafkaCompanion == null && kafka != null) { kafka.start(); await().until(kafka::isRunning); kafkaCompanion = new KafkaCompanion(kafka.getBootstrapServers()); return Collections.singletonMap("kafka.bootstrap.servers", kafka.getBootstrapServers()); } else { return Collections.emptyMap(); } } @Override public void stop() { if (kafkaCompanion != null) { kafkaCompanion.close(); } if (kafka != null) { kafka.close(); } } @Override public void inject(TestInjector testInjector) { testInjector.injectIntoFields(this.kafkaCompanion, new TestInjector.AnnotatedAndMatchesType(InjectKafkaCompanion.class, KafkaCompanion.class)); } }
KafkaCompanionResource
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoUnidirectionalTest.java
{ "start": 1248, "end": 1994 }
class ____ { @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testVeto(SessionFactoryScope scope) { scope.getSessionFactory().getEventListenerRegistry() .appendListeners( EventType.PRE_INSERT, event -> event.getEntity() instanceof Parent ); assertThatThrownBy( () -> scope.inTransaction( session -> { Parent parent = new Parent(); parent.setField1( "f1" ); parent.setfield2( "f2" ); Child child = new Child(); child.setParent( parent ); session.persist( child ); } ) ).isInstanceOf( EntityActionVetoException.class ); } @Entity(name = "Child") public static
PreInsertEventListenerVetoUnidirectionalTest
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/BulkDeleteOperationCallbacksImpl.java
{ "start": 1786, "end": 3981 }
class ____ implements BulkDeleteOperation.BulkDeleteOperationCallbacks { /** * Path for logging. */ private final String path; /** Page size for bulk delete. */ private final int pageSize; /** span for operations. */ private final AuditSpan span; /** * Store. */ private final S3AStore store; public BulkDeleteOperationCallbacksImpl(final S3AStore store, String path, int pageSize, AuditSpan span) { this.span = span; this.pageSize = pageSize; this.path = path; this.store = store; } @Override @Retries.RetryTranslated public List<Map.Entry<String, String>> bulkDelete(final List<ObjectIdentifier> keysToDelete) throws IOException, IllegalArgumentException { span.activate(); final int size = keysToDelete.size(); checkArgument(size <= pageSize, "Too many paths to delete in one operation: %s", size); if (size == 0) { return emptyList(); } if (size == 1) { return deleteSingleObject(keysToDelete.get(0).key()); } final DeleteObjectsResponse response = once("bulkDelete", path, () -> store.deleteObjects(store.getRequestFactory() .newBulkDeleteRequestBuilder(keysToDelete) .build())).getValue(); final List<S3Error> errors = response.errors(); if (errors.isEmpty()) { // all good. return emptyList(); } else { return errors.stream() .map(e -> pair(e.key(), e.toString())) .collect(Collectors.toList()); } } /** * Delete a single object. * @param key key to delete * @return list of keys which failed to delete: length 0 or 1. * @throws IOException IO problem other than AccessDeniedException */ @Retries.RetryTranslated private List<Map.Entry<String, String>> deleteSingleObject(final String key) throws IOException { try { once("bulkDelete", path, () -> store.deleteObject(store.getRequestFactory() .newDeleteObjectRequestBuilder(key) .build())); } catch (AccessDeniedException e) { return singletonList(pair(key, e.toString())); } return emptyList(); } }
BulkDeleteOperationCallbacksImpl
java
alibaba__druid
core/src/test/java/com/alibaba/druid/spring/User.java
{ "start": 658, "end": 1085 }
class ____ { private long id; private String name; public User() { } public User(long id, String name) { this.id = id; this.name = name; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
User
java
apache__camel
components/camel-sjms/src/test/java/org/apache/camel/component/sjms/bugfixes/CAMEL6820Test.java
{ "start": 1438, "end": 3424 }
class ____ extends JmsTestSupport { private static final String TEST_DATA_DIR = "target/testdata"; private static final String FILE_OUTPUT_URI = "file:" + TEST_DATA_DIR; private static final String FILE_INPUT_URI = "file:" + TEST_DATA_DIR; private static final String SJMS_QUEUE_URI = "sjms:queue:file.converter.queue.CAMEL6820Test"; private static final String MOCK_RESULT_URI = "mock:result"; @Test public void testCamelGenericFileConverterMessage() throws Exception { File f = new File(TEST_DATA_DIR); // First make sure the directories are empty or purged so we don't get bad data on a // test that is run against an uncleaned target directory if (f.exists()) { FileUtils.deleteDirectory(new File(TEST_DATA_DIR)); } // Then add the directory back f.mkdirs(); // Make sure the SjmsComponent is available SjmsComponent component = context.getComponent("sjms", SjmsComponent.class); assertNotNull(component); // Create the test String final String expectedBody = "Hello World"; // Create the Mock endpoint MockEndpoint mock = getMockEndpoint(MOCK_RESULT_URI); mock.expectedMessageCount(1); mock.expectedBodiesReceived(expectedBody); // Send the message to a file to be read by the file component template.sendBody(FILE_OUTPUT_URI, expectedBody); // Verify that it is working correctly mock.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(FILE_INPUT_URI) .convertBodyTo(InputStream.class) .to(SJMS_QUEUE_URI); from(SJMS_QUEUE_URI) .convertBodyTo(String.class) .to(MOCK_RESULT_URI); } }; } }
CAMEL6820Test
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MinaEndpointBuilderFactory.java
{ "start": 19611, "end": 32241 }
interface ____ extends EndpointConsumerBuilder { default MinaEndpointConsumerBuilder basic() { return (MinaEndpointConsumerBuilder) this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: <code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * <code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder exceptionHandler(String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder exchangePattern(String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * If sync is enabled this option dictates MinaConsumer which logging * level to use when logging a there is no reply to send back. * * The option is a: <code>org.apache.camel.LoggingLevel</code> type. * * Default: WARN * Group: consumer (advanced) * * @param noReplyLogLevel the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder noReplyLogLevel(org.apache.camel.LoggingLevel noReplyLogLevel) { doSetProperty("noReplyLogLevel", noReplyLogLevel); return this; } /** * If sync is enabled this option dictates MinaConsumer which logging * level to use when logging a there is no reply to send back. * * The option will be converted to a * <code>org.apache.camel.LoggingLevel</code> type. * * Default: WARN * Group: consumer (advanced) * * @param noReplyLogLevel the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder noReplyLogLevel(String noReplyLogLevel) { doSetProperty("noReplyLogLevel", noReplyLogLevel); return this; } /** * If sync is enabled then this option dictates MinaConsumer if it * should disconnect where there is no reply to send back. * * The option is a: <code>boolean</code> type. * * Default: true * Group: advanced * * @param disconnectOnNoReply the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder disconnectOnNoReply(boolean disconnectOnNoReply) { doSetProperty("disconnectOnNoReply", disconnectOnNoReply); return this; } /** * If sync is enabled then this option dictates MinaConsumer if it * should disconnect where there is no reply to send back. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: advanced * * @param disconnectOnNoReply the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder disconnectOnNoReply(String disconnectOnNoReply) { doSetProperty("disconnectOnNoReply", disconnectOnNoReply); return this; } /** * Number of worker threads in the worker pool for TCP and UDP. * * The option is a: <code>int</code> type. * * Default: 16 * Group: advanced * * @param maximumPoolSize the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder maximumPoolSize(int maximumPoolSize) { doSetProperty("maximumPoolSize", maximumPoolSize); return this; } /** * Number of worker threads in the worker pool for TCP and UDP. * * The option will be converted to a <code>int</code> type. * * Default: 16 * Group: advanced * * @param maximumPoolSize the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder maximumPoolSize(String maximumPoolSize) { doSetProperty("maximumPoolSize", maximumPoolSize); return this; } /** * Whether to use ordered thread pool, to ensure events are processed * orderly on the same channel. * * The option is a: <code>boolean</code> type. * * Default: true * Group: advanced * * @param orderedThreadPoolExecutor the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder orderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { doSetProperty("orderedThreadPoolExecutor", orderedThreadPoolExecutor); return this; } /** * Whether to use ordered thread pool, to ensure events are processed * orderly on the same channel. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: advanced * * @param orderedThreadPoolExecutor the value to set * @return the dsl builder */ default AdvancedMinaEndpointConsumerBuilder orderedThreadPoolExecutor(String orderedThreadPoolExecutor) { doSetProperty("orderedThreadPoolExecutor", orderedThreadPoolExecutor); return this; } /** * Only used for TCP. You can transfer the exchange over the wire * instead of just the body. The following fields are transferred: In * body, Out body, fault body, In headers, Out headers, fault headers, * exchange properties, exchange exception. This requires that the * objects are serializable. Camel will exclude any non-serializable * objects and log it at WARN level. Also make sure to configure * objectCodecPattern to (star) to allow transferring java objects. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param transferExchange the value to set * @return the dsl builder */ @Deprecated default AdvancedMinaEndpointConsumerBuilder transferExchange(boolean transferExchange) { doSetProperty("transferExchange", transferExchange); return this; } /** * Only used for TCP. You can transfer the exchange over the wire * instead of just the body. The following fields are transferred: In * body, Out body, fault body, In headers, Out headers, fault headers, * exchange properties, exchange exception. This requires that the * objects are serializable. Camel will exclude any non-serializable * objects and log it at WARN level. Also make sure to configure * objectCodecPattern to (star) to allow transferring java objects. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param transferExchange the value to set * @return the dsl builder */ @Deprecated default AdvancedMinaEndpointConsumerBuilder transferExchange(String transferExchange) { doSetProperty("transferExchange", transferExchange); return this; } } /** * Builder for endpoint producers for the Mina component. */ public
AdvancedMinaEndpointConsumerBuilder
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/ExecNodeTranslator.java
{ "start": 1224, "end": 1563 }
interface ____<T> { /** * Translates this node into a {@link Transformation}. * * <p>NOTE: This method should return same translate result if called multiple times. * * @param planner The {@link Planner} of the translated graph. */ Transformation<T> translateToPlan(Planner planner); }
ExecNodeTranslator
java
elastic__elasticsearch
modules/aggregations/src/test/java/org/elasticsearch/aggregations/bucket/AggregationBuilderTestCase.java
{ "start": 965, "end": 1218 }
class ____<AB extends AbstractAggregationBuilder<AB>> extends BaseAggregationTestCase<AB> { @Override protected Collection<Class<? extends Plugin>> getPlugins() { return List.of(AggregationsPlugin.class); } }
AggregationBuilderTestCase
java
netty__netty
resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCnameCache.java
{ "start": 889, "end": 3255 }
class ____ implements DnsCnameCache { private final int minTtl; private final int maxTtl; private final Cache<String> cache = new Cache<String>() { @Override protected boolean shouldReplaceAll(String entry) { // Only one 1:1 mapping is supported as specified in the RFC. return true; } @Override protected boolean equals(String entry, String otherEntry) { return AsciiString.contentEqualsIgnoreCase(entry, otherEntry); } }; /** * Create a cache that respects the TTL returned by the DNS server. */ public DefaultDnsCnameCache() { this(0, Cache.MAX_SUPPORTED_TTL_SECS); } /** * Create a cache. * * @param minTtl the minimum TTL * @param maxTtl the maximum TTL */ public DefaultDnsCnameCache(int minTtl, int maxTtl) { this.minTtl = Math.min(Cache.MAX_SUPPORTED_TTL_SECS, checkPositiveOrZero(minTtl, "minTtl")); this.maxTtl = Math.min(Cache.MAX_SUPPORTED_TTL_SECS, checkPositive(maxTtl, "maxTtl")); if (minTtl > maxTtl) { throw new IllegalArgumentException( "minTtl: " + minTtl + ", maxTtl: " + maxTtl + " (expected: 0 <= minTtl <= maxTtl)"); } } @SuppressWarnings("unchecked") @Override public String get(String hostname) { List<? extends String> cached = cache.get(checkNotNull(hostname, "hostname")); if (cached == null || cached.isEmpty()) { return null; } // We can never have more then one record. return cached.get(0); } @Override public void cache(String hostname, String cname, long originalTtl, EventLoop loop) { checkNotNull(hostname, "hostname"); checkNotNull(cname, "cname"); checkNotNull(loop, "loop"); cache.cache(hostname, cname, Math.max(minTtl, (int) Math.min(maxTtl, originalTtl)), loop); } @Override public void clear() { cache.clear(); } @Override public boolean clear(String hostname) { return cache.clear(checkNotNull(hostname, "hostname")); } // Package visibility for testing purposes int minTtl() { return minTtl; } // Package visibility for testing purposes int maxTtl() { return maxTtl; } }
DefaultDnsCnameCache
java
google__error-prone
core/src/main/java/com/google/errorprone/refaster/USkip.java
{ "start": 916, "end": 1618 }
class ____ extends USimpleStatement implements EmptyStatementTree { public static final USkip INSTANCE = new USkip(); private USkip() {} Object readResolve() { return INSTANCE; } @Override public JCSkip inline(Inliner inliner) { return inliner.maker().Skip(); } @Override public <R, D> R accept(TreeVisitor<R, D> visitor, D data) { return visitor.visitEmptyStatement(this, data); } @Override public Kind getKind() { return Kind.EMPTY_STATEMENT; } @Override public Choice<Unifier> visitEmptyStatement(EmptyStatementTree node, Unifier unifier) { return Choice.of(unifier); } @Override public String toString() { return "USkip{}"; } }
USkip
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingNotInDefaultFetchGroupPersistTest.java
{ "start": 1725, "end": 2444 }
class ____ { @Test public void test(SessionFactoryScope scope) { assertFalse( scope.getSessionFactory().getSessionFactoryOptions().isCollectionsInDefaultFetchGroupEnabled() ); Hentity hentity = new Hentity(); HotherEntity hotherEntity = new HotherEntity(); hentity.setLineItems( new ArrayList<>( Collections.singletonList( hotherEntity ) ) ); hentity.setNextRevUNs( new ArrayList<>( Collections.singletonList( "something" ) ) ); scope.inTransaction( session -> { session.persist( hentity ); } ); scope.inTransaction( session -> { hentity.bumpNumber(); session.merge( hentity ); } ); } // --- // @Entity(name = "HotherEntity") public static
DirtyTrackingNotInDefaultFetchGroupPersistTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/StateBackendLoader.java
{ "start": 1952, "end": 3872 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(StateBackendLoader.class); /** Used for Loading ChangelogStateBackend. */ private static final String CHANGELOG_STATE_BACKEND = "org.apache.flink.state.changelog.ChangelogStateBackend"; /** Used for Loading TempChangelogStateBackend. */ private static final String DEACTIVATED_CHANGELOG_STATE_BACKEND = "org.apache.flink.state.changelog.DeactivatedChangelogStateBackend"; /** Used for loading RocksDBStateBackend. */ private static final String ROCKSDB_STATE_BACKEND_FACTORY = "org.apache.flink.state.rocksdb.EmbeddedRocksDBStateBackendFactory"; /** Used for loading ForStStateBackend. */ private static final String FORST_STATE_BACKEND_FACTORY = "org.apache.flink.state.forst.ForStStateBackendFactory"; // ------------------------------------------------------------------------ // Configuration shortcut names // ------------------------------------------------------------------------ /** The shortcut configuration name of the HashMap state backend. */ public static final String HASHMAP_STATE_BACKEND_NAME = "hashmap"; /** The shortcut configuration name for the RocksDB State Backend. */ public static final String ROCKSDB_STATE_BACKEND_NAME = "rocksdb"; public static final String FORST_STATE_BACKEND_NAME = "forst"; // ------------------------------------------------------------------------ // Loading the state backend from a configuration // ------------------------------------------------------------------------ /** * Loads the unwrapped state backend from the configuration, from the parameter 'state.backend', * as defined in {@link StateBackendOptions#STATE_BACKEND}. * * <p>The state backends can be specified either via their shortcut name, or via the
StateBackendLoader
java
greenrobot__EventBus
EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java
{ "start": 1148, "end": 3170 }
class ____ { private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool(); boolean logSubscriberExceptions = true; boolean logNoSubscriberMessages = true; boolean sendSubscriberExceptionEvent = true; boolean sendNoSubscriberEvent = true; boolean throwSubscriberException; boolean eventInheritance = true; boolean ignoreGeneratedIndex; boolean strictMethodVerification; ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE; List<Class<?>> skipMethodVerificationForClasses; List<SubscriberInfoIndex> subscriberInfoIndexes; Logger logger; MainThreadSupport mainThreadSupport; EventBusBuilder() { } /** Default: true */ public EventBusBuilder logSubscriberExceptions(boolean logSubscriberExceptions) { this.logSubscriberExceptions = logSubscriberExceptions; return this; } /** Default: true */ public EventBusBuilder logNoSubscriberMessages(boolean logNoSubscriberMessages) { this.logNoSubscriberMessages = logNoSubscriberMessages; return this; } /** Default: true */ public EventBusBuilder sendSubscriberExceptionEvent(boolean sendSubscriberExceptionEvent) { this.sendSubscriberExceptionEvent = sendSubscriberExceptionEvent; return this; } /** Default: true */ public EventBusBuilder sendNoSubscriberEvent(boolean sendNoSubscriberEvent) { this.sendNoSubscriberEvent = sendNoSubscriberEvent; return this; } /** * Fails if an subscriber throws an exception (default: false). * <p/> * Tip: Use this with BuildConfig.DEBUG to let the app crash in DEBUG mode (only). This way, you won't miss * exceptions during development. */ public EventBusBuilder throwSubscriberException(boolean throwSubscriberException) { this.throwSubscriberException = throwSubscriberException; return this; } /** * By default, EventBus considers the event
EventBusBuilder
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/data/DataFetcher.java
{ "start": 884, "end": 1092 }
interface ____<T> { /** * Callback that must be called when data has been loaded and is available, or when the load * fails. * * @param <T> The type of data that will be loaded. */
DataFetcher
java
playframework__playframework
dev-mode/gradle-plugin/src/main/java/play/gradle/plugin/PlayRunPlugin.java
{ "start": 1905, "end": 6247 }
class ____ implements Plugin<Project> { public static final int DEFAULT_HTTP_PORT = 9000; public static final String PLAY_RUN_TASK_NAME = "playRun"; @Override public void apply(@NotNull final Project project) { createRunTask(project); } private boolean isChangingArtifact(ComponentIdentifier component) { return isProjectComponent(component) || (component instanceof ComponentArtifactIdentifier && component.getDisplayName().endsWith("-assets.jar")); } private FileCollection filterNonChangingArtifacts(Configuration configuration) { return configuration .getIncoming() .artifactView(view -> view.componentFilter(__ -> !isChangingArtifact(__))) .getFiles(); } private ConfigurableFileCollection findClasspathDirectories(@Nullable Project project) { if (project == null) return null; var mainSourceSet = mainSourceSet(project); var processResources = (ProcessResources) project.getTasks().findByName(PROCESS_RESOURCES_TASK_NAME); var compileJava = (AbstractCompile) project.getTasks().findByName(COMPILE_JAVA_TASK_NAME); return project.files( (processResources != null) ? processResources.getDestinationDir() : null, (compileJava != null) ? compileJava.getDestinationDirectory() : null, Stream.of("scala", "kotlin") .map(source -> ((SourceDirectorySet) mainSourceSet.getExtensions().findByName(source))) .filter(Objects::nonNull) .map(SourceDirectorySet::getClassesDirectory) .collect(Collectors.toList())); } private List<DirectoryProperty> findAssetsDirectories(@Nullable Project project) { if (project == null) return List.of(); var assets = new ArrayList<DirectoryProperty>(); var publicSource = (SourceDirectorySet) mainSourceSet(project).getExtensions().findByName(PUBLIC_SOURCE_NAME); if (publicSource != null) { assets.add(publicSource.getDestinationDirectory()); } var assetsSource = (SourceDirectorySet) mainSourceSet(project).getExtensions().findByName(ASSETS_SOURCE_NAME); if (assetsSource != null) { assets.add(assetsSource.getDestinationDirectory()); } return assets; } private void createRunTask(final Project project) { project .getTasks() .register( PLAY_RUN_TASK_NAME, PlayRun.class, playRun -> { playRun.setDescription("Runs the Play application for local development."); playRun.setGroup(APPLICATION_GROUP); playRun.dependsOn(project.getTasks().findByName(JavaPlugin.CLASSES_TASK_NAME)); playRun.getOutputs().upToDateWhen(task -> ((PlayRun) task).isUpToDate()); playRun.getWorkingDir().convention(project.getLayout().getProjectDirectory()); playRun.getClasses().from(findClasspathDirectories(project)); playRun.getAssetsDirs().from(findAssetsDirectories(project)); playRun.getAssetsPath().convention(playExtension(project).getAssets().getPath()); playRun.getHttpPort().convention(DEFAULT_HTTP_PORT); playRun .getDevSettings() .convention(project.getObjects().mapProperty(String.class, String.class)); var runtime = project.getConfigurations().getByName(RUNTIME_CLASSPATH_CONFIGURATION_NAME); playRun.getRuntimeClasspath().from(filterNonChangingArtifacts(runtime)); filterProjectComponents(runtime) .forEach( path -> { Project child = project.findProject(path); if (child == null) return; playRun.getClasses().from(findClasspathDirectories(child)); playRun.dependsOn(child.getTasks().findByName(PROCESS_RESOURCES_TASK_NAME)); if (isPlayProject(child)) { playRun.getAssetsDirs().from(findAssetsDirectories(child)); playRun.dependsOn(child.getTasks().findByName(PROCESS_ASSETS_TASK_NAME)); } }); playRun.dependsOn(project.getTasks().findByName(PROCESS_ASSETS_TASK_NAME)); }); } }
PlayRunPlugin
java
apache__flink
flink-connectors/flink-connector-files/src/test/java/org/apache/flink/connector/file/src/PendingSplitsCheckpointSerializerTest.java
{ "start": 1288, "end": 6558 }
class ____ { @Test void serializeEmptyCheckpoint() throws Exception { final PendingSplitsCheckpoint<FileSourceSplit> checkpoint = PendingSplitsCheckpoint.fromCollectionSnapshot(Collections.emptyList()); final PendingSplitsCheckpoint<FileSourceSplit> deSerialized = serializeAndDeserialize(checkpoint); assertCheckpointsEqual(checkpoint, deSerialized); } @Test void serializeSomeSplits() throws Exception { final PendingSplitsCheckpoint<FileSourceSplit> checkpoint = PendingSplitsCheckpoint.fromCollectionSnapshot( Arrays.asList(testSplit1(), testSplit2(), testSplit3())); final PendingSplitsCheckpoint<FileSourceSplit> deSerialized = serializeAndDeserialize(checkpoint); assertCheckpointsEqual(checkpoint, deSerialized); } @Test void serializeSplitsAndProcessedPaths() throws Exception { final PendingSplitsCheckpoint<FileSourceSplit> checkpoint = PendingSplitsCheckpoint.fromCollectionSnapshot( Arrays.asList(testSplit1(), testSplit2(), testSplit3()), Arrays.asList( new Path("file:/some/path"), new Path("s3://bucket/key/and/path"), new Path("hdfs://namenode:12345/path"))); final PendingSplitsCheckpoint<FileSourceSplit> deSerialized = serializeAndDeserialize(checkpoint); assertCheckpointsEqual(checkpoint, deSerialized); } @Test void repeatedSerialization() throws Exception { final PendingSplitsCheckpoint<FileSourceSplit> checkpoint = PendingSplitsCheckpoint.fromCollectionSnapshot( Arrays.asList(testSplit3(), testSplit1())); serializeAndDeserialize(checkpoint); serializeAndDeserialize(checkpoint); final PendingSplitsCheckpoint<FileSourceSplit> deSerialized = serializeAndDeserialize(checkpoint); assertCheckpointsEqual(checkpoint, deSerialized); } @Test void repeatedSerializationCaches() throws Exception { final PendingSplitsCheckpoint<FileSourceSplit> checkpoint = PendingSplitsCheckpoint.fromCollectionSnapshot( Collections.singletonList(testSplit2())); final byte[] ser1 = new PendingSplitsCheckpointSerializer<>(FileSourceSplitSerializer.INSTANCE) .serialize(checkpoint); final byte[] ser2 = new PendingSplitsCheckpointSerializer<>(FileSourceSplitSerializer.INSTANCE) .serialize(checkpoint); assertThat(ser1).isSameAs(ser2); } // ------------------------------------------------------------------------ // test utils // ------------------------------------------------------------------------ private static FileSourceSplit testSplit1() { return new FileSourceSplit( "random-id", new Path("hdfs://namenode:14565/some/path/to/a/file"), 100_000_000, 64_000_000, 0, 200_000_000, "host1", "host2", "host3"); } private static FileSourceSplit testSplit2() { return new FileSourceSplit("some-id", new Path("file:/some/path/to/a/file"), 0, 0, 0, 0); } private static FileSourceSplit testSplit3() { return new FileSourceSplit( "an-id", new Path("s3://some-bucket/key/to/the/object"), 0, 1234567, 0, 1234567); } private static PendingSplitsCheckpoint<FileSourceSplit> serializeAndDeserialize( final PendingSplitsCheckpoint<FileSourceSplit> split) throws IOException { final PendingSplitsCheckpointSerializer<FileSourceSplit> serializer = new PendingSplitsCheckpointSerializer<>(FileSourceSplitSerializer.INSTANCE); final byte[] bytes = SimpleVersionedSerialization.writeVersionAndSerialize(serializer, split); return SimpleVersionedSerialization.readVersionAndDeSerialize(serializer, bytes); } private static void assertCheckpointsEqual( final PendingSplitsCheckpoint<FileSourceSplit> expected, final PendingSplitsCheckpoint<FileSourceSplit> actual) { assertOrderedCollectionEquals( expected.getSplits(), actual.getSplits(), FileSourceSplitSerializerTest::assertSplitsEqual); assertThat(actual.getAlreadyProcessedPaths()) .containsExactlyElementsOf(expected.getAlreadyProcessedPaths()); } private static <E> void assertOrderedCollectionEquals( Collection<E> expected, Collection<E> actual, BiConsumer<E, E> equalityAsserter) { assertThat(actual).hasSize(expected.size()); final Iterator<E> expectedIter = expected.iterator(); final Iterator<E> actualIter = actual.iterator(); while (expectedIter.hasNext()) { equalityAsserter.accept(expectedIter.next(), actualIter.next()); } } }
PendingSplitsCheckpointSerializerTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/InfluxDbEndpointBuilderFactory.java
{ "start": 13126, "end": 13453 }
class ____ extends AbstractEndpointBuilder implements InfluxDbEndpointBuilder, AdvancedInfluxDbEndpointBuilder { public InfluxDbEndpointBuilderImpl(String path) { super(componentName, path); } } return new InfluxDbEndpointBuilderImpl(path); } }
InfluxDbEndpointBuilderImpl
java
apache__flink
flink-core/src/main/java/org/apache/flink/util/InstantiationUtil.java
{ "start": 15268, "end": 15601 }
class ____ a non-statically accessible inner class. */ public static boolean isNonStaticInnerClass(Class<?> clazz) { return clazz.getEnclosingClass() != null && (clazz.getDeclaringClass() == null || !Modifier.isStatic(clazz.getModifiers())); } /** * Performs a standard check whether the
is
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/PlatformConfig.java
{ "start": 547, "end": 918 }
interface ____ { /** * groupId of the platform to use */ @WithDefault("io.quarkus.platform") String groupId(); /** * artifactId of the platform to use */ @WithDefault("quarkus-bom") String artifactId(); /** * version of the platform to use */ @WithDefault("999-SNAPSHOT") String version(); }
PlatformConfig
java
spring-projects__spring-boot
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java
{ "start": 7399, "end": 7627 }
class ____ implements Supplier<EndpointServlet> { @Override public EndpointServlet get() { return new EndpointServlet(TestServlet.class); } } @ServletEndpoint(id = "testservlet") @Validated static
TestServletEndpoint
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/aroundconstruct/AroundConstructTest.java
{ "start": 743, "end": 1346 }
class ____ { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(MyTransactional.class, SimpleBean.class, SimpleInterceptor.class, MyDependency.class, SomeAroundInvokeInterceptor.class); public static AtomicBoolean INTERCEPTOR_CALLED = new AtomicBoolean(false); @Test public void testInterception() { SimpleBean simpleBean = Arc.container().instance(SimpleBean.class).get(); assertNotNull(simpleBean); Assertions.assertTrue(INTERCEPTOR_CALLED.get()); } @Singleton @MyTransactional static
AroundConstructTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByCheckerTest.java
{ "start": 43344, "end": 43951 }
class ____ { public final Object mu = new Object(); @GuardedBy("Lib.Inner.mu") int x = 1; void f() { synchronized (Lib.Inner.mu) { x++; } } } """) .doTest(); } @Test public void instanceInitializersAreUnchecked() { compilationHelper .addSourceLines( "threadsafety/Test.java", """ package threadsafety; import com.google.errorprone.annotations.concurrent.GuardedBy; public
Test
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/env/NodeRepurposeCommandIT.java
{ "start": 1100, "end": 5300 }
class ____ extends ESIntegTestCase { public void testRepurpose() throws Exception { final String indexName = "test-repurpose"; logger.info("--> starting two nodes"); final String masterNode = internalCluster().startMasterOnlyNode(); final String dataNode = internalCluster().startDataOnlyNode( Settings.builder().put(IndicesService.WRITE_DANGLING_INDICES_INFO_SETTING.getKey(), false).build() ); logger.info("--> creating index"); prepareCreate(indexName, indexSettings(1, 0)).get(); logger.info("--> indexing a simple document"); prepareIndex(indexName).setId("1").setSource("field1", "value1").get(); ensureGreen(); assertTrue(client().prepareGet(indexName, "1").get().isExists()); final Settings masterNodeDataPathSettings = internalCluster().dataPathSettings(masterNode); final Settings dataNodeDataPathSettings = internalCluster().dataPathSettings(dataNode); // put some unknown role here to make sure the tool does not bark when encountering an unknown role final Settings noMasterNoDataSettings = nonMasterNode(nonDataNode()); final Settings noMasterNoDataSettingsForMasterNode = Settings.builder() .put(noMasterNoDataSettings) .put(masterNodeDataPathSettings) .build(); final Settings noMasterNoDataSettingsForDataNode = Settings.builder() .put(noMasterNoDataSettings) .put(dataNodeDataPathSettings) .build(); internalCluster().stopRandomDataNode(); // verify test setup logger.info("--> restarting node with node.data=false and node.master=false"); IllegalStateException ex = expectThrows( IllegalStateException.class, "Node started with node.data=false and node.master=false while having existing index metadata must fail", () -> internalCluster().startCoordinatingOnlyNode(dataNodeDataPathSettings) ); logger.info("--> Repurposing node 1"); executeRepurposeCommand(noMasterNoDataSettingsForDataNode, 1, 1); ElasticsearchException lockedException = expectThrows( ElasticsearchException.class, () -> executeRepurposeCommand(noMasterNoDataSettingsForMasterNode, 1, 1) ); assertThat(lockedException.getMessage(), containsString(NodeRepurposeCommand.FAILED_TO_OBTAIN_NODE_LOCK_MSG)); logger.info("--> Starting node after repurpose"); internalCluster().startCoordinatingOnlyNode(dataNodeDataPathSettings); assertTrue(indexExists(indexName)); expectThrows(NoShardAvailableActionException.class, client().prepareGet(indexName, "1")); logger.info("--> Restarting and repurposing other node"); internalCluster().stopNode(internalCluster().getRandomNodeName()); internalCluster().stopNode(internalCluster().getRandomNodeName()); executeRepurposeCommand(noMasterNoDataSettingsForMasterNode, 1, 0); // by restarting as master and data node, we can check that the index definition was really deleted and also that the tool // does not mess things up so much that the nodes cannot boot as master or data node any longer. internalCluster().startMasterOnlyNode(masterNodeDataPathSettings); internalCluster().startDataOnlyNode(dataNodeDataPathSettings); ensureGreen(); // index is gone. assertFalse(indexExists(indexName)); } private void executeRepurposeCommand(Settings settings, int expectedIndexCount, int expectedShardCount) throws Exception { boolean verbose = randomBoolean(); Settings settingsWithPath = Settings.builder().put(internalCluster().getDefaultSettings()).put(settings).build(); Matcher<String> matcher = allOf( containsString(NodeRepurposeCommand.noMasterMessage(expectedIndexCount, expectedShardCount, 0)), NodeRepurposeCommandTests.conditionalNot(containsString("test-repurpose"), verbose == false) ); NodeRepurposeCommandTests.verifySuccess(settingsWithPath, matcher, verbose); } }
NodeRepurposeCommandIT