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
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/support/SearchOption.java
{ "start": 755, "end": 1348 }
enum ____ { /** * Search the inheritance hierarchy (i.e., the current class, implemented * interfaces, and superclasses), but do not search on enclosing classes. * * @see Class#getSuperclass() * @see Class#getInterfaces() */ DEFAULT, /** * Search the inheritance hierarchy as with the {@link #DEFAULT} search option * but also search the {@linkplain Class#getEnclosingClass() enclosing class} * hierarchy for <em>inner classes</em> (i.e., a non-static member classes). * * @deprecated because it is preferable to inspect the runtime enclosing * types of a
SearchOption
java
grpc__grpc-java
benchmarks/src/generated/main/grpc/io/grpc/benchmarks/proto/ReportQpsScenarioServiceGrpc.java
{ "start": 12141, "end": 12763 }
class ____ implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { ReportQpsScenarioServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return io.grpc.benchmarks.proto.Services.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("ReportQpsScenarioService"); } } private static final
ReportQpsScenarioServiceBaseDescriptorSupplier
java
apache__dubbo
dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RuleConverter.java
{ "start": 960, "end": 1045 }
interface ____ { List<URL> convert(URL subscribeUrl, Object source); }
RuleConverter
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/TestConstructor.java
{ "start": 3585, "end": 3758 }
interface ____ { /** * JVM system property used to change the default <em>test constructor * autowire mode</em>: {@value}. * <p>Acceptable values include
TestConstructor
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/alter/OracleAlterTableTest4.java
{ "start": 977, "end": 2437 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "ALTER TABLE ws_pledge_contract modify ( reference VARCHAR2(4000) )"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); statemen.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("ws_pledge_contract"))); assertEquals(1, visitor.getColumns().size()); assertTrue(visitor.getColumns().contains(new TableStat.Column("ws_pledge_contract", "reference"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode"))); } }
OracleAlterTableTest4
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/reduce/WrappedReducer.java
{ "start": 1905, "end": 2476 }
class ____<KEYIN, VALUEIN, KEYOUT, VALUEOUT> extends Reducer<KEYIN, VALUEIN, KEYOUT, VALUEOUT> { /** * A a wrapped {@link Reducer.Context} for custom implementations. * @param reduceContext <code>ReduceContext</code> to be wrapped * @return a wrapped <code>Reducer.Context</code> for custom implementations */ public Reducer<KEYIN, VALUEIN, KEYOUT, VALUEOUT>.Context getReducerContext(ReduceContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT> reduceContext) { return new Context(reduceContext); } @InterfaceStability.Evolving public
WrappedReducer
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/mutiny/UniBean.java
{ "start": 372, "end": 984 }
class ____ { private static final String OUT_STREAM = "exclamated-stream"; final List<String> strings = Collections.synchronizedList(new ArrayList<>()); @Incoming(StringProducer.ANOTHER_STRING_STREAM) @Outgoing(OUT_STREAM) public Uni<String> transform(String input) { return Uni.createFrom().item(input).map(this::exclamate); } @Incoming(OUT_STREAM) public void collect(String input) { strings.add(input); } private String exclamate(String in) { return in + "!"; } public List<String> getStrings() { return strings; } }
UniBean
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolver.java
{ "start": 2410, "end": 10900 }
class ____ { /** * A filter for selecting {@code @ExceptionHandler} methods. */ private static final MethodFilter EXCEPTION_HANDLER_METHODS = method -> AnnotatedElementUtils.hasAnnotation(method, ExceptionHandler.class); private static final ExceptionHandlerMappingInfo NO_MATCHING_EXCEPTION_HANDLER; static { try { NO_MATCHING_EXCEPTION_HANDLER = new ExceptionHandlerMappingInfo(Set.of(), Set.of(), ExceptionHandlerMethodResolver.class.getDeclaredMethod("noMatchingExceptionHandler")); } catch (NoSuchMethodException ex) { throw new IllegalStateException("Expected method not found: " + ex); } } private final Map<ExceptionMapping, ExceptionHandlerMappingInfo> mappedMethods = new HashMap<>(16); private final ConcurrentLruCache<ExceptionMapping, ExceptionHandlerMappingInfo> lookupCache = new ConcurrentLruCache<>(24, cacheKey -> getMappedMethod(cacheKey.exceptionType(), cacheKey.mediaType())); /** * A constructor that finds {@link ExceptionHandler} methods in the given type. * @param handlerType the type to introspect * @throws IllegalStateException in case of invalid or ambiguous exception mapping declarations */ public ExceptionHandlerMethodResolver(Class<?> handlerType) { for (Method method : MethodIntrospector.selectMethods(handlerType, EXCEPTION_HANDLER_METHODS)) { ExceptionHandlerMappingInfo mappingInfo = detectExceptionMappings(method); for (Class<? extends Throwable> exceptionType : mappingInfo.getExceptionTypes()) { for (MediaType producibleType : mappingInfo.getProducibleTypes()) { addExceptionMapping(new ExceptionMapping(exceptionType, producibleType), mappingInfo); } if (mappingInfo.getProducibleTypes().isEmpty()) { addExceptionMapping(new ExceptionMapping(exceptionType, MediaType.ALL), mappingInfo); } } } } /** * Extract exception mappings from the {@code @ExceptionHandler} annotation first, * and then as a fallback from the method signature itself. */ @SuppressWarnings("unchecked") private ExceptionHandlerMappingInfo detectExceptionMappings(Method method) { ExceptionHandler exceptionHandler = readExceptionHandlerAnnotation(method); List<Class<? extends Throwable>> exceptions = new ArrayList<>(Arrays.asList(exceptionHandler.exception())); if (exceptions.isEmpty()) { for (Class<?> paramType : method.getParameterTypes()) { if (Throwable.class.isAssignableFrom(paramType)) { exceptions.add((Class<? extends Throwable>) paramType); } } } if (exceptions.isEmpty()) { throw new IllegalStateException("No exception types mapped to " + method); } Set<MediaType> mediaTypes = new LinkedHashSet<>(); for (String mediaType : exceptionHandler.produces()) { try { mediaTypes.add(MediaType.parseMediaType(mediaType)); } catch (InvalidMediaTypeException exc) { throw new IllegalStateException("Invalid media type [" + mediaType + "] declared on @ExceptionHandler for " + method, exc); } } return new ExceptionHandlerMappingInfo(Set.copyOf(exceptions), mediaTypes, method); } private ExceptionHandler readExceptionHandlerAnnotation(Method method) { ExceptionHandler ann = AnnotatedElementUtils.findMergedAnnotation(method, ExceptionHandler.class); Assert.state(ann != null, "No ExceptionHandler annotation"); return ann; } private void addExceptionMapping(ExceptionMapping mapping, ExceptionHandlerMappingInfo mappingInfo) { ExceptionHandlerMappingInfo oldMapping = this.mappedMethods.put(mapping, mappingInfo); if (oldMapping != null && !oldMapping.getHandlerMethod().equals(mappingInfo.getHandlerMethod())) { throw new IllegalStateException("Ambiguous @ExceptionHandler method mapped for [" + mapping + "]: {" + oldMapping.getHandlerMethod() + ", " + mappingInfo.getHandlerMethod() + "}"); } } /** * Whether the contained type has any exception mappings. */ public boolean hasExceptionMappings() { return !this.mappedMethods.isEmpty(); } /** * Find a {@link Method} to handle the given exception. * <p>Uses {@link ExceptionDepthComparator} if more than one match is found. * @param exception the exception * @return a Method to handle the exception, or {@code null} if none found */ public @Nullable Method resolveMethod(Exception exception) { ExceptionHandlerMappingInfo mappingInfo = resolveExceptionMapping(exception, MediaType.ALL); return (mappingInfo != null) ? mappingInfo.getHandlerMethod() : null; } /** * Find a {@link Method} to handle the given Throwable. * <p>Uses {@link ExceptionDepthComparator} if more than one match is found. * @param exception the exception * @return a Method to handle the exception, or {@code null} if none found * @since 5.0 */ public @Nullable Method resolveMethodByThrowable(Throwable exception) { ExceptionHandlerMappingInfo mappingInfo = resolveExceptionMapping(exception, MediaType.ALL); return (mappingInfo != null) ? mappingInfo.getHandlerMethod() : null; } /** * Find a {@link Method} to handle the given Throwable for the requested {@link MediaType}. * <p>Uses {@link ExceptionDepthComparator} and {@link MediaType#isMoreSpecific(MimeType)} * if more than one match is found. * @param exception the exception * @param mediaType the media type requested by the HTTP client * @return a Method to handle the exception, or {@code null} if none found * @since 6.2 */ public @Nullable ExceptionHandlerMappingInfo resolveExceptionMapping(Throwable exception, MediaType mediaType) { ExceptionHandlerMappingInfo mappingInfo = resolveExceptionMappingByExceptionType(exception.getClass(), mediaType); if (mappingInfo == null) { Throwable cause = exception.getCause(); if (cause != null) { mappingInfo = resolveExceptionMapping(cause, mediaType); } } return mappingInfo; } /** * Find a {@link Method} to handle the given exception type. This can be * useful if an {@link Exception} instance is not available (for example, for tools). * <p>Uses {@link ExceptionDepthComparator} if more than one match is found. * @param exceptionType the exception type * @return a Method to handle the exception, or {@code null} if none found */ public @Nullable Method resolveMethodByExceptionType(Class<? extends Throwable> exceptionType) { ExceptionHandlerMappingInfo mappingInfo = resolveExceptionMappingByExceptionType(exceptionType, MediaType.ALL); return (mappingInfo != null) ? mappingInfo.getHandlerMethod() : null; } /** * Find a {@link Method} to handle the given exception type and media type. * This can be useful if an {@link Exception} instance is not available (for example, for tools). * @param exceptionType the exception type * @param mediaType the media type requested by the HTTP client * @return a Method to handle the exception, or {@code null} if none found */ public @Nullable ExceptionHandlerMappingInfo resolveExceptionMappingByExceptionType(Class<? extends Throwable> exceptionType, MediaType mediaType) { ExceptionHandlerMappingInfo mappingInfo = this.lookupCache.get(new ExceptionMapping(exceptionType, mediaType)); return (mappingInfo != NO_MATCHING_EXCEPTION_HANDLER ? mappingInfo : null); } /** * Return the {@link Method} mapped to the given exception type, or * {@link #NO_MATCHING_EXCEPTION_HANDLER} if none. */ private ExceptionHandlerMappingInfo getMappedMethod(Class<? extends Throwable> exceptionType, MediaType mediaType) { List<ExceptionMapping> matches = new ArrayList<>(); for (ExceptionMapping mappingInfo : this.mappedMethods.keySet()) { if (mappingInfo.exceptionType().isAssignableFrom(exceptionType) && mappingInfo.mediaType().isCompatibleWith(mediaType)) { matches.add(mappingInfo); } } if (!matches.isEmpty()) { if (matches.size() > 1) { matches.sort(new ExceptionMapingComparator(exceptionType, mediaType)); } return Objects.requireNonNull(this.mappedMethods.get(matches.get(0))); } else { return NO_MATCHING_EXCEPTION_HANDLER; } } /** * For the {@link #NO_MATCHING_EXCEPTION_HANDLER} constant. */ @SuppressWarnings("unused") private void noMatchingExceptionHandler() { } private record ExceptionMapping(Class<? extends Throwable> exceptionType, MediaType mediaType) { @Override public String toString() { return "ExceptionHandler{" + "exceptionType=" + this.exceptionType.getCanonicalName() + ", mediaType=" + this.mediaType + '}'; } } private static
ExceptionHandlerMethodResolver
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/LearningToRankConfigTests.java
{ "start": 7819, "end": 10534 }
class ____ implements LearningToRankFeatureExtractorBuilder { public static final ParseField NAME = new ParseField("test"); private final String featureName; private static final ConstructingObjectParser<TestValueExtractor, Void> PARSER = new ConstructingObjectParser<>( NAME.getPreferredName(), a -> new TestValueExtractor((String) a[0]) ); private static final ConstructingObjectParser<TestValueExtractor, Void> LENIENT_PARSER = new ConstructingObjectParser<>( NAME.getPreferredName(), true, a -> new TestValueExtractor((String) a[0]) ); static { PARSER.declareString(constructorArg(), FEATURE_NAME); LENIENT_PARSER.declareString(constructorArg(), FEATURE_NAME); } public static TestValueExtractor fromXContent(XContentParser parser, Object context) { boolean lenient = Boolean.TRUE.equals(context); return lenient ? LENIENT_PARSER.apply(parser, null) : PARSER.apply(parser, null); } TestValueExtractor(StreamInput in) throws IOException { this.featureName = in.readString(); } TestValueExtractor(String featureName) { this.featureName = featureName; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(FEATURE_NAME.getPreferredName(), featureName); builder.endObject(); return builder; } @Override public String getWriteableName() { return NAME.getPreferredName(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(featureName); } @Override public String featureName() { return featureName; } @Override public void validate() throws Exception {} @Override public String getName() { return NAME.getPreferredName(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TestValueExtractor that = (TestValueExtractor) o; return Objects.equals(featureName, that.featureName); } @Override public int hashCode() { return Objects.hash(featureName); } @Override public TestValueExtractor rewrite(QueryRewriteContext ctx) throws IOException { return this; } } }
TestValueExtractor
java
apache__camel
catalog/camel-report-maven-plugin/src/test/java/org/apache/camel/maven/htmlxlsx/process/TestResultParserTest.java
{ "start": 1251, "end": 2235 }
class ____ { @Test public void testTestResultParser() { // keep jacoco happy TestResultParser result = new TestResultParser(); assertNotNull(result); } @Test public void testParse() { TestResultParser parser = new TestResultParser(); TestResult result = parser.parse(TestUtil.testResult()); assertAll( () -> assertNotNull(result), () -> assertNotNull(result.getCamelContextRouteCoverage().getRoutes().getRouteList().get(0).getComponents())); } @Test public void testParseException() { TestResultParser spy = spy(new TestResultParser()); Mockito .doAnswer(invocation -> { throw new TestJsonProcessingException(); }) .when(spy).objectMapper(); assertThrows(RuntimeException.class, () -> { spy.parse(TestUtil.testResult()); }); } }
TestResultParserTest
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/creation/bytebuddy/AbstractByteBuddyMockMakerTest.java
{ "start": 3963, "end": 4027 }
class ____ implements Serializable {} private
SerializableClass
java
spring-projects__spring-framework
spring-jms/src/main/java/org/springframework/jms/core/JmsMessageOperations.java
{ "start": 8794, "end": 13172 }
class ____ convert the payload to * @return the converted payload of the reply message, possibly {@code null} if * the message could not be received, for example due to a timeout * @since 7.0 */ <T> @Nullable T receiveSelectedAndConvert(String destinationName, @Nullable String messageSelector, Class<T> targetClass) throws MessagingException; /** * Send a request message and receive the reply from the given destination. * @param destinationName the name of the target destination * @param requestMessage the message to send * @return the reply, possibly {@code null} if the message could not be received, * for example due to a timeout */ @Nullable Message<?> sendAndReceive(String destinationName, Message<?> requestMessage) throws MessagingException; /** * Convert the given request Object to serialized form, possibly using a * {@link org.springframework.messaging.converter.MessageConverter}, send * it as a {@link Message} to the given destination, receive the reply and convert * its body of the specified target class. * @param destinationName the name of the target destination * @param request payload for the request message to send * @param targetClass the target type to convert the payload of the reply to * @return the payload of the reply message, possibly {@code null} if the message * could not be received, for example due to a timeout */ <T> @Nullable T convertSendAndReceive(String destinationName, Object request, Class<T> targetClass) throws MessagingException; /** * Convert the given request Object to serialized form, possibly using a * {@link org.springframework.messaging.converter.MessageConverter}, send * it as a {@link Message} with the given headers, to the specified destination, * receive the reply and convert its body of the specified target class. * @param destinationName the name of the target destination * @param request payload for the request message to send * @param headers the headers for the request message to send * @param targetClass the target type to convert the payload of the reply to * @return the payload of the reply message, possibly {@code null} if the message * could not be received, for example due to a timeout */ <T> @Nullable T convertSendAndReceive(String destinationName, Object request, @Nullable Map<String, Object> headers, Class<T> targetClass) throws MessagingException; /** * Convert the given request Object to serialized form, possibly using a * {@link org.springframework.messaging.converter.MessageConverter}, * apply the given post-processor and send the resulting {@link Message} to the * given destination, receive the reply and convert its body of the given * target class. * @param destinationName the name of the target destination * @param request payload for the request message to send * @param targetClass the target type to convert the payload of the reply to * @param requestPostProcessor post-process to apply to the request message * @return the payload of the reply message, possibly {@code null} if the message * could not be received, for example due to a timeout */ <T> @Nullable T convertSendAndReceive(String destinationName, Object request, Class<T> targetClass, @Nullable MessagePostProcessor requestPostProcessor) throws MessagingException; /** * Convert the given request Object to serialized form, possibly using a * {@link org.springframework.messaging.converter.MessageConverter}, * wrap it as a message with the given headers, apply the given post-processor * and send the resulting {@link Message} to the specified destination, receive * the reply and convert its body of the given target class. * @param destinationName the name of the target destination * @param request payload for the request message to send * @param targetClass the target type to convert the payload of the reply to * @param requestPostProcessor post-process to apply to the request message * @return the payload of the reply message, possibly {@code null} if the message * could not be received, for example due to a timeout */ <T> @Nullable T convertSendAndReceive(String destinationName, Object request, @Nullable Map<String, Object> headers, Class<T> targetClass, @Nullable MessagePostProcessor requestPostProcessor) throws MessagingException; }
to
java
apache__camel
components/camel-pqc/src/test/java/org/apache/camel/component/pqc/PQCMLKEMGenerateEncapsulationAESTest.java
{ "start": 1626, "end": 4900 }
class ____ extends CamelTestSupport { @EndpointInject("mock:encapsulate") protected MockEndpoint resultEncapsulate; @Produce("direct:encapsulate") protected ProducerTemplate templateEncapsulate; @EndpointInject("mock:extract") protected MockEndpoint resultExtract; public PQCMLKEMGenerateEncapsulationAESTest() throws NoSuchAlgorithmException { } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:encapsulate").to("pqc:keyenc?operation=generateSecretKeyEncapsulation&symmetricKeyAlgorithm=AES") .to("mock:encapsulate") .to("pqc:keyenc?operation=extractSecretKeyEncapsulation&symmetricKeyAlgorithm=AES").to("mock:extract"); } }; } @BeforeAll public static void startup() throws Exception { Security.addProvider(new BouncyCastleProvider()); Security.addProvider(new BouncyCastlePQCProvider()); } @Test void testSignAndVerify() throws Exception { resultEncapsulate.expectedMessageCount(1); resultExtract.expectedMessageCount(1); templateEncapsulate.sendBody("Hello"); resultEncapsulate.assertIsSatisfied(); assertNotNull(resultEncapsulate.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class)); assertEquals(PQCSymmetricAlgorithms.AES.getAlgorithm(), resultEncapsulate.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class).getAlgorithm()); SecretKeyWithEncapsulation secEncrypted = resultEncapsulate.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class); assertNotNull(resultExtract.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class)); assertEquals(PQCSymmetricAlgorithms.AES.getAlgorithm(), resultExtract.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class).getAlgorithm()); SecretKeyWithEncapsulation secEncryptedExtracted = resultExtract.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class); assertTrue(Arrays.areEqual(secEncrypted.getEncoded(), secEncryptedExtracted.getEncoded())); } @BindToRegistry("Keypair") public KeyPair setKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { KeyPairGenerator kpg = KeyPairGenerator.getInstance(PQCKeyEncapsulationAlgorithms.MLKEM.getAlgorithm(), PQCKeyEncapsulationAlgorithms.MLKEM.getBcProvider()); kpg.initialize(MLKEMParameterSpec.ml_kem_512, new SecureRandom()); KeyPair kp = kpg.generateKeyPair(); return kp; } @BindToRegistry("KeyGenerator") public KeyGenerator setKeyGenerator() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { KeyGenerator kg = KeyGenerator.getInstance(PQCKeyEncapsulationAlgorithms.MLKEM.getAlgorithm(), PQCKeyEncapsulationAlgorithms.MLKEM.getBcProvider()); return kg; } }
PQCMLKEMGenerateEncapsulationAESTest
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmConfigPersistenceUnit.java
{ "start": 19840, "end": 21363 }
enum ____ { /** * Assumes the value retrieved from the table/sequence is the lower end of the pool. * * Upon retrieving value `N`, the new pool of identifiers will go from `N` to `N + <allocation size> - 1`, inclusive. * * @asciidoclet */ POOLED_LO(StandardOptimizerDescriptor.POOLED_LO), /** * Assumes the value retrieved from the table/sequence is the higher end of the pool. * * Upon retrieving value `N`, the new pool of identifiers will go from `N - <allocation size>` to `N + <allocation size> * - 1`, inclusive. * * The first value, `1`, is handled differently to avoid negative identifiers. * * Use this to get the legacy behavior of Quarkus 2 / Hibernate ORM 5 or older. * * @asciidoclet */ POOLED(StandardOptimizerDescriptor.POOLED), /** * No optimizer, resulting in a database call each and every time an identifier value is needed from the generator. * * Not recommended in production environments: * may result in degraded performance and/or frequent gaps in identifier values. * * @asciidoclet */ NONE(StandardOptimizerDescriptor.NONE); public final String configName; IdOptimizerType(StandardOptimizerDescriptor delegate) { configName = delegate.getExternalName(); } } @ConfigGroup
IdOptimizerType
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/xcontent/ChunkedToXContent.java
{ "start": 1199, "end": 5640 }
interface ____ { /** * Create an iterator of {@link ToXContent} chunks for a REST response for the given {@link RestApiVersion}. Each chunk is serialized * with the same {@link XContentBuilder} and {@link ToXContent.Params}, which is also the same as the {@link ToXContent.Params} passed * as the {@code params} argument. For best results, all chunks should be {@code O(1)} size. The last chunk in the iterator must always * yield at least one byte of output. See also {@link ChunkedToXContentHelper} for some handy utilities. * <p> * Note that chunked response bodies cannot send deprecation warning headers once transmission has started, so implementations must * check for deprecated feature use before returning. * <p> * By default, delegates to {@link #toXContentChunked} or {#toXContentChunkedV8}. * * @return iterator over chunks of {@link ToXContent} */ default Iterator<? extends ToXContent> toXContentChunked(RestApiVersion restApiVersion, ToXContent.Params params) { return switch (restApiVersion) { case V_8 -> toXContentChunkedV8(params); case V_9 -> toXContentChunked(params); }; } /** * Create an iterator of {@link ToXContent} chunks for a REST response. Each chunk is serialized with the same {@link XContentBuilder} * and {@link ToXContent.Params}, which is also the same as the {@link ToXContent.Params} passed as the {@code params} argument. For * best results, all chunks should be {@code O(1)} size. The last chunk in the iterator must always yield at least one byte of output. * See also {@link ChunkedToXContentHelper} for some handy utilities. * <p> * Note that chunked response bodies cannot send deprecation warning headers once transmission has started, so implementations must * check for deprecated feature use before returning. * * @return iterator over chunks of {@link ToXContent} */ Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params params); /** * Create an iterator of {@link ToXContent} chunks for a response to the {@link RestApiVersion#V_8} API. Each chunk is serialized with * the same {@link XContentBuilder} and {@link ToXContent.Params}, which is also the same as the {@link ToXContent.Params} passed as the * {@code params} argument. For best results, all chunks should be {@code O(1)} size. The last chunk in the iterator must always yield * at least one byte of output. See also {@link ChunkedToXContentHelper} for some handy utilities. * <p> * Similar to {@link #toXContentChunked} but for the {@link RestApiVersion#V_8} API. By default this method delegates to {@link * #toXContentChunked}. * <p> * Note that chunked response bodies cannot send deprecation warning headers once transmission has started, so implementations must * check for deprecated feature use before returning. * * @return iterator over chunks of {@link ToXContent} */ default Iterator<? extends ToXContent> toXContentChunkedV8(ToXContent.Params params) { return toXContentChunked(params); } /** * Wraps the given instance in a {@link ToXContent} that will fully serialize the instance when serialized. * * @param chunkedToXContent instance to wrap * @return x-content instance */ static ToXContent wrapAsToXContent(ChunkedToXContent chunkedToXContent) { return new ToXContent() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { Iterator<? extends ToXContent> serialization = chunkedToXContent.toXContentChunked(params); while (serialization.hasNext()) { serialization.next().toXContent(builder, params); } return builder; } @Override public boolean isFragment() { return chunkedToXContent.isFragment(); } }; } /** * @return true iff this instance serializes as a fragment. See {@link ToXContentObject} for additional details. */ default boolean isFragment() { return true; } /** * A {@link ChunkedToXContent} that yields no chunks */ ChunkedToXContent EMPTY = params -> Collections.emptyIterator(); }
ChunkedToXContent
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/writing/FactoryGenerator.java
{ "start": 5755, "end": 8514 }
class ____ extends SourceFileGenerator<ContributionBinding> { private static final ImmutableSet<BindingKind> VALID_BINDING_KINDS = ImmutableSet.of(BindingKind.INJECTION, BindingKind.ASSISTED_INJECTION, BindingKind.PROVISION); private final CompilerOptions compilerOptions; private final SourceFiles sourceFiles; @Inject FactoryGenerator( XFiler filer, CompilerOptions compilerOptions, SourceFiles sourceFiles, XProcessingEnv processingEnv) { super(filer, processingEnv); this.compilerOptions = compilerOptions; this.sourceFiles = sourceFiles; } @Override public XElement originatingElement(ContributionBinding binding) { // we only create factories for bindings that have a binding element return binding.bindingElement().get(); } @Override public ImmutableList<XTypeSpec> topLevelTypes(ContributionBinding binding) { // We don't want to write out resolved bindings -- we want to write out the generic version. checkArgument(!binding.unresolved().isPresent()); checkArgument(binding.bindingElement().isPresent()); checkArgument(VALID_BINDING_KINDS.contains(binding.kind())); return ImmutableList.of(factoryBuilder(binding)); } private XTypeSpec factoryBuilder(ContributionBinding binding) { XTypeSpecs.Builder factoryBuilder = XTypeSpecs.classBuilder(generatedClassNameForBinding(binding)) .addModifiers(PUBLIC, FINAL) .addTypeVariableNames(bindingTypeElementTypeVariableNames(binding)) .addAnnotation(scopeMetadataAnnotation(binding)) .addAnnotation(qualifierMetadataAnnotation(binding)); factoryTypeName(binding).ifPresent(factoryBuilder::addSuperinterface); FactoryFields factoryFields = FactoryFields.create(binding, compilerOptions); // If the factory has no input fields we can use a static instance holder to create a // singleton instance of the factory. Otherwise, we create a new instance via the constructor. if (useStaticInstanceHolder(binding, factoryFields)) { factoryBuilder.addType(staticInstanceHolderType(binding)); } else { factoryBuilder .addProperties(factoryFields.getAll()) .addFunction(constructorMethod(factoryFields)); } gwtIncompatibleAnnotation(binding).ifPresent(factoryBuilder::addAnnotation); return factoryBuilder .addFunction(getMethod(binding, factoryFields)) .addFunction(staticCreateMethod(binding, factoryFields)) .addFunction(staticProxyMethod(binding)) .build(); } private boolean useStaticInstanceHolder( ContributionBinding binding, FactoryFields factoryFields) { return factoryFields.isEmpty(); } // private static final
FactoryGenerator
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java
{ "start": 68139, "end": 68636 }
class ____ implements WebFilter { private final ReactiveSessionRegistry sessionRegistry; private SessionRegistryWebFilter(ReactiveSessionRegistry sessionRegistry) { Assert.notNull(sessionRegistry, "sessionRegistry cannot be null"); this.sessionRegistry = sessionRegistry; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return chain.filter(new SessionRegistryWebExchange(exchange)); } private final
SessionRegistryWebFilter
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/model/GlobalOptionsDefinitionTest.java
{ "start": 1079, "end": 3446 }
class ____ { private static final String LOG_DEBUG_BODY_MAX_CHARS_VALUE = "500"; private static final String LOG_DEBUG_BODY_MAX_CHARS_DUP_VALUE = "400"; private GlobalOptionsDefinition instance; private List<GlobalOptionDefinition> globalOptions; private GlobalOptionDefinition nominalOption; private GlobalOptionDefinition duplicateOption; @BeforeEach public void setup() { nominalOption = new GlobalOptionDefinition(); nominalOption.setKey(Exchange.LOG_DEBUG_BODY_MAX_CHARS); nominalOption.setValue(LOG_DEBUG_BODY_MAX_CHARS_VALUE); duplicateOption = new GlobalOptionDefinition(); duplicateOption.setKey(Exchange.LOG_DEBUG_BODY_MAX_CHARS); duplicateOption.setValue(LOG_DEBUG_BODY_MAX_CHARS_DUP_VALUE); globalOptions = new ArrayList<>(); globalOptions.add(nominalOption); instance = new GlobalOptionsDefinition(); instance.setGlobalOptions(globalOptions); } @Test public void asMapShouldCarryOnLogDebugMaxChars() { Map<String, String> map = instance.asMap(); assertNotNull(map); assertEquals(1, map.size()); assertEquals(LOG_DEBUG_BODY_MAX_CHARS_VALUE, map.get(Exchange.LOG_DEBUG_BODY_MAX_CHARS)); } @Test public void asMapWithDuplicateKeyShouldOverride() { globalOptions.add(duplicateOption); Map<String, String> map = instance.asMap(); assertNotNull(map); assertEquals(1, map.size()); assertEquals(LOG_DEBUG_BODY_MAX_CHARS_DUP_VALUE, map.get(Exchange.LOG_DEBUG_BODY_MAX_CHARS)); } @Test public void asMapWithNullGlobalOptionsShouldThrowNullPointerException() { instance.setGlobalOptions(null); assertThrows(NullPointerException.class, () -> instance.asMap()); } @Test public void asMapWithEmptyGlobalOptionsShouldReturnEmptyMap() { globalOptions.clear(); Map<String, String> map = instance.asMap(); assertNotNull(map); assertEquals(0, map.size()); } @Test public void asMapWithNullKeyShouldReturnEmptyMap() { nominalOption.setKey(null); Map<String, String> map = instance.asMap(); assertNotNull(map); assertEquals(1, map.size()); assertEquals(LOG_DEBUG_BODY_MAX_CHARS_VALUE, map.get(null)); } }
GlobalOptionsDefinitionTest
java
apache__camel
components/camel-mock/src/main/java/org/apache/camel/component/mock/AssertionClause.java
{ "start": 1236, "end": 4489 }
class ____ extends MockExpressionClauseSupport<MockValueBuilder> implements Runnable { protected final MockEndpoint mock; protected volatile int currentIndex; private final Set<Predicate> predicates = new LinkedHashSet<>(); private final Expression previous = new PreviousTimestamp(); private final Expression next = new NextTimestamp(); protected AssertionClause(MockEndpoint mock) { super(null); this.mock = mock; } // Builder methods // ------------------------------------------------------------------------- @Override public MockValueBuilder expression(Expression expression) { // must override this method as we provide null in the constructor super.expression(expression); return new PredicateValueBuilder(expression); } @Override public MockValueBuilder language(ExpressionFactory expression) { // must override this method as we provide null in the constructor super.expression(expression.createExpression(mock.getCamelContext())); return new PredicateValueBuilder(getExpressionValue()); } /** * Adds the given predicate to this assertion clause */ public AssertionClause predicate(Predicate predicate) { addPredicate(predicate); return this; } /** * Adds the given predicate to this assertion clause */ public MockExpressionClause<AssertionClause> predicate() { MockExpressionClause<AssertionClause> clause = new MockExpressionClause<>(this); addPredicate(clause); return clause; } /** * Adds a {@link TimeClause} predicate for the message arriving. */ public TimeClause arrives() { final TimeClause clause = new TimeClause(previous, next); addPredicate(new Predicate() { public boolean matches(Exchange exchange) { return clause.matches(exchange); } @Override public String toString() { return "arrives " + clause.toString() + " exchange"; } }); return clause; } /** * Performs any assertions on the given exchange */ protected void applyAssertionOn(MockEndpoint endpoint, int index, Exchange exchange) { for (Predicate predicate : predicates) { currentIndex = index; if (exchange != null) { Object value = exchange.getMessage().getBody(); // if the value is StreamCache then ensure It's readable before evaluating any predicates // by resetting it (this is also what StreamCachingAdvice does) if (value instanceof StreamCache streamCache) { streamCache.reset(); } } predicate.init(endpoint.getCamelContext()); PredicateAssertHelper.assertMatches(predicate, "Assertion error at index " + index + " on mock " + endpoint.getEndpointUri() + " with predicate: ", exchange); } } protected void addPredicate(Predicate predicate) { predicates.add(predicate); } @SuppressWarnings("unchecked") private final
AssertionClause
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GitEndpointBuilderFactory.java
{ "start": 45308, "end": 45610 }
class ____ extends AbstractEndpointBuilder implements GitEndpointBuilder, AdvancedGitEndpointBuilder { public GitEndpointBuilderImpl(String path) { super(componentName, path); } } return new GitEndpointBuilderImpl(path); } }
GitEndpointBuilderImpl
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/reflect/TestReflect.java
{ "start": 41562, "end": 42822 }
class ____ { @AvroAlias(alias = "aliasName", space = "forbidden.space.entry") int primitiveField; } @Test void avroAliasOnField() { Schema expectedSchema = SchemaBuilder.record(ClassWithAliasOnField.class.getSimpleName()) .namespace("org.apache.avro.reflect.TestReflect").fields().name("primitiveField").aliases("aliasName") .type(Schema.create(org.apache.avro.Schema.Type.INT)).noDefault().endRecord(); check(ClassWithAliasOnField.class, expectedSchema.toString()); } @Test void namespaceDefinitionOnFieldAliasMustThrowException() { assertThrows(AvroRuntimeException.class, () -> { ReflectData.get().getSchema(ClassWithAliasAndNamespaceOnField.class); }); } @Test public void testMultipleFieldAliases() { Field field = new Field("primitiveField", Schema.create(Schema.Type.INT)); field.addAlias("alias1"); field.addAlias("alias2"); Schema avroMultiMeta = Schema.createRecord("ClassWithMultipleAliasesOnField", null, "org.apache.avro.reflect.TestReflect", false, Arrays.asList(field)); Schema schema = ReflectData.get().getSchema(ClassWithMultipleAliasesOnField.class); assertEquals(avroMultiMeta, schema); } private static
ClassWithAliasAndNamespaceOnField
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/OfflineAggregationWriter.java
{ "start": 1556, "end": 2885 }
class ____ extends AbstractService { /** * Construct the offline writer. * * @param name service name */ public OfflineAggregationWriter(String name) { super(name); } /** * Persist aggregated timeline entities to the offline store based on which * track this entity is to be rolled up to. The tracks along which * aggregations are to be done are given by {@link OfflineAggregationInfo}. * * @param context a {@link TimelineCollectorContext} object that describes the * context information of the aggregated data. Depends on the * type of the aggregation, some fields of this context maybe * empty or null. * @param entities {@link TimelineEntities} to be persisted. * @param info an {@link OfflineAggregationInfo} object that describes the * detail of the aggregation. Current supported option is * {@link OfflineAggregationInfo#FLOW_AGGREGATION}. * @return a {@link TimelineWriteResponse} object. * @throws IOException if any problem occurs while writing aggregated * entities. */ abstract TimelineWriteResponse writeAggregatedEntity( TimelineCollectorContext context, TimelineEntities entities, OfflineAggregationInfo info) throws IOException; }
OfflineAggregationWriter
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/kstream/ValueJoinerWithKey.java
{ "start": 958, "end": 2453 }
interface ____ access to a read-only key that the user should not modify as this would lead to * undefined behavior * This is a stateless operation, i.e, {@link #apply(Object, Object, Object)} is invoked individually for each joining * record-pair of a {@link KStream}-{@link KStream}, {@link KStream}-{@link KTable}, or {@link KTable}-{@link KTable} * join. * * @param <K1> key value type * @param <V1> first value type * @param <V2> second value type * @param <VR> joined value type * @see KStream#join(KStream, ValueJoinerWithKey, JoinWindows) * @see KStream#join(KStream, ValueJoinerWithKey, JoinWindows, StreamJoined) * @see KStream#leftJoin(KStream, ValueJoinerWithKey, JoinWindows) * @see KStream#leftJoin(KStream, ValueJoinerWithKey, JoinWindows, StreamJoined) * @see KStream#outerJoin(KStream, ValueJoinerWithKey, JoinWindows) * @see KStream#outerJoin(KStream, ValueJoinerWithKey, JoinWindows, StreamJoined) * @see KStream#join(KTable, ValueJoinerWithKey) * @see KStream#join(KTable, ValueJoinerWithKey, Joined) * @see KStream#leftJoin(KTable, ValueJoinerWithKey) * @see KStream#leftJoin(KTable, ValueJoinerWithKey, Joined) * @see KStream#join(GlobalKTable, KeyValueMapper, ValueJoinerWithKey) * @see KStream#join(GlobalKTable, KeyValueMapper, ValueJoinerWithKey, Named) * @see KStream#leftJoin(GlobalKTable, KeyValueMapper, ValueJoinerWithKey) * @see KStream#leftJoin(GlobalKTable, KeyValueMapper, ValueJoinerWithKey, Named) */ @FunctionalInterface public
provides
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/SortedNumericDocValuesSyntheticFieldLoader.java
{ "start": 6433, "end": 8476 }
class ____ implements DocValuesLoader, Values { private final int[] docIdsInLeaf; private final long[] values; private final boolean[] hasValue; private int idx = -1; private SingletonDocValuesLoader(int[] docIdsInLeaf, long[] values, boolean[] hasValue) { this.docIdsInLeaf = docIdsInLeaf; this.values = values; this.hasValue = hasValue; } @Override public boolean advanceToDoc(int docId) throws IOException { idx++; if (docIdsInLeaf[idx] != docId) { throw new IllegalArgumentException( "expected to be called with [" + docIdsInLeaf[idx] + "] but was called with " + docId + " instead" ); } return hasValue[idx]; } @Override public int count() { return hasValue[idx] ? 1 : 0; } @Override public void write(XContentBuilder b) throws IOException { if (hasValue[idx] == false) { return; } writeValue(b, values[idx]); } } /** * Returns a {@link SortedNumericDocValues} or null if it doesn't have any doc values. * See {@link DocValues#getSortedNumeric} which is *nearly* the same, but it returns * an "empty" implementation if there aren't any doc values. We need to be able to * tell if there aren't any and return our empty leaf source loader. */ public static SortedNumericDocValues docValuesOrNull(LeafReader reader, String fieldName) throws IOException { SortedNumericDocValues dv = reader.getSortedNumericDocValues(fieldName); if (dv != null) { return dv; } NumericDocValues single = reader.getNumericDocValues(fieldName); if (single != null) { return DocValues.singleton(single); } return null; } @Override public String fieldName() { return name; } }
SingletonDocValuesLoader
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/TestData.java
{ "start": 11747, "end": 12688 }
class ____<T extends Tuple> implements TypeSerializerFactory<T> { private final TupleTypeInfo<T> info; public MockTupleSerializerFactory(TupleTypeInfo<T> info) { this.info = info; } @Override public void writeParametersToConfig(Configuration config) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void readParametersFromConfig(Configuration config, ClassLoader cl) throws ClassNotFoundException { throw new UnsupportedOperationException("Not supported yet."); } @Override public TypeSerializer<T> getSerializer() { return info.createSerializer((SerializerConfig) null); } @Override public Class<T> getDataType() { return info.getTypeClass(); } } public static
MockTupleSerializerFactory
java
spring-projects__spring-boot
core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/DefaultConnectionPortsTests.java
{ "start": 2175, "end": 2977 }
class ____ { @Test void parse() { ContainerPort port = ContainerPort.parse("123/tcp"); assertThat(port).isEqualTo(new ContainerPort(123, "tcp")); } @Test void parseWhenNoSlashThrowsException() { assertThatIllegalStateException().isThrownBy(() -> ContainerPort.parse("123")) .withMessage("Unable to parse container port '123'"); } @Test void parseWhenMultipleSlashesThrowsException() { assertThatIllegalStateException().isThrownBy(() -> ContainerPort.parse("123/tcp/ip")) .withMessage("Unable to parse container port '123/tcp/ip'"); } @Test void parseWhenNotNumberThrowsException() { assertThatIllegalStateException().isThrownBy(() -> ContainerPort.parse("tcp/123")) .withMessage("Unable to parse container port 'tcp/123'"); } } }
ContainerPortTests
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindHandlerAdvisorTests.java
{ "start": 6364, "end": 6800 }
class ____ { private @Nullable String destination; private String contentType = "application/json"; @Nullable String getDestination() { return this.destination; } void setDestination(@Nullable String destination) { this.destination = destination; } String getContentType() { return this.contentType; } void setContentType(String contentType) { this.contentType = contentType; } } }
BindingProperties
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationPerformanceTests.java
{ "start": 22014, "end": 22180 }
class ____ { public Bar bar = new Bar(); Bar b = new Bar(); public Bar getBaz() { return b; } public Bar bay() { return b; } } public static
Foo
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/Node.java
{ "start": 1059, "end": 3460 }
class ____ { /** * Main plugin category for plugins which are represented as a configuration node. Such plugins tend to be * available as XML elements in a configuration file. * * @since 2.1 */ public static final String CATEGORY = "Core"; private Node parent; private final String name; private String value; private final PluginType<?> type; private final Map<String, String> attributes = new HashMap<>(); private final List<Node> children = new ArrayList<>(); private Object object; /** * Creates a new instance of {@code Node} and initializes it * with a name and the corresponding XML element. * * @param parent the node's parent. * @param name the node's name. * @param type The Plugin Type associated with the node. */ public Node(final Node parent, final String name, final PluginType<?> type) { this.parent = parent; this.name = name; this.type = type; } public Node() { this.parent = null; this.name = null; this.type = null; } public Node(final Node node) { this.parent = node.parent; this.name = node.name; this.type = node.type; this.attributes.putAll(node.getAttributes()); this.value = node.getValue(); for (final Node child : node.getChildren()) { this.children.add(new Node(child)); } this.object = node.object; } public void setParent(final Node parent) { this.parent = parent; } public Map<String, String> getAttributes() { return attributes; } public List<Node> getChildren() { return children; } public boolean hasChildren() { return !children.isEmpty(); } public String getValue() { return value; } public void setValue(final String value) { this.value = value; } public Node getParent() { return parent; } public String getName() { return name; } public boolean isRoot() { return parent == null; } public void setObject(final Object obj) { object = obj; } @SuppressWarnings("unchecked") public <T> T getObject() { return (T) object; } /** * Returns this node's object cast to the given class. * * @param clazz the
Node
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/bcextensions/MethodConfigImpl.java
{ "start": 332, "end": 1278 }
class ____ extends DeclarationConfigImpl<org.jboss.jandex.MethodInfo, MethodConfigImpl> implements MethodConfig { MethodConfigImpl(org.jboss.jandex.IndexView jandexIndex, org.jboss.jandex.MutableAnnotationOverlay annotationOverlay, org.jboss.jandex.MethodInfo jandexDeclaration) { super(jandexIndex, annotationOverlay, jandexDeclaration); } @Override public MethodInfo info() { return new MethodInfoImpl(jandexIndex, annotationOverlay, jandexDeclaration); } @Override public List<ParameterConfig> parameters() { List<ParameterConfig> result = new ArrayList<>(jandexDeclaration.parametersCount()); for (org.jboss.jandex.MethodParameterInfo jandexParameter : jandexDeclaration.parameters()) { result.add(new ParameterConfigImpl(jandexIndex, annotationOverlay, jandexParameter)); } return Collections.unmodifiableList(result); } }
MethodConfigImpl
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/codec/ArrayTextCodecTest.java
{ "start": 1359, "end": 1626 }
class ____ { // The default JsonTextMessageCodec is used @OnOpen Item[] open() { Item item = new Item(); item.setName("Foo"); item.setCount(1); return new Item[] { item }; } } }
Endpont
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/HttpServer.java
{ "start": 5289, "end": 6687 }
class ____ { private int port; private String username; private String password; private StreamSource source; public HttpServerBuilder port(int port) { this.port = port; return this; } public HttpServerBuilder username(String username) { this.username = username; return this; } public HttpServerBuilder password(String password) { this.password = password; return this; } public HttpServerBuilder source(final String source) { this.source = new StreamSource() { @Override public InputStream stream(String path) throws IOException { return new URL(String.format("%s/%s", source, path)).openStream(); } }; return this; } public HttpServerBuilder source(final File source) { this.source = new StreamSource() { @Override public InputStream stream(String path) throws IOException { return new FileInputStream(new File(source, path)); } }; return this; } public HttpServer build() { return new HttpServer(port, username, password, source); } } public
HttpServerBuilder
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/XmppEndpointBuilderFactory.java
{ "start": 35729, "end": 44259 }
interface ____ extends XmppEndpointConsumerBuilder, XmppEndpointProducerBuilder { default AdvancedXmppEndpointBuilder advanced() { return (AdvancedXmppEndpointBuilder) this; } /** * Whether to login the user. * * The option is a: <code>boolean</code> type. * * Default: true * Group: common * * @param login the value to set * @return the dsl builder */ default XmppEndpointBuilder login(boolean login) { doSetProperty("login", login); return this; } /** * Whether to login the user. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: common * * @param login the value to set * @return the dsl builder */ default XmppEndpointBuilder login(String login) { doSetProperty("login", login); return this; } /** * Use nickname when joining room. If room is specified and nickname is * not, user will be used for the nickname. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param nickname the value to set * @return the dsl builder */ default XmppEndpointBuilder nickname(String nickname) { doSetProperty("nickname", nickname); return this; } /** * Accept pubsub packets on input, default is false. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param pubsub the value to set * @return the dsl builder */ default XmppEndpointBuilder pubsub(boolean pubsub) { doSetProperty("pubsub", pubsub); return this; } /** * Accept pubsub packets on input, default is false. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param pubsub the value to set * @return the dsl builder */ default XmppEndpointBuilder pubsub(String pubsub) { doSetProperty("pubsub", pubsub); return this; } /** * If this option is specified, the component will connect to MUC (Multi * User Chat). Usually, the domain name for MUC is different from the * login domain. For example, if you are supermanjabber.org and want to * join the krypton room, then the room URL is * kryptonconference.jabber.org. Note the conference part. It is not a * requirement to provide the full room JID. If the room parameter does * not contain the symbol, the domain part will be discovered and added * by Camel. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param room the value to set * @return the dsl builder */ default XmppEndpointBuilder room(String room) { doSetProperty("room", room); return this; } /** * The name of the service you are connecting to. For Google Talk, this * would be gmail.com. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param serviceName the value to set * @return the dsl builder */ default XmppEndpointBuilder serviceName(String serviceName) { doSetProperty("serviceName", serviceName); return this; } /** * Specifies whether to test the connection on startup. This is used to * ensure that the XMPP client has a valid connection to the XMPP server * when the route starts. Camel throws an exception on startup if a * connection cannot be established. When this option is set to false, * Camel will attempt to establish a lazy connection when needed by a * producer, and will poll for a consumer connection until the * connection is established. Default is true. * * The option is a: <code>boolean</code> type. * * Default: true * Group: common * * @param testConnectionOnStartup the value to set * @return the dsl builder */ default XmppEndpointBuilder testConnectionOnStartup(boolean testConnectionOnStartup) { doSetProperty("testConnectionOnStartup", testConnectionOnStartup); return this; } /** * Specifies whether to test the connection on startup. This is used to * ensure that the XMPP client has a valid connection to the XMPP server * when the route starts. Camel throws an exception on startup if a * connection cannot be established. When this option is set to false, * Camel will attempt to establish a lazy connection when needed by a * producer, and will poll for a consumer connection until the * connection is established. Default is true. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: common * * @param testConnectionOnStartup the value to set * @return the dsl builder */ default XmppEndpointBuilder testConnectionOnStartup(String testConnectionOnStartup) { doSetProperty("testConnectionOnStartup", testConnectionOnStartup); return this; } /** * To use a custom HeaderFilterStrategy to filter header to and from * Camel message. * * The option is a: * <code>org.apache.camel.spi.HeaderFilterStrategy</code> type. * * Group: filter * * @param headerFilterStrategy the value to set * @return the dsl builder */ default XmppEndpointBuilder headerFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy headerFilterStrategy) { doSetProperty("headerFilterStrategy", headerFilterStrategy); return this; } /** * To use a custom HeaderFilterStrategy to filter header to and from * Camel message. * * The option will be converted to a * <code>org.apache.camel.spi.HeaderFilterStrategy</code> type. * * Group: filter * * @param headerFilterStrategy the value to set * @return the dsl builder */ default XmppEndpointBuilder headerFilterStrategy(String headerFilterStrategy) { doSetProperty("headerFilterStrategy", headerFilterStrategy); return this; } /** * Password for login. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param password the value to set * @return the dsl builder */ default XmppEndpointBuilder password(String password) { doSetProperty("password", password); return this; } /** * Password for room. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param roomPassword the value to set * @return the dsl builder */ default XmppEndpointBuilder roomPassword(String roomPassword) { doSetProperty("roomPassword", roomPassword); return this; } /** * User name (without server name). If not specified, anonymous login * will be attempted. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param user the value to set * @return the dsl builder */ default XmppEndpointBuilder user(String user) { doSetProperty("user", user); return this; } } /** * Advanced builder for endpoint for the XMPP component. */ public
XmppEndpointBuilder
java
netty__netty
example/src/main/java/io/netty/example/dns/tcp/TcpDnsServer.java
{ "start": 2287, "end": 8256 }
class ____ { private static final String QUERY_DOMAIN = "www.example.com"; private static final int DNS_SERVER_PORT = 53; private static final String DNS_SERVER_HOST = "127.0.0.1"; private static final byte[] QUERY_RESULT = new byte[]{(byte) 192, (byte) 168, 1, 1}; public static void main(String[] args) throws Exception { ServerBootstrap bootstrap = new ServerBootstrap().group( new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory())) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new TcpDnsQueryDecoder(), new TcpDnsResponseEncoder(), new SimpleChannelInboundHandler<DnsQuery>() { @Override protected void channelRead0(ChannelHandlerContext ctx, DnsQuery msg) throws Exception { DnsQuestion question = msg.recordAt(DnsSection.QUESTION); System.out.println("Query domain: " + question); //always return 192.168.1.1 ctx.writeAndFlush(newResponse(msg, question, 600, QUERY_RESULT)); } private DefaultDnsResponse newResponse(DnsQuery query, DnsQuestion question, long ttl, byte[]... addresses) { DefaultDnsResponse response = new DefaultDnsResponse(query.id()); response.addRecord(DnsSection.QUESTION, question); for (byte[] address : addresses) { DefaultDnsRawRecord queryAnswer = new DefaultDnsRawRecord( question.name(), DnsRecordType.A, ttl, Unpooled.wrappedBuffer(address)); response.addRecord(DnsSection.ANSWER, queryAnswer); } return response; } }); } }); final Channel channel = bootstrap.bind(DNS_SERVER_PORT).channel(); Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() { @Override public void run() { try { clientQuery(); channel.close(); } catch (Exception e) { e.printStackTrace(); } } }, 1000, TimeUnit.MILLISECONDS); channel.closeFuture().sync(); } // copy from TcpDnsClient.java private static void clientQuery() throws Exception { EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new TcpDnsQueryEncoder()) .addLast(new TcpDnsResponseDecoder()) .addLast(new SimpleChannelInboundHandler<DefaultDnsResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, DefaultDnsResponse msg) { try { handleQueryResp(msg); } finally { ctx.close(); } } }); } }); final Channel ch = b.connect(DNS_SERVER_HOST, DNS_SERVER_PORT).sync().channel(); int randomID = new Random().nextInt(60000 - 1000) + 1000; DnsQuery query = new DefaultDnsQuery(randomID, DnsOpCode.QUERY) .setRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A)); ch.writeAndFlush(query).sync(); boolean success = ch.closeFuture().await(10, TimeUnit.SECONDS); if (!success) { System.err.println("dns query timeout!"); ch.close().sync(); } } finally { group.shutdownGracefully(); } } private static void handleQueryResp(DefaultDnsResponse msg) { if (msg.count(DnsSection.QUESTION) > 0) { DnsQuestion question = msg.recordAt(DnsSection.QUESTION, 0); System.out.printf("name: %s%n", question.name()); } for (int i = 0, count = msg.count(DnsSection.ANSWER); i < count; i++) { DnsRecord record = msg.recordAt(DnsSection.ANSWER, i); if (record.type() == DnsRecordType.A) { //just print the IP after query DnsRawRecord raw = (DnsRawRecord) record; System.out.println(NetUtil.bytesToIpAddress(ByteBufUtil.getBytes(raw.content()))); } } } }
TcpDnsServer
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/file/ProducerMergedPartitionFileIndex.java
{ "start": 2665, "end": 7960 }
class ____ { private final Path indexFilePath; /** * The regions belonging to each subpartitions. * * <p>Note that the field can be accessed by the writing and reading IO thread, so the lock is * to ensure the thread safety. */ @GuardedBy("lock") private final FileDataIndexCache<FixedSizeRegion> indexCache; private final Object lock = new Object(); public ProducerMergedPartitionFileIndex( int numSubpartitions, Path indexFilePath, int regionGroupSizeInBytes, long numRetainedInMemoryRegionsMax) { this.indexFilePath = indexFilePath; this.indexCache = new FileDataIndexCache<>( numSubpartitions, indexFilePath, numRetainedInMemoryRegionsMax, new FileDataIndexSpilledRegionManagerImpl.Factory<>( regionGroupSizeInBytes, numRetainedInMemoryRegionsMax, FixedSizeRegion.REGION_SIZE, ProducerMergedPartitionFileDataIndexRegionHelper.INSTANCE)); } /** * Add buffers to the index. * * @param buffers to be added. Note, the provided buffers are required to be physically * consecutive and in the same order as in the file. */ void addBuffers(List<FlushedBuffer> buffers) { if (buffers.isEmpty()) { return; } Map<Integer, List<FixedSizeRegion>> convertedRegions = convertToRegions(buffers); synchronized (lock) { convertedRegions.forEach(indexCache::put); } } /** * Get the subpartition's {@link FixedSizeRegion} containing the specific buffer index. * * @param subpartitionId the subpartition id * @param bufferIndex the buffer index * @return the region containing the buffer index, or return emtpy if the region is not found. */ Optional<FixedSizeRegion> getRegion( TieredStorageSubpartitionId subpartitionId, int bufferIndex) { synchronized (lock) { return indexCache.get(subpartitionId.getSubpartitionId(), bufferIndex); } } void release() { synchronized (lock) { try { indexCache.close(); IOUtils.deleteFileQuietly(indexFilePath); } catch (IOException e) { ExceptionUtils.rethrow(e); } } } // ------------------------------------------------------------------------ // Internal Methods // ------------------------------------------------------------------------ private static Map<Integer, List<FixedSizeRegion>> convertToRegions( List<FlushedBuffer> buffers) { Map<Integer, List<FixedSizeRegion>> subpartitionRegionMap = new HashMap<>(); Iterator<FlushedBuffer> iterator = buffers.iterator(); FlushedBuffer firstBufferInRegion = iterator.next(); FlushedBuffer lastBufferInRegion = firstBufferInRegion; while (iterator.hasNext()) { FlushedBuffer currentBuffer = iterator.next(); if (currentBuffer.getSubpartitionId() != firstBufferInRegion.getSubpartitionId() || currentBuffer.getBufferIndex() != lastBufferInRegion.getBufferIndex() + 1) { // The current buffer belongs to a new region, add the current region to the map addRegionToMap(firstBufferInRegion, lastBufferInRegion, subpartitionRegionMap); firstBufferInRegion = currentBuffer; } lastBufferInRegion = currentBuffer; } // Add the last region to the map addRegionToMap(firstBufferInRegion, lastBufferInRegion, subpartitionRegionMap); return subpartitionRegionMap; } private static void addRegionToMap( FlushedBuffer firstBufferInRegion, FlushedBuffer lastBufferInRegion, Map<Integer, List<FixedSizeRegion>> subpartitionRegionMap) { checkArgument( firstBufferInRegion.getSubpartitionId() == lastBufferInRegion.getSubpartitionId()); checkArgument(firstBufferInRegion.getBufferIndex() <= lastBufferInRegion.getBufferIndex()); subpartitionRegionMap .computeIfAbsent(firstBufferInRegion.getSubpartitionId(), k -> new ArrayList<>()) .add( new FixedSizeRegion( firstBufferInRegion.getBufferIndex(), firstBufferInRegion.getFileOffset(), lastBufferInRegion.getFileOffset() + lastBufferInRegion.getBufferSizeBytes(), lastBufferInRegion.getBufferIndex() - firstBufferInRegion.getBufferIndex() + 1)); } // ------------------------------------------------------------------------ // Internal Classes // ------------------------------------------------------------------------ /** Represents a buffer to be flushed. */ static
ProducerMergedPartitionFileIndex
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/RouteScopedOnExceptionWithInterceptSendToEndpointIssueTest.java
{ "start": 1399, "end": 3306 }
class ____ extends ContextTestSupport { @Test public void testIssue() throws Exception { RouteDefinition route = context.getRouteDefinitions().get(0); AdviceWith.adviceWith(route, context, new AdviceWithRouteBuilder() { @Override public void configure() { interceptSendToEndpoint("seda:*").skipSendToOriginalEndpoint().throwException(new ConnectException("Forced")); } }); getMockEndpoint("mock:global").expectedMessageCount(0); getMockEndpoint("mock:seda").expectedMessageCount(0); // we fail all redeliveries so after that we send to mock:exhausted getMockEndpoint("mock:exhausted").expectedMessageCount(1); CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> template.sendBody("direct:start", "Hello World"), "Should thrown an exception"); ConnectException cause = assertIsInstanceOf(ConnectException.class, e.getCause()); assertEquals("Forced", cause.getMessage()); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { errorHandler(deadLetterChannel("mock:global").maximumRedeliveries(2).redeliveryDelay(5000)); from("direct:start") // no redelivery delay for faster unit tests .onException(ConnectException.class).maximumRedeliveries(5).redeliveryDelay(0).logRetryAttempted(true) .retryAttemptedLogLevel(LoggingLevel.WARN) // send to mock when we are exhausted .to("mock:exhausted").end().to("seda:foo"); } }; } }
RouteScopedOnExceptionWithInterceptSendToEndpointIssueTest
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/type/YearMonthTypeHandlerTest.java
{ "start": 1025, "end": 2734 }
class ____ extends BaseTypeHandlerTest { private static final TypeHandler<YearMonth> TYPE_HANDLER = new YearMonthTypeHandler(); private static final YearMonth INSTANT = YearMonth.now(); @Override @Test public void shouldSetParameter() throws Exception { TYPE_HANDLER.setParameter(ps, 1, INSTANT, null); verify(ps).setString(1, INSTANT.toString()); } @Override @Test public void shouldGetResultFromResultSetByName() throws Exception { when(rs.getString("column")).thenReturn(INSTANT.toString()); assertEquals(INSTANT, TYPE_HANDLER.getResult(rs, "column")); verify(rs, never()).wasNull(); } @Override @Test public void shouldGetResultNullFromResultSetByName() throws Exception { assertNull(TYPE_HANDLER.getResult(rs, "column")); verify(rs, never()).wasNull(); } @Override @Test public void shouldGetResultFromResultSetByPosition() throws Exception { when(rs.getString(1)).thenReturn(INSTANT.toString()); assertEquals(INSTANT, TYPE_HANDLER.getResult(rs, 1)); verify(rs, never()).wasNull(); } @Override @Test public void shouldGetResultNullFromResultSetByPosition() throws Exception { assertNull(TYPE_HANDLER.getResult(rs, 1)); verify(rs, never()).wasNull(); } @Override @Test public void shouldGetResultFromCallableStatement() throws Exception { when(cs.getString(1)).thenReturn(INSTANT.toString()); assertEquals(INSTANT, TYPE_HANDLER.getResult(cs, 1)); verify(cs, never()).wasNull(); } @Override @Test public void shouldGetResultNullFromCallableStatement() throws Exception { assertNull(TYPE_HANDLER.getResult(cs, 1)); verify(cs, never()).wasNull(); } }
YearMonthTypeHandlerTest
java
apache__kafka
server-common/src/main/java/org/apache/kafka/server/share/persister/InitializeShareGroupStateParameters.java
{ "start": 2141, "end": 2829 }
class ____ { private GroupTopicPartitionData<PartitionStateData> groupTopicPartitionData; public Builder setGroupTopicPartitionData(GroupTopicPartitionData<PartitionStateData> groupTopicPartitionData) { this.groupTopicPartitionData = groupTopicPartitionData; return this; } public InitializeShareGroupStateParameters build() { return new InitializeShareGroupStateParameters(this.groupTopicPartitionData); } } @Override public String toString() { return "InitializeShareGroupStateParameters{" + "groupTopicPartitionData=" + groupTopicPartitionData + '}'; } }
Builder
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/type/ClassKey.java
{ "start": 114, "end": 234 }
class ____, such as * {@link tools.jackson.databind.ValueSerializer}s. *<p> * The reason for having a separate key
values
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/internal/AbstractPojoInstantiator.java
{ "start": 359, "end": 997 }
class ____ implements Instantiator { private final Class<?> mappedPojoClass; private final boolean isAbstract; public AbstractPojoInstantiator(Class<?> mappedPojoClass) { this.mappedPojoClass = mappedPojoClass; this.isAbstract = isAbstractClass( mappedPojoClass ); } public Class<?> getMappedPojoClass() { return mappedPojoClass; } public boolean isAbstract() { return isAbstract; } @Override public boolean isInstance(Object object) { return mappedPojoClass.isInstance( object ); } @Override public boolean isSameClass(Object object) { return object.getClass() == mappedPojoClass; } }
AbstractPojoInstantiator
java
google__guice
core/test/com/google/inject/multibindings/ProvidesIntoTest.java
{ "start": 7692, "end": 8459 }
interface ____ { int[] value(); } public void testArrayKeys_unwrapValuesTrue() { Module m = new AbstractModule() { @ProvidesIntoMap @ArrayUnwrappedKey({1, 2}) String provideFoo() { return "foo"; } }; try { Guice.createInjector(MultibindingsScanner.asModule(), m); fail(); } catch (CreationException ce) { assertEquals(1, ce.getErrorMessages().size()); assertContains( ce.getMessage(), "Array types are not allowed in a MapKey with unwrapValue=true:" + " ProvidesIntoTest$ArrayUnwrappedKey", "at ProvidesIntoTest$14.provideFoo"); } } @MapKey(unwrapValue = false) @Retention(RUNTIME) @
ArrayUnwrappedKey
java
playframework__playframework
transport/client/play-ws/src/main/java/play/libs/ws/WSBodyWritables.java
{ "start": 409, "end": 904 }
interface ____ extends DefaultBodyWritables, XMLBodyWritables, JsonBodyWritables { default SourceBodyWritable multipartBody( Source<? super Http.MultipartFormData.Part<Source<ByteString, ?>>, ?> body) { String boundary = MultipartFormatter.randomBoundary(); Source<ByteString, ?> source = MultipartFormatter.transform(body, boundary); String contentType = "multipart/form-data; boundary=" + boundary; return new SourceBodyWritable(source, contentType); } }
WSBodyWritables
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/asyncio/AsyncIOTest.java
{ "start": 261, "end": 687 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(AsyncIOResource.class)) .withConfigurationResource("application-asyncio.properties"); @Test public void testAsyncIODoesNotBlock() { Assertions.assertEquals("OK", RestAssured.get("/asyncio").asString()); } }
AsyncIOTest
java
apache__camel
dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/main/java/org/apache/camel/dsl/yaml/deserializers/DataFormatsDefinitionDeserializer.java
{ "start": 2133, "end": 3499 }
class ____ extends YamlDeserializerSupport implements ConstructNode { @Override public Object construct(Node node) { final DataFormatsCustomizer customizer = new DataFormatsCustomizer(); final YamlDeserializationContext dc = getDeserializationContext(node); final YamlDeserializationContext resolver = (YamlDeserializationContext) node.getProperty(YamlDeserializationContext.class.getName()); if (resolver == null) { throw new YamlDeserializationException(node, "Unable to find YamlConstructor"); } final SequenceNode sn = asSequenceNode(node); for (Node item : sn.getValue()) { setDeserializationContext(item, dc); MappingNode mn = asMappingNode(item); for (NodeTuple nt : mn.getValue()) { String name = asText(nt.getKeyNode()); ConstructNode cn = resolver.resolve(mn, name); Object answer = cn.construct(nt.getValueNode()); if (answer instanceof DataFormatDefinition def) { if (dc != null) { def.setResource(dc.getResource()); } customizer.addDataFormat(def); } } } return customizer; } private static
DataFormatsDefinitionDeserializer
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/config/ConfigDef.java
{ "start": 53009, "end": 53773 }
class ____ implements Validator { final List<String> validStrings; private ValidString(List<String> validStrings) { this.validStrings = validStrings; } public static ValidString in(String... validStrings) { return new ValidString(Arrays.asList(validStrings)); } @Override public void ensureValid(String name, Object o) { String s = (String) o; if (!validStrings.contains(s)) { throw new ConfigException(name, o, "String must be one of: " + String.join(", ", validStrings)); } } public String toString() { return "[" + String.join(", ", validStrings) + "]"; } } public static
ValidString
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plugin/ClusterComputeHandler.java
{ "start": 2215, "end": 16147 }
class ____ implements TransportRequestHandler<ClusterComputeRequest> { private final ComputeService computeService; private final ExchangeService exchangeService; private final TransportService transportService; private final Executor esqlExecutor; private final DataNodeComputeHandler dataNodeComputeHandler; ClusterComputeHandler( ComputeService computeService, ExchangeService exchangeService, TransportService transportService, Executor esqlExecutor, DataNodeComputeHandler dataNodeComputeHandler ) { this.computeService = computeService; this.exchangeService = exchangeService; this.esqlExecutor = esqlExecutor; this.transportService = transportService; this.dataNodeComputeHandler = dataNodeComputeHandler; transportService.registerRequestHandler(ComputeService.CLUSTER_ACTION_NAME, esqlExecutor, ClusterComputeRequest::new, this); } void startComputeOnRemoteCluster( String sessionId, CancellableTask rootTask, Configuration configuration, PhysicalPlan plan, ExchangeSourceHandler exchangeSource, RemoteCluster cluster, Runnable cancelQueryOnFailure, EsqlExecutionInfo executionInfo, ActionListener<DriverCompletionInfo> listener ) { var queryPragmas = configuration.pragmas(); listener = ActionListener.runBefore(listener, exchangeSource.addEmptySink()::close); final var childSessionId = computeService.newChildSession(sessionId); final String clusterAlias = cluster.clusterAlias(); final AtomicBoolean pagesFetched = new AtomicBoolean(); final AtomicReference<ComputeResponse> finalResponse = new AtomicReference<>(); listener = listener.delegateResponse((l, e) -> { final boolean receivedResults = finalResponse.get() != null || pagesFetched.get(); if (executionInfo.shouldSkipOnFailure(clusterAlias) || (configuration.allowPartialResults() && EsqlCCSUtils.canAllowPartial(e))) { EsqlCCSUtils.markClusterWithFinalStateAndNoShards( executionInfo, clusterAlias, receivedResults ? EsqlExecutionInfo.Cluster.Status.PARTIAL : EsqlExecutionInfo.Cluster.Status.SKIPPED, e ); l.onResponse(DriverCompletionInfo.EMPTY); } else { l.onFailure(e); } }); ExchangeService.openExchange( transportService, cluster.connection, childSessionId, queryPragmas.exchangeBufferSize(), esqlExecutor, listener.delegateFailure((l, unused) -> { final CancellableTask groupTask; final Runnable onGroupFailure; boolean failFast = executionInfo.shouldSkipOnFailure(clusterAlias) == false && configuration.allowPartialResults() == false; if (failFast) { groupTask = rootTask; onGroupFailure = cancelQueryOnFailure; } else { try { groupTask = computeService.createGroupTask(rootTask, () -> "compute group: cluster [" + clusterAlias + "]"); } catch (TaskCancelledException e) { l.onFailure(e); return; } onGroupFailure = computeService.cancelQueryOnFailure(groupTask); l = ActionListener.runAfter(l, () -> transportService.getTaskManager().unregister(groupTask)); } try (var computeListener = new ComputeListener(transportService.getThreadPool(), onGroupFailure, l.map(completionInfo -> { updateExecutionInfo(executionInfo, clusterAlias, finalResponse.get()); return completionInfo; }))) { var remotePlan = new RemoteClusterPlan(plan, cluster.concreteIndices, cluster.originalIndices); var clusterRequest = new ClusterComputeRequest(clusterAlias, childSessionId, configuration, remotePlan); final ActionListener<ComputeResponse> clusterListener = computeListener.acquireCompute().map(r -> { finalResponse.set(r); return r.getCompletionInfo(); }); transportService.sendChildRequest( cluster.connection, ComputeService.CLUSTER_ACTION_NAME, clusterRequest, groupTask, TransportRequestOptions.EMPTY, new ActionListenerResponseHandler<>(clusterListener, ComputeResponse::new, esqlExecutor) ); var remoteSink = exchangeService.newRemoteSink(groupTask, childSessionId, transportService, cluster.connection); exchangeSource.addRemoteSink( remoteSink, failFast, () -> pagesFetched.set(true), queryPragmas.concurrentExchangeClients(), computeListener.acquireAvoid() ); } }) ); } private void updateExecutionInfo(EsqlExecutionInfo executionInfo, String clusterAlias, ComputeResponse resp) { executionInfo.swapCluster(clusterAlias, (k, v) -> { var builder = new EsqlExecutionInfo.Cluster.Builder(v); if (executionInfo.isMainPlan()) { builder.setTotalShards(resp.getTotalShards()) .setSuccessfulShards(resp.getSuccessfulShards()) .setSkippedShards(resp.getSkippedShards()) .setFailedShards(resp.getFailedShards()); } if (v.getTook() != null && resp.getTook() != null) { // This can happen when we had some subplan executions before the main plan - we need to accumulate the took time builder.setTook(TimeValue.timeValueNanos(v.getTook().nanos() + resp.getTook().nanos())); } else { if (resp.getTook() != null) { builder.setTook(TimeValue.timeValueNanos(executionInfo.planningTookTime().nanos() + resp.getTook().nanos())); } else { // if the cluster is an older version and does not send back took time, then calculate it here on the coordinator // and leave shard info unset, so it is not shown in the CCS metadata section of the JSON response builder.setTook(executionInfo.tookSoFar()); } } if (v.getStatus() == EsqlExecutionInfo.Cluster.Status.RUNNING) { builder.addFailures(v.getFailures()); builder.addFailures(resp.failures); if (executionInfo.isMainPlan()) { if (executionInfo.isStopped() || resp.failedShards > 0 || resp.failures.isEmpty() == false) { builder.setStatus(EsqlExecutionInfo.Cluster.Status.PARTIAL); } else { builder.setStatus(EsqlExecutionInfo.Cluster.Status.SUCCESSFUL); } } } return builder.build(); }); } List<RemoteCluster> getRemoteClusters( Map<String, OriginalIndices> clusterToConcreteIndices, Map<String, OriginalIndices> clusterToOriginalIndices ) { List<RemoteCluster> remoteClusters = new ArrayList<>(clusterToConcreteIndices.size()); RemoteClusterService remoteClusterService = transportService.getRemoteClusterService(); for (Map.Entry<String, OriginalIndices> e : clusterToConcreteIndices.entrySet()) { String clusterAlias = e.getKey(); OriginalIndices concreteIndices = clusterToConcreteIndices.get(clusterAlias); OriginalIndices originalIndices = clusterToOriginalIndices.get(clusterAlias); if (originalIndices == null) { assert false : "can't find original indices for cluster " + clusterAlias; throw new IllegalStateException("can't find original indices for cluster " + clusterAlias); } if (concreteIndices.indices().length > 0) { Transport.Connection connection = remoteClusterService.getConnection(clusterAlias); remoteClusters.add(new RemoteCluster(clusterAlias, connection, concreteIndices.indices(), originalIndices)); } } return remoteClusters; } record RemoteCluster(String clusterAlias, Transport.Connection connection, String[] concreteIndices, OriginalIndices originalIndices) { } @Override public void messageReceived(ClusterComputeRequest request, TransportChannel channel, Task task) { ChannelActionListener<ComputeResponse> listener = new ChannelActionListener<>(channel); RemoteClusterPlan remoteClusterPlan = request.remoteClusterPlan(); var plan = remoteClusterPlan.plan(); if (plan instanceof ExchangeSinkExec == false) { listener.onFailure(new IllegalStateException("expected exchange sink for a remote compute; got " + plan)); return; } runComputeOnRemoteCluster( request.clusterAlias(), request.sessionId(), (CancellableTask) task, request.configuration(), (ExchangeSinkExec) plan, Set.of(remoteClusterPlan.targetIndices()), remoteClusterPlan.originalIndices(), listener ); } /** * Performs a compute on a remote cluster. The output pages are placed in an exchange sink specified by * {@code globalSessionId}. The coordinator on the main cluster will poll pages from there. * <p> * Currently, the coordinator on the remote cluster polls pages from data nodes within the remote cluster * and performs cluster-level reduction before sending pages to the querying cluster. This reduction aims * to minimize data transfers across clusters but may require additional CPU resources for operations like * aggregations. */ void runComputeOnRemoteCluster( String clusterAlias, String globalSessionId, CancellableTask parentTask, Configuration configuration, ExchangeSinkExec plan, Set<String> concreteIndices, OriginalIndices originalIndices, ActionListener<ComputeResponse> listener ) { final var exchangeSink = exchangeService.getSinkHandler(globalSessionId); parentTask.addListener( () -> exchangeService.finishSinkHandler(globalSessionId, new TaskCancelledException(parentTask.getReasonCancelled())) ); final String localSessionId = clusterAlias + ":" + globalSessionId; ReductionPlan reductionPlan = ComputeService.reductionPlan( computeService.plannerSettings(), computeService.createFlags(), configuration, configuration.newFoldContext(), plan, true, false ); PhysicalPlan coordinatorPlan = reductionPlan.nodeReducePlan(); final AtomicReference<ComputeResponse> finalResponse = new AtomicReference<>(); final EsqlFlags flags = computeService.createFlags(); final long startTimeInNanos = System.nanoTime(); final Runnable cancelQueryOnFailure = computeService.cancelQueryOnFailure(parentTask); try (var computeListener = new ComputeListener(transportService.getThreadPool(), cancelQueryOnFailure, listener.map(profiles -> { final TimeValue took = TimeValue.timeValueNanos(System.nanoTime() - startTimeInNanos); final ComputeResponse r = finalResponse.get(); return new ComputeResponse(profiles, took, r.totalShards, r.successfulShards, r.skippedShards, r.failedShards, r.failures); }))) { var exchangeSource = new ExchangeSourceHandler( configuration.pragmas().exchangeBufferSize(), transportService.getThreadPool().executor(ThreadPool.Names.SEARCH) ); try (Releasable ignored = exchangeSource.addEmptySink()) { exchangeSink.addCompletionListener(computeListener.acquireAvoid()); computeService.runCompute( parentTask, new ComputeContext( localSessionId, "remote_reduce", clusterAlias, flags, EmptyIndexedByShardId.instance(), configuration, configuration.newFoldContext(), exchangeSource::createExchangeSource, () -> exchangeSink.createExchangeSink(() -> {}) ), coordinatorPlan, computeListener.acquireCompute() ); dataNodeComputeHandler.startComputeOnDataNodes( localSessionId, clusterAlias, parentTask, flags, configuration, reductionPlan.dataNodePlan(), concreteIndices, originalIndices, exchangeSource, cancelQueryOnFailure, computeListener.acquireCompute().map(r -> { finalResponse.set(r); return r.getCompletionInfo(); }) ); } } } }
ClusterComputeHandler
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/subscribers/QueueDrainSubscriber.java
{ "start": 5076, "end": 5238 }
class ____ { volatile long p1, p2, p3, p4, p5, p6, p7; volatile long p8, p9, p10, p11, p12, p13, p14, p15; } /** The WIP counter. */
QueueDrainSubscriberPad0
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/function/ByteSupplier.java
{ "start": 1011, "end": 1133 }
interface ____ { /** * Supplies a byte. * * @return a result. */ byte getAsByte(); }
ByteSupplier
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/TypeSearchability.java
{ "start": 291, "end": 1342 }
enum ____ { /** * Type is not searchable. * @see DatabaseMetaData#typePredNone */ NONE, /** * Type is fully searchable * @see DatabaseMetaData#typeSearchable */ FULL, /** * Type is valid only in {@code WHERE ... LIKE} * @see DatabaseMetaData#typePredChar */ CHAR, /** * Type is supported only in {@code WHERE ... LIKE} * @see DatabaseMetaData#typePredBasic */ BASIC; /** * Based on the code retrieved from {@link DatabaseMetaData#getTypeInfo()} for the {@code SEARCHABLE} * column, return the appropriate enum. * * @param code The retrieved code value. * * @return The corresponding enum. */ public static TypeSearchability interpret(short code) { return switch (code) { case DatabaseMetaData.typeSearchable -> FULL; case DatabaseMetaData.typePredNone -> NONE; case DatabaseMetaData.typePredBasic -> BASIC; case DatabaseMetaData.typePredChar -> CHAR; default -> throw new IllegalArgumentException( "Unknown type searchability code [" + code + "] encountered" ); }; } }
TypeSearchability
java
micronaut-projects__micronaut-core
inject-groovy/src/main/groovy/io/micronaut/ast/groovy/visitor/AbstractGroovyElement.java
{ "start": 2209, "end": 23513 }
class ____ extends AbstractAnnotationElement { private static final Pattern JAVADOC_PATTERN = Pattern.compile("(/\\s*\\*\\*)|\\s*\\*|(\\s*[*/])"); protected final SourceUnit sourceUnit; protected final CompilationUnit compilationUnit; protected final GroovyVisitorContext visitorContext; private final GroovyNativeElement nativeElement; /** * Default constructor. * * @param visitorContext The groovy visitor context * @param nativeElement The native element * @param annotationMetadataFactory The annotation metadata factory */ protected AbstractGroovyElement(GroovyVisitorContext visitorContext, GroovyNativeElement nativeElement, ElementAnnotationMetadataFactory annotationMetadataFactory) { super(annotationMetadataFactory); this.visitorContext = visitorContext; this.compilationUnit = visitorContext.getCompilationUnit(); this.nativeElement = nativeElement; this.sourceUnit = visitorContext.getSourceUnit(); } /** * Constructs this element by invoking the constructor. * * @return the copy */ @NonNull protected abstract AbstractGroovyElement copyConstructor(); /** * Copies additional values after the element was constructed by {@link #copyConstructor()}. * * @param element the values to be copied to */ protected void copyValues(@NonNull AbstractGroovyElement element) { element.presetAnnotationMetadata = presetAnnotationMetadata; } /** * Makes a copy of this element. * * @return a copy */ @NonNull protected final AbstractGroovyElement copy() { AbstractGroovyElement element = copyConstructor(); copyValues(element); return element; } @Override public io.micronaut.inject.ast.Element withAnnotationMetadata(AnnotationMetadata annotationMetadata) { AbstractGroovyElement element = copy(); element.presetAnnotationMetadata = annotationMetadata; return element; } @Override public @NonNull GroovyNativeElement getNativeType() { return nativeElement; } @Override public boolean isPackagePrivate() { return hasDeclaredAnnotation(PackageScope.class); } @NonNull protected final ClassElement newClassElement(@NonNull ClassNode type, @Nullable Map<String, ClassElement> genericsSpec) { if (genericsSpec == null) { return newClassElement(type); } return newClassElement(getNativeType(), type, genericsSpec, new HashSet<>(), false, false); } @NonNull protected final ClassElement newClassElement(GenericsType genericsType) { return newClassElement(getNativeType(), getNativeType().annotatedNode(), genericsType, genericsType, Collections.emptyMap(), new HashSet<>(), false); } @NonNull protected final ClassElement newClassElement(ClassNode type) { return newClassElement(getNativeType(), type, Collections.emptyMap(), new HashSet<>(), false, false); } @NonNull private ClassElement newClassElement(@Nullable GroovyNativeElement declaredElement, AnnotatedNode genericsOwner, GenericsType genericsType, GenericsType redirectType, Map<String, ClassElement> parentTypeArguments, Set<Object> visitedTypes, boolean isRawType) { if (parentTypeArguments == null) { parentTypeArguments = Collections.emptyMap(); } if (genericsType.isWildcard()) { return resolveWildcard(declaredElement, genericsOwner, genericsType, redirectType, parentTypeArguments, visitedTypes); } if (genericsType.isPlaceholder()) { return resolvePlaceholder(declaredElement, genericsOwner, genericsType, redirectType, parentTypeArguments, visitedTypes, isRawType); } return newClassElement(declaredElement, genericsType.getType(), parentTypeArguments, visitedTypes, genericsType.isPlaceholder(), isRawType); } @NonNull private ClassElement newClassElement(@Nullable GroovyNativeElement declaredElement, ClassNode classNode, Map<String, ClassElement> parentTypeArguments, Set<Object> visitedTypes, boolean isTypeVariable, boolean isRawTypeParameter) { return newClassElement(declaredElement, classNode, parentTypeArguments, visitedTypes, isTypeVariable, isRawTypeParameter, false); } @NonNull private ClassElement newClassElement(@Nullable GroovyNativeElement declaredElement, ClassNode classNode, Map<String, ClassElement> parentTypeArguments, Set<Object> visitedTypes, boolean isTypeVariable, boolean isRawTypeParameter, boolean stripTypeArguments) { if (parentTypeArguments == null) { parentTypeArguments = Collections.emptyMap(); } if (classNode.isArray()) { ClassNode componentType = classNode.getComponentType(); return newClassElement(declaredElement, componentType, parentTypeArguments, visitedTypes, isTypeVariable, isRawTypeParameter) .toArray(); } if (classNode.isGenericsPlaceHolder()) { GenericsType genericsType; GenericsType redirectType; GenericsType[] genericsTypes = classNode.getGenericsTypes(); if (ArrayUtils.isNotEmpty(genericsTypes)) { genericsType = genericsTypes[0]; GenericsType[] redirectTypes = classNode.redirect().getGenericsTypes(); if (ArrayUtils.isNotEmpty(redirectTypes)) { redirectType = redirectTypes[0]; } else { redirectType = new GenericsType(classNode.redirect()); } } else { // Bypass Groovy compiler weirdness genericsType = new GenericsType(classNode.redirect()); redirectType = genericsType; } return newClassElement(declaredElement, getNativeType().annotatedNode(), genericsType, redirectType, parentTypeArguments, visitedTypes, isRawTypeParameter); } if (ClassHelper.isPrimitiveType(classNode)) { return PrimitiveElement.valueOf(classNode.getName()); } if (classNode.isEnum()) { return new GroovyEnumElement(visitorContext, new GroovyNativeElement.Class(classNode), elementAnnotationMetadataFactory); } if (classNode.isAnnotationDefinition()) { return new GroovyAnnotationElement(visitorContext, new GroovyNativeElement.Class(classNode), elementAnnotationMetadataFactory); } Map<String, ClassElement> newTypeArguments; GroovyNativeElement groovyNativeElement; if (declaredElement == null) { groovyNativeElement = new GroovyNativeElement.Class(classNode); } else { groovyNativeElement = new GroovyNativeElement.ClassWithOwner(classNode, declaredElement); } if (stripTypeArguments) { newTypeArguments = resolveTypeArgumentsToObject(classNode); } else { newTypeArguments = resolveClassTypeArguments(groovyNativeElement, classNode, parentTypeArguments, visitedTypes); } return new GroovyClassElement(visitorContext, groovyNativeElement, elementAnnotationMetadataFactory, newTypeArguments, 0, isTypeVariable); } @NonNull private ClassElement resolvePlaceholder(GroovyNativeElement owner, AnnotatedNode genericsOwner, GenericsType genericsType, GenericsType redirectType, Map<String, ClassElement> parentTypeArguments, Set<Object> visitedTypes, boolean isRawType) { ClassNode placeholderClassNode = genericsType.getType(); String variableName = genericsType.getName(); ClassElement resolvedBound = parentTypeArguments.get(variableName); List<GroovyClassElement> bounds = null; Element declaredElement = this; GroovyClassElement resolved = null; int arrayDimensions = 0; if (resolvedBound != null) { if (resolvedBound instanceof WildcardElement wildcardElement) { if (wildcardElement.isBounded()) { return wildcardElement; } } else if (resolvedBound instanceof GroovyGenericPlaceholderElement groovyGenericPlaceholderElement) { bounds = groovyGenericPlaceholderElement.getBounds(); declaredElement = groovyGenericPlaceholderElement.getRequiredDeclaringElement(); resolved = groovyGenericPlaceholderElement.getResolvedInternal(); arrayDimensions = groovyGenericPlaceholderElement.getArrayDimensions(); isRawType = groovyGenericPlaceholderElement.isRawType(); } else if (resolvedBound instanceof GroovyClassElement resolvedClassElement) { resolved = resolvedClassElement; arrayDimensions = resolved.getArrayDimensions(); isRawType = resolved.isRawType(); } else { // Most likely primitive array return resolvedBound; } } GroovyNativeElement groovyPlaceholderNativeElement = new GroovyNativeElement.Placeholder(placeholderClassNode, owner, variableName); if (bounds == null) { List<ClassNode> classNodeBounds = new ArrayList<>(); addBounds(genericsType, classNodeBounds); if (genericsType != redirectType) { addBounds(redirectType, classNodeBounds); } PlaceholderEntry placeholderEntry = new PlaceholderEntry(genericsOwner, variableName); boolean alreadyVisitedPlaceholder = visitedTypes.contains(placeholderEntry); if (!alreadyVisitedPlaceholder) { visitedTypes.add(placeholderEntry); } boolean finalIsRawType = isRawType; bounds = classNodeBounds .stream() .map(classNode -> { if (alreadyVisitedPlaceholder && classNode.isGenericsPlaceHolder()) { classNode = classNode.redirect(); } return classNode; }) .filter(classNode -> !alreadyVisitedPlaceholder || !classNode.isGenericsPlaceHolder()) .map(classNode -> { // Strip declared type arguments and replace with an Object to prevent recursion boolean stripTypeArguments = alreadyVisitedPlaceholder; return (GroovyClassElement) newClassElement(groovyPlaceholderNativeElement, classNode, parentTypeArguments, visitedTypes, true, finalIsRawType, stripTypeArguments); }) .toList(); if (bounds.isEmpty()) { bounds = Collections.singletonList((GroovyClassElement) getObjectClassElement()); } } return new GroovyGenericPlaceholderElement(visitorContext, declaredElement, groovyPlaceholderNativeElement, resolved, bounds, arrayDimensions, isRawType, variableName); } private static void addBounds(GenericsType genericsType, List<ClassNode> classNodeBounds) { if (genericsType.getUpperBounds() != null) { for (ClassNode ub : genericsType.getUpperBounds()) { if (!classNodeBounds.contains(ub)) { classNodeBounds.add(ub); } } } else { ClassNode type = genericsType.getType(); if (!classNodeBounds.contains(type)) { classNodeBounds.add(type); } } } @NonNull private ClassElement getObjectClassElement() { return visitorContext.getClassElement(Object.class) .orElseThrow(() -> new IllegalStateException("java.lang.Object element not found")); } @NonNull private ClassElement resolveWildcard(GroovyNativeElement declaredElement, AnnotatedNode genericsOwner, GenericsType genericsType, GenericsType redirectType, Map<String, ClassElement> parentTypeArguments, Set<Object> visitedTypes) { Stream<ClassNode> lowerBounds = Stream.ofNullable(genericsType.getLowerBound()); Stream<ClassNode> upperBounds; ClassNode[] genericsUpperBounds = genericsType.getUpperBounds(); if (genericsUpperBounds == null || genericsUpperBounds.length == 0) { upperBounds = Stream.empty(); } else { upperBounds = Arrays.stream(genericsUpperBounds); } List<ClassElement> upperBoundsAsElements = upperBounds .map(classNode -> newClassElement(declaredElement, classNode, parentTypeArguments, visitedTypes, true, false)) .toList(); List<ClassElement> lowerBoundsAsElements = lowerBounds .map(classNode -> newClassElement(declaredElement, classNode, parentTypeArguments, visitedTypes, true, false)) .toList(); if (upperBoundsAsElements.isEmpty()) { upperBoundsAsElements = Collections.singletonList(getObjectClassElement()); } ClassElement upperType = WildcardElement.findUpperType(upperBoundsAsElements, lowerBoundsAsElements); if (upperType.getType().getName().equals("java.lang.Object")) { // Not bounded wildcard: <?> if (redirectType != null && redirectType != genericsType) { ClassElement definedTypeBound = newClassElement(declaredElement, genericsOwner, redirectType, redirectType, parentTypeArguments, visitedTypes, false); // Use originating parameter to extract the bound defined if (definedTypeBound instanceof GroovyGenericPlaceholderElement groovyGenericPlaceholderElement) { upperType = WildcardElement.findUpperType(groovyGenericPlaceholderElement.getBounds(), Collections.emptyList()); } } } if (upperType.isPrimitive()) { // TODO: Support primitives for wildcards (? extends byte[]) return upperType; } GroovyNativeElement wildcardNativeElement = new GroovyNativeElement.ClassWithOwner(genericsType.getType(), declaredElement); return new GroovyWildcardElement( wildcardNativeElement, upperBoundsAsElements.stream().map(GroovyClassElement.class::cast).toList(), lowerBoundsAsElements.stream().map(GroovyClassElement.class::cast).toList(), elementAnnotationMetadataFactory, (GroovyClassElement) upperType ); } @NonNull protected final Map<String, ClassElement> resolveMethodTypeArguments(GroovyNativeElement declaredElement, MethodNode methodNode, @Nullable Map<String, ClassElement> parentTypeArguments) { if (parentTypeArguments == null) { parentTypeArguments = Collections.emptyMap(); } return resolveTypeArguments(declaredElement, methodNode, methodNode.getGenericsTypes(), methodNode.getGenericsTypes(), parentTypeArguments, new HashSet<>()); } @NonNull protected final Map<String, ClassElement> resolveClassTypeArguments(GroovyNativeElement declaredElement, ClassNode classNode, @Nullable Map<String, ClassElement> parentTypeArguments, Set<Object> visitedTypes) { return resolveTypeArguments(declaredElement, classNode, classNode.getGenericsTypes(), classNode.redirect().getGenericsTypes(), parentTypeArguments, visitedTypes); } @NonNull private Map<String, ClassElement> resolveTypeArguments(GroovyNativeElement declaredElement, AnnotatedNode genericsOwner, GenericsType[] genericsTypes, GenericsType[] redirectTypes, @Nullable Map<String, ClassElement> parentTypeArguments, Set<Object> visitedTypes) { if (redirectTypes == null || redirectTypes.length == 0) { return Collections.emptyMap(); } Map<String, ClassElement> resolved = CollectionUtils.newLinkedHashMap(redirectTypes.length); if (genericsTypes != null && genericsTypes.length == redirectTypes.length) { for (int i = 0; i < genericsTypes.length; i++) { GenericsType genericsType = genericsTypes[i]; GenericsType redirectType = redirectTypes[i]; ClassElement classElement = newClassElement(declaredElement, genericsOwner, genericsType, redirectType, parentTypeArguments, visitedTypes, false); resolved.put(redirectType.getName(), classElement); } } else { boolean isRaw = genericsTypes == null; for (GenericsType redirectType : redirectTypes) { String variableName = redirectType.getName(); resolved.put( variableName, newClassElement(declaredElement, genericsOwner, redirectType, redirectType, parentTypeArguments, visitedTypes, isRaw) ); } } return resolved; } @NonNull protected final Map<String, ClassElement> resolveTypeArgumentsToObject(ClassNode classNode) { GenericsType[] redirectTypes = classNode.redirect().getGenericsTypes(); if (redirectTypes == null || redirectTypes.length == 0) { return Collections.emptyMap(); } ClassElement objectClassElement = getObjectClassElement(); Map<String, ClassElement> resolved = CollectionUtils.newLinkedHashMap(redirectTypes.length); for (GenericsType redirectType : redirectTypes) { String variableName = redirectType.getName(); resolved.put(variableName, objectClassElement); } return resolved; } @Override public Optional<String> getDocumentation(boolean parse) { GroovyNativeElement nativeType = getNativeType(); AnnotatedNode annotatedNode = nativeType.annotatedNode(); Groovydoc groovydoc = annotatedNode.getGroovydoc(); if (groovydoc == null || groovydoc.getContent() == null) { return Optional.empty(); } if (parse) { return Optional.of(JAVADOC_PATTERN.matcher(annotatedNode.getGroovydoc().getContent()).replaceAll(StringUtils.EMPTY_STRING).trim()); } return Optional.of(annotatedNode.getGroovydoc().getContent()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (!(o instanceof AbstractGroovyElement that)) { return false; } // Allow to match GroovyClassElement / GroovyGenericPlaceholderElement / GroovyWildcardElement return nativeElement.annotatedNode().equals(that.nativeElement.annotatedNode()); } @Override public int hashCode() { return nativeElement.annotatedNode().hashCode(); } /** * Resolve modifiers for a method node. * * @param methodNode The method node * @return The modifiers */ protected Set<ElementModifier> resolveModifiers(MethodNode methodNode) { return resolveModifiers(methodNode.getModifiers()); } /** * Resolve modifiers for a field node. * * @param fieldNode The field node * @return The modifiers */ protected Set<ElementModifier> resolveModifiers(FieldNode fieldNode) { return resolveModifiers(fieldNode.getModifiers()); } /** * Resolve modifiers for a
AbstractGroovyElement
java
netty__netty
codec-compression/src/test/java/io/netty/handler/codec/compression/JdkZlibTest.java
{ "start": 13088, "end": 13887 }
class ____ extends AbstractByteBufAllocator { private static final int MAX = 1024 * 1024; private final ByteBufAllocator wrapped; LimitedByteBufAllocator(ByteBufAllocator wrapped) { this.wrapped = wrapped; } @Override public boolean isDirectBufferPooled() { return wrapped.isDirectBufferPooled(); } @Override protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) { return wrapped.heapBuffer(initialCapacity, Math.min(maxCapacity, MAX)); } @Override protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) { return wrapped.directBuffer(initialCapacity, Math.min(maxCapacity, MAX)); } } }
LimitedByteBufAllocator
java
google__error-prone
core/src/test/java/com/google/errorprone/matchers/NonNullLiteralTest.java
{ "start": 1370, "end": 2171 }
class ____ { public int getInt() { return 2; } public long getLong() { return 3L; } public float getFloat() { return 4.0f; } public double getDouble() { return 5.0d; } public boolean getBool() { return true; } public char getChar() { return 'c'; } public String getString() { return "test string"; } } """); assertCompiles(nonNullLiteralMatches(/* shouldMatch= */ true, Matchers.nonNullLiteral())); } @Test public void shouldMatchClassLiteral() { writeFile( "A.java", """ import java.lang.reflect.Type; public
A
java
apache__dubbo
dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceInfoV2OrBuilder.java
{ "start": 845, "end": 4194 }
interface ____ extends // @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.ServiceInfoV2) com.google.protobuf.MessageOrBuilder { /** * <pre> * The service name. * </pre> * * <code>string name = 1;</code> * @return The name. */ String getName(); /** * <pre> * The service name. * </pre> * * <code>string name = 1;</code> * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); /** * <pre> * The service group. * </pre> * * <code>string group = 2;</code> * @return The group. */ String getGroup(); /** * <pre> * The service group. * </pre> * * <code>string group = 2;</code> * @return The bytes for group. */ com.google.protobuf.ByteString getGroupBytes(); /** * <pre> * The service version. * </pre> * * <code>string version = 3;</code> * @return The version. */ String getVersion(); /** * <pre> * The service version. * </pre> * * <code>string version = 3;</code> * @return The bytes for version. */ com.google.protobuf.ByteString getVersionBytes(); /** * <pre> * The service protocol. * </pre> * * <code>string protocol = 4;</code> * @return The protocol. */ String getProtocol(); /** * <pre> * The service protocol. * </pre> * * <code>string protocol = 4;</code> * @return The bytes for protocol. */ com.google.protobuf.ByteString getProtocolBytes(); /** * <pre> * The service port. * </pre> * * <code>int32 port = 5;</code> * @return The port. */ int getPort(); /** * <pre> * The service path. * </pre> * * <code>string path = 6;</code> * @return The path. */ String getPath(); /** * <pre> * The service path. * </pre> * * <code>string path = 6;</code> * @return The bytes for path. */ com.google.protobuf.ByteString getPathBytes(); /** * <pre> * A map of service parameters. * </pre> * * <code>map&lt;string, string&gt; params = 7;</code> */ int getParamsCount(); /** * <pre> * A map of service parameters. * </pre> * * <code>map&lt;string, string&gt; params = 7;</code> */ boolean containsParams(String key); /** * Use {@link #getParamsMap()} instead. */ @Deprecated java.util.Map<String, String> getParams(); /** * <pre> * A map of service parameters. * </pre> * * <code>map&lt;string, string&gt; params = 7;</code> */ java.util.Map<String, String> getParamsMap(); /** * <pre> * A map of service parameters. * </pre> * * <code>map&lt;string, string&gt; params = 7;</code> */ /* nullable */ String getParamsOrDefault( String key, /* nullable */ String defaultValue); /** * <pre> * A map of service parameters. * </pre> * * <code>map&lt;string, string&gt; params = 7;</code> */ String getParamsOrThrow(String key); }
ServiceInfoV2OrBuilder
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/jdbc/proxy/SerializableBlobProxy.java
{ "start": 590, "end": 2163 }
class ____ implements InvocationHandler, Serializable { private static final Class<?>[] PROXY_INTERFACES = new Class[] { Blob.class, WrappedBlob.class, Serializable.class }; private final transient Blob blob; /** * Builds a serializable {@link Blob} wrapper around the given {@link Blob}. * * @param blob The {@link Blob} to be wrapped. * @see #generateProxy(Blob) */ private SerializableBlobProxy(Blob blob) { this.blob = blob; } /** * Access to the wrapped Blob reference * * @return The wrapped Blob reference */ public Blob getWrappedBlob() { if ( blob == null ) { throw new IllegalStateException( "Blobs may not be accessed after serialization" ); } else { return blob; } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ( "getWrappedBlob".equals( method.getName() ) ) { return getWrappedBlob(); } try { return method.invoke( getWrappedBlob(), args ); } catch ( AbstractMethodError e ) { throw new HibernateException( "The JDBC driver does not implement the method: " + method, e ); } catch ( InvocationTargetException e ) { throw e.getTargetException(); } } /** * Generates a SerializableBlob proxy wrapping the provided Blob object. * * @param blob The Blob to wrap. * * @return The generated proxy. */ public static Blob generateProxy(Blob blob) { return (Blob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new SerializableBlobProxy( blob ) ); } /** * Determines the appropriate
SerializableBlobProxy
java
google__guava
guava/src/com/google/common/collect/Streams.java
{ "start": 28254, "end": 28441 }
interface ____ only intended for use by callers of {@link #mapWithIndex(Stream, * FunctionWithIndex)}. * * @since 21.0 (but only since 33.4.0 in the Android flavor) */ public
is
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/testutils/statemigration/V1TestTypeSerializerSnapshot.java
{ "start": 2817, "end": 3222 }
class ____ TestType."); } } @Override public TypeSerializer<TestType> restoreSerializer() { return new TestType.V1TestTypeSerializer(); } @Override public void writeSnapshot(DataOutputView out) throws IOException {} @Override public void readSnapshot(int readVersion, DataInputView in, ClassLoader userCodeClassLoader) throws IOException {} }
for
java
google__error-prone
core/src/test/java/com/google/errorprone/refaster/TemplatingTest.java
{ "start": 22617, "end": 23232 }
class ____ {", " public boolean example(Object foo) {", " return foo instanceof CharSequence;", " }", "}"); assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example"))) .isEqualTo( ExpressionTemplate.create( ImmutableMap.of("foo", UClassType.create("java.lang.Object")), UInstanceOf.create( UFreeIdent.create("foo"), UClassIdent.create("java.lang.CharSequence")), UPrimitiveType.BOOLEAN)); } @Test public void assignment() { compile( "
InstanceOfExample
java
elastic__elasticsearch
x-pack/plugin/mapper-constant-keyword/src/main/java/org/elasticsearch/xpack/constantkeyword/mapper/ConstantKeywordFieldMapper.java
{ "start": 3546, "end": 5566 }
class ____ extends FieldMapper.Builder { // This is defined as updateable because it can be updated once, from [null] to any value, // by a dynamic mapping update. Once it has been set, however, the value cannot be changed. private final Parameter<String> value = new Parameter<>("value", true, () -> null, (n, c, o) -> { if (o instanceof Number == false && o instanceof CharSequence == false) { throw new MapperParsingException("Property [value] on field [" + n + "] must be a number or a string, but got [" + o + "]"); } return o.toString(); }, m -> toType(m).fieldType().value, XContentBuilder::field, Objects::toString); private final Parameter<Map<String, String>> meta = Parameter.metaParam(); public Builder(String name) { super(name); value.setSerializerCheck((id, ic, v) -> v != null); value.setMergeValidator((previous, current, c) -> previous == null || Objects.equals(previous, current)); } @Override protected Parameter<?>[] getParameters() { return new Parameter<?>[] { value, meta }; } @Override public ConstantKeywordFieldMapper build(MapperBuilderContext context) { if (multiFieldsBuilder.hasMultiFields()) { DEPRECATION_LOGGER.warn( DeprecationCategory.MAPPINGS, CONTENT_TYPE + "_multifields", "Adding multifields to [" + CONTENT_TYPE + "] mappers has no effect and will be forbidden in future" ); } return new ConstantKeywordFieldMapper( leafName(), new ConstantKeywordFieldType(context.buildFullName(leafName()), value.getValue(), meta.getValue()), builderParams(this, context) ); } } public static final TypeParser PARSER = new TypeParser((n, c) -> new Builder(n)); public static final
Builder
java
elastic__elasticsearch
libs/entitlement/src/main/java/org/elasticsearch/entitlement/runtime/policy/ExternalEntitlement.java
{ "start": 1114, "end": 1988 }
interface ____ { /** * This is the list of parameter names that are * parseable in {@link PolicyParser#parseEntitlement(String, String)}. * The number and order of parameter names much match the number and order * of constructor parameters as this is how the parser will pass in the * parsed values from a policy file. However, the names themselves do NOT * have to match the parameter names of the constructor. */ String[] parameterNames() default {}; /** * This flag indicates if this Entitlement can be used in external plugins, * or if it can be used only in Elasticsearch modules ("internal" plugins). * Using an entitlement that is not {@code pluginsAccessible} in an external * plugin policy will throw in exception while parsing. */ boolean esModulesOnly() default true; }
ExternalEntitlement
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Issue101_field.java
{ "start": 598, "end": 1191 }
class ____ { private Object a; private Object b; private Object c; public Object getA() { return a; } public void setA(Object a) { this.a = a; } @JSONField(serialzeFeatures=SerializerFeature.DisableCircularReferenceDetect) public Object getB() { return b; } public void setB(Object b) { this.b = b; } public Object getC() { return c; } public void setC(Object c) { this.c = c; } } }
VO
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/runtime/leaderelection/ZooKeeperLeaderElectionITCase.java
{ "start": 9440, "end": 10116 }
class ____ extends AbstractInvokable { private static final Object lock = new Object(); private static volatile boolean isBlocking = true; public BlockingOperator(Environment environment) { super(environment); } @Override public void invoke() throws Exception { synchronized (lock) { while (isBlocking) { lock.wait(); } } } public static void unblock() { synchronized (lock) { isBlocking = false; lock.notifyAll(); } } } private static
BlockingOperator
java
google__dagger
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
{ "start": 28309, "end": 28563 }
class ____ {", " @Inject TestClass(List list) {}", "}"); Source usesTest = CompilerTests.javaSource("test.UsesTest", "package test;", "", "import javax.inject.Inject;", "", "final
TestClass
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/OverloadedMethodsDeserTest.java
{ "start": 2656, "end": 3708 }
class ____. */ @Test public void testOverride() throws Exception { WasNumberBean bean = MAPPER.readValue ("{\"value\" : \"abc\"}", WasNumberBean.class); assertNotNull(bean); assertEquals("abc", bean.value); } // for [JACKSON-739] @Test public void testConflictResolution() throws Exception { Overloaded739 bean = MAPPER.readValue ("{\"value\":\"abc\"}", Overloaded739.class); assertNotNull(bean); assertEquals("abc", bean._value); } /* /************************************************************ /* Unit tests, failures /************************************************************ */ /** * For genuine setter conflict, an exception is to be thrown. */ @Test public void testSetterConflict() throws Exception { try { MAPPER.readValue("{ }", ConflictBean.class); } catch (Exception e) { verifyException(e, "Conflicting setter definitions"); } } }
conflicts
java
google__guice
core/test/com/google/inject/BinderTestSuite.java
{ "start": 11531, "end": 13810 }
class ____ { private String name = "test"; private Key<?> key = Key.get(A.class); private Class<? extends Injectable> injectsKey = InjectsA.class; private List<Module> modules = Lists.<Module>newArrayList( new AbstractModule() { @Override protected void configure() { bindScope(TwoAtATimeScoped.class, new TwoAtATimeScope()); } }); private List<Object> expectedValues = Lists.<Object>newArrayList(new PlainA(201), new PlainA(202), new PlainA(203)); private CreationTime creationTime = CreationTime.LAZY; private String creationException; private String configurationException; public Builder module(Module module) { this.modules.add(module); return this; } public Builder creationTime(CreationTime creationTime) { this.creationTime = creationTime; return this; } public Builder name(String name) { this.name = name; return this; } public Builder key(Key<?> key, Class<? extends Injectable> injectsKey) { this.key = key; this.injectsKey = injectsKey; return this; } private Builder creationException(String message, Object... args) { this.creationException = String.format(message, args); return this; } private Builder configurationException(String message, Object... args) { configurationException = String.format(message, args); return this; } private Builder scoper(Scoper scoper) { name(name + " in " + scoper); scoper.apply(this); return this; } private <T> Builder expectedValues(T... values) { this.expectedValues.clear(); Collections.addAll(this.expectedValues, values); return this; } public void addToSuite(TestSuite suite) { if (creationException != null) { suite.addTest(new CreationExceptionTest(this)); } else if (configurationException != null) { suite.addTest(new ConfigurationExceptionTest(this)); } else { suite.addTest(new SuccessTest(this)); if (creationTime != CreationTime.NONE) { suite.addTest(new UserExceptionsTest(this)); } } } } public static
Builder
java
grpc__grpc-java
core/src/test/java/io/grpc/internal/DelayedClientTransportTest.java
{ "start": 2785, "end": 35502 }
class ____ { @Rule public final MockitoRule mocks = MockitoJUnit.rule(); @Mock private ManagedClientTransport.Listener transportListener; @Mock private SubchannelPicker mockPicker; @Mock private AbstractSubchannel mockSubchannel; @Mock private TransportProvider mockInternalSubchannel; @Mock private ClientTransport mockRealTransport; @Mock private ClientTransport mockRealTransport2; @Mock private ClientStream mockRealStream; @Mock private ClientStream mockRealStream2; @Mock private ClientStreamListener streamListener; @Captor private ArgumentCaptor<Status> statusCaptor; @Captor private ArgumentCaptor<ClientStreamListener> listenerCaptor; private static final CallOptions.Key<Integer> SHARD_ID = CallOptions.Key.createWithDefault("shard-id", -1); private static final Status SHUTDOWN_STATUS = Status.UNAVAILABLE.withDescription("shutdown called"); private static final ClientStreamTracer[] tracers = new ClientStreamTracer[] { new ClientStreamTracer() {} }; private final MethodDescriptor<String, Integer> method = MethodDescriptor.<String, Integer>newBuilder() .setType(MethodType.UNKNOWN) .setFullMethodName("service/method") .setRequestMarshaller(new StringMarshaller()) .setResponseMarshaller(new IntegerMarshaller()) .build(); private final MethodDescriptor<String, Integer> method2 = method.toBuilder().setFullMethodName("service/method").build(); private final Metadata headers = new Metadata(); private final Metadata headers2 = new Metadata(); private final CallOptions callOptions = CallOptions.DEFAULT.withAuthority("dummy_value"); private final CallOptions callOptions2 = CallOptions.DEFAULT.withAuthority("dummy_value2"); private final FakeClock fakeExecutor = new FakeClock(); private final DelayedClientTransport delayedTransport = new DelayedClientTransport( fakeExecutor.getScheduledExecutorService(), new SynchronizationContext( new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { throw new AssertionError(e); } })); @Before public void setUp() { when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))) .thenReturn(PickResult.withSubchannel(mockSubchannel)); when(mockSubchannel.getInternalSubchannel()).thenReturn(mockInternalSubchannel); when(mockInternalSubchannel.obtainActiveTransport()).thenReturn(mockRealTransport); when(mockRealTransport.newStream( same(method), same(headers), same(callOptions), ArgumentMatchers.<ClientStreamTracer[]>any())) .thenReturn(mockRealStream); when(mockRealTransport2.newStream( same(method2), same(headers2), same(callOptions2), ArgumentMatchers.<ClientStreamTracer[]>any())) .thenReturn(mockRealStream2); delayedTransport.start(transportListener); } @After public void noMorePendingTasks() { assertEquals(0, fakeExecutor.numPendingTasks()); } @Test public void streamStartThenAssignTransport() { assertFalse(delayedTransport.hasPendingStreams()); ClientStream stream = delayedTransport.newStream( method, headers, callOptions, tracers); stream.start(streamListener); assertEquals(1, delayedTransport.getPendingStreamsCount()); assertTrue(delayedTransport.hasPendingStreams()); assertTrue(stream instanceof DelayedStream); assertEquals(0, fakeExecutor.numPendingTasks()); delayedTransport.reprocess(mockPicker); assertEquals(0, delayedTransport.getPendingStreamsCount()); assertFalse(delayedTransport.hasPendingStreams()); assertEquals(1, fakeExecutor.runDueTasks()); verify(mockRealTransport).newStream( same(method), same(headers), same(callOptions), ArgumentMatchers.<ClientStreamTracer[]>any()); verify(mockRealStream).start(listenerCaptor.capture()); verifyNoMoreInteractions(streamListener); listenerCaptor.getValue().onReady(); verify(streamListener).onReady(); verifyNoMoreInteractions(streamListener); } @Test public void newStreamThenAssignTransportThenShutdown() { ClientStream stream = delayedTransport.newStream(method, headers, callOptions, tracers); assertEquals(1, delayedTransport.getPendingStreamsCount()); assertTrue(stream instanceof DelayedStream); delayedTransport.reprocess(mockPicker); assertEquals(0, delayedTransport.getPendingStreamsCount()); delayedTransport.shutdown(SHUTDOWN_STATUS); verify(transportListener).transportShutdown(same(SHUTDOWN_STATUS)); verify(transportListener).transportTerminated(); assertEquals(0, fakeExecutor.runDueTasks()); verify(mockRealTransport).newStream( same(method), same(headers), same(callOptions), ArgumentMatchers.<ClientStreamTracer[]>any()); stream.start(streamListener); verify(mockRealStream).start(same(streamListener)); } @Test public void transportTerminatedThenAssignTransport() { delayedTransport.shutdown(SHUTDOWN_STATUS); verify(transportListener).transportShutdown(same(SHUTDOWN_STATUS)); verify(transportListener).transportTerminated(); delayedTransport.reprocess(mockPicker); verifyNoMoreInteractions(transportListener); } @Test public void assignTransportThenShutdownThenNewStream() { delayedTransport.reprocess(mockPicker); delayedTransport.shutdown(SHUTDOWN_STATUS); verify(transportListener).transportShutdown(same(SHUTDOWN_STATUS)); verify(transportListener).transportTerminated(); ClientStream stream = delayedTransport.newStream( method, headers, callOptions, tracers); assertEquals(0, delayedTransport.getPendingStreamsCount()); assertTrue(stream instanceof FailingClientStream); verify(mockRealTransport, never()).newStream( any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any()); } @Test public void assignTransportThenShutdownNowThenNewStream() { delayedTransport.reprocess(mockPicker); delayedTransport.shutdownNow(Status.UNAVAILABLE); verify(transportListener).transportShutdown(any(Status.class)); verify(transportListener).transportTerminated(); ClientStream stream = delayedTransport.newStream( method, headers, callOptions, tracers); assertEquals(0, delayedTransport.getPendingStreamsCount()); assertTrue(stream instanceof FailingClientStream); verify(mockRealTransport, never()).newStream( any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any()); } @Test public void startThenCancelStreamWithoutSetTransport() { ClientStream stream = delayedTransport.newStream( method, new Metadata(), CallOptions.DEFAULT, tracers); stream.start(streamListener); assertEquals(1, delayedTransport.getPendingStreamsCount()); stream.cancel(Status.CANCELLED); assertEquals(0, delayedTransport.getPendingStreamsCount()); verify(streamListener).closed( same(Status.CANCELLED), same(RpcProgress.PROCESSED), any(Metadata.class)); verifyNoMoreInteractions(mockRealTransport); verifyNoMoreInteractions(mockRealStream); } @Test public void newStreamThenShutdownTransportThenAssignTransport() { ClientStream stream = delayedTransport.newStream( method, headers, callOptions, tracers); stream.start(streamListener); delayedTransport.shutdown(SHUTDOWN_STATUS); // Stream is still buffered verify(transportListener).transportShutdown(same(SHUTDOWN_STATUS)); verify(transportListener, times(0)).transportTerminated(); assertEquals(1, delayedTransport.getPendingStreamsCount()); // ... and will proceed if a real transport is available delayedTransport.reprocess(mockPicker); fakeExecutor.runDueTasks(); verify(mockRealTransport).newStream( method, headers, callOptions, tracers); verify(mockRealStream).start(any(ClientStreamListener.class)); // Since no more streams are pending, delayed transport is now terminated assertEquals(0, delayedTransport.getPendingStreamsCount()); verify(transportListener).transportTerminated(); // Further newStream() will return a failing stream stream = delayedTransport.newStream( method, new Metadata(), CallOptions.DEFAULT, tracers); verify(streamListener, never()).closed( any(Status.class), any(RpcProgress.class), any(Metadata.class)); stream.start(streamListener); verify(streamListener).closed( statusCaptor.capture(), any(RpcProgress.class), any(Metadata.class)); assertEquals(Status.Code.UNAVAILABLE, statusCaptor.getValue().getCode()); assertEquals(0, delayedTransport.getPendingStreamsCount()); verifyNoMoreInteractions(mockRealTransport); verifyNoMoreInteractions(mockRealStream); } @Test public void newStreamThenShutdownTransportThenCancelStream() { ClientStream stream = delayedTransport.newStream( method, new Metadata(), CallOptions.DEFAULT, tracers); delayedTransport.shutdown(SHUTDOWN_STATUS); verify(transportListener).transportShutdown(same(SHUTDOWN_STATUS)); verify(transportListener, times(0)).transportTerminated(); assertEquals(1, delayedTransport.getPendingStreamsCount()); stream.start(streamListener); stream.cancel(Status.CANCELLED); verify(transportListener).transportTerminated(); assertEquals(0, delayedTransport.getPendingStreamsCount()); verifyNoMoreInteractions(mockRealTransport); verifyNoMoreInteractions(mockRealStream); } @Test public void shutdownThenNewStream() { delayedTransport.shutdown(SHUTDOWN_STATUS); verify(transportListener).transportShutdown(same(SHUTDOWN_STATUS)); verify(transportListener).transportTerminated(); ClientStream stream = delayedTransport.newStream( method, new Metadata(), CallOptions.DEFAULT, tracers); stream.start(streamListener); verify(streamListener).closed( statusCaptor.capture(), any(RpcProgress.class), any(Metadata.class)); assertEquals(Status.Code.UNAVAILABLE, statusCaptor.getValue().getCode()); } @Test public void startStreamThenShutdownNow() { ClientStream stream = delayedTransport.newStream( method, new Metadata(), CallOptions.DEFAULT, tracers); stream.start(streamListener); delayedTransport.shutdownNow(Status.UNAVAILABLE); verify(transportListener).transportShutdown(any(Status.class)); verify(transportListener).transportTerminated(); verify(streamListener) .closed(statusCaptor.capture(), eq(RpcProgress.REFUSED), any(Metadata.class)); assertEquals(Status.Code.UNAVAILABLE, statusCaptor.getValue().getCode()); } @Test public void shutdownNowThenNewStream() { delayedTransport.shutdownNow(Status.UNAVAILABLE); verify(transportListener).transportShutdown(any(Status.class)); verify(transportListener).transportTerminated(); ClientStream stream = delayedTransport.newStream( method, new Metadata(), CallOptions.DEFAULT, tracers); stream.start(streamListener); verify(streamListener).closed( statusCaptor.capture(), any(RpcProgress.class), any(Metadata.class)); assertEquals(Status.Code.UNAVAILABLE, statusCaptor.getValue().getCode()); } @Test public void reprocessSemantics() { CallOptions failFastCallOptions = CallOptions.DEFAULT.withOption(SHARD_ID, 1); CallOptions waitForReadyCallOptions = CallOptions.DEFAULT.withOption(SHARD_ID, 2) .withWaitForReady(); AbstractSubchannel subchannel1 = mock(AbstractSubchannel.class); AbstractSubchannel subchannel2 = mock(AbstractSubchannel.class); AbstractSubchannel subchannel3 = mock(AbstractSubchannel.class); when(mockRealTransport.newStream( any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any())) .thenReturn(mockRealStream); when(mockRealTransport2.newStream( any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any())) .thenReturn(mockRealStream2); when(subchannel1.getInternalSubchannel()).thenReturn(newTransportProvider(mockRealTransport)); when(subchannel2.getInternalSubchannel()).thenReturn(newTransportProvider(mockRealTransport2)); when(subchannel3.getInternalSubchannel()).thenReturn(newTransportProvider(null)); // Fail-fast streams DelayedStream ff1 = (DelayedStream) delayedTransport.newStream( method, headers, failFastCallOptions, tracers); ff1.start(mock(ClientStreamListener.class)); ff1.halfClose(); PickSubchannelArgsMatcher ff1args = new PickSubchannelArgsMatcher(method, headers, failFastCallOptions); verify(transportListener).transportInUse(true); DelayedStream ff2 = (DelayedStream) delayedTransport.newStream( method2, headers2, failFastCallOptions, tracers); PickSubchannelArgsMatcher ff2args = new PickSubchannelArgsMatcher(method2, headers2, failFastCallOptions); DelayedStream ff3 = (DelayedStream) delayedTransport.newStream( method, headers, failFastCallOptions, tracers); PickSubchannelArgsMatcher ff3args = new PickSubchannelArgsMatcher(method, headers, failFastCallOptions); DelayedStream ff4 = (DelayedStream) delayedTransport.newStream( method2, headers2, failFastCallOptions, tracers); PickSubchannelArgsMatcher ff4args = new PickSubchannelArgsMatcher(method2, headers2, failFastCallOptions); // Wait-for-ready streams FakeClock wfr3Executor = new FakeClock(); DelayedStream wfr1 = (DelayedStream) delayedTransport.newStream( method, headers, waitForReadyCallOptions, tracers); PickSubchannelArgsMatcher wfr1args = new PickSubchannelArgsMatcher(method, headers, waitForReadyCallOptions); DelayedStream wfr2 = (DelayedStream) delayedTransport.newStream( method2, headers2, waitForReadyCallOptions, tracers); PickSubchannelArgsMatcher wfr2args = new PickSubchannelArgsMatcher(method2, headers2, waitForReadyCallOptions); CallOptions wfr3callOptions = waitForReadyCallOptions.withExecutor( wfr3Executor.getScheduledExecutorService()); DelayedStream wfr3 = (DelayedStream) delayedTransport.newStream( method, headers, wfr3callOptions, tracers); wfr3.start(mock(ClientStreamListener.class)); wfr3.halfClose(); PickSubchannelArgsMatcher wfr3args = new PickSubchannelArgsMatcher(method, headers, wfr3callOptions); DelayedStream wfr4 = (DelayedStream) delayedTransport.newStream( method2, headers2, waitForReadyCallOptions, tracers); PickSubchannelArgsMatcher wfr4args = new PickSubchannelArgsMatcher(method2, headers2, waitForReadyCallOptions); assertEquals(8, delayedTransport.getPendingStreamsCount()); // First reprocess(). Some will proceed, some will fail and the rest will stay buffered. SubchannelPicker picker = mock(SubchannelPicker.class); when(picker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn( // For the fail-fast streams PickResult.withSubchannel(subchannel1), // ff1: proceed PickResult.withError(Status.UNAVAILABLE), // ff2: fail PickResult.withSubchannel(subchannel3), // ff3: stay PickResult.withNoResult(), // ff4: stay // For the wait-for-ready streams PickResult.withSubchannel(subchannel2), // wfr1: proceed PickResult.withError(Status.RESOURCE_EXHAUSTED), // wfr2: stay PickResult.withSubchannel(subchannel3)); // wfr3: stay InOrder inOrder = inOrder(picker); delayedTransport.reprocess(picker); assertEquals(5, delayedTransport.getPendingStreamsCount()); inOrder.verify(picker).pickSubchannel(argThat(ff1args)); inOrder.verify(picker).pickSubchannel(argThat(ff2args)); inOrder.verify(picker).pickSubchannel(argThat(ff3args)); inOrder.verify(picker).pickSubchannel(argThat(ff4args)); inOrder.verify(picker).pickSubchannel(argThat(wfr1args)); inOrder.verify(picker).pickSubchannel(argThat(wfr2args)); inOrder.verify(picker).pickSubchannel(argThat(wfr3args)); inOrder.verify(picker).pickSubchannel(argThat(wfr4args)); inOrder.verifyNoMoreInteractions(); // Make sure that streams are created and started immediately, not in any executor. This is // necessary during shut down to guarantee that when DelayedClientTransport terminates, all // streams are now owned by a real transport (which should prevent the Channel from // terminating). // ff1 and wfr1 went through verify(mockRealTransport).newStream( method, headers, failFastCallOptions, tracers); verify(mockRealTransport2).newStream( method, headers, waitForReadyCallOptions, tracers); assertSame(mockRealStream, ff1.getRealStream()); assertSame(mockRealStream2, wfr1.getRealStream()); verify(mockRealStream).start(any(ClientStreamListener.class)); // But also verify that non-start()-related calls are run within the Executor, since they may be // slow. verify(mockRealStream, never()).halfClose(); fakeExecutor.runDueTasks(); assertEquals(0, fakeExecutor.numPendingTasks()); verify(mockRealStream).halfClose(); // The ff2 has failed due to picker returning an error assertSame(Status.UNAVAILABLE, ((FailingClientStream) ff2.getRealStream()).getError()); // Other streams are still buffered assertNull(ff3.getRealStream()); assertNull(ff4.getRealStream()); assertNull(wfr2.getRealStream()); assertNull(wfr3.getRealStream()); assertNull(wfr4.getRealStream()); // Second reprocess(). All existing streams will proceed. picker = mock(SubchannelPicker.class); when(picker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn( PickResult.withSubchannel(subchannel1), // ff3 PickResult.withSubchannel(subchannel2), // ff4 PickResult.withSubchannel(subchannel2), // wfr2 PickResult.withSubchannel(subchannel1), // wfr3 PickResult.withSubchannel(subchannel2), // wfr4 PickResult.withNoResult()); // wfr5 (not yet created) inOrder = inOrder(picker); assertEquals(0, wfr3Executor.numPendingTasks()); verify(transportListener, never()).transportInUse(false); delayedTransport.reprocess(picker); assertEquals(0, delayedTransport.getPendingStreamsCount()); verify(transportListener).transportInUse(false); inOrder.verify(picker).pickSubchannel(argThat(ff3args)); // ff3 inOrder.verify(picker).pickSubchannel(argThat(ff4args)); // ff4 inOrder.verify(picker).pickSubchannel(argThat(wfr2args)); // wfr2 inOrder.verify(picker).pickSubchannel(argThat(wfr3args)); // wfr3 inOrder.verify(picker).pickSubchannel(argThat(wfr4args)); // wfr4 inOrder.verifyNoMoreInteractions(); fakeExecutor.runDueTasks(); assertEquals(0, fakeExecutor.numPendingTasks()); assertSame(mockRealStream, ff3.getRealStream()); assertSame(mockRealStream2, ff4.getRealStream()); assertSame(mockRealStream2, wfr2.getRealStream()); assertSame(mockRealStream2, wfr4.getRealStream()); assertSame(mockRealStream, wfr3.getRealStream()); // If there is an executor in the CallOptions, it will be used to create the real stream. verify(mockRealStream, times(1)).halfClose(); // 1 for ff1 wfr3Executor.runDueTasks(); verify(mockRealStream, times(2)).halfClose(); // New streams will use the last picker DelayedStream wfr5 = (DelayedStream) delayedTransport.newStream( method, headers, waitForReadyCallOptions, tracers); assertNull(wfr5.getRealStream()); inOrder.verify(picker).pickSubchannel( eqPickSubchannelArgs(method, headers, waitForReadyCallOptions)); inOrder.verifyNoMoreInteractions(); assertEquals(1, delayedTransport.getPendingStreamsCount()); // wfr5 will stop delayed transport from terminating delayedTransport.shutdown(SHUTDOWN_STATUS); verify(transportListener).transportShutdown(same(SHUTDOWN_STATUS)); verify(transportListener, never()).transportTerminated(); // ... until it's gone picker = mock(SubchannelPicker.class); when(picker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn( PickResult.withSubchannel(subchannel1)); delayedTransport.reprocess(picker); verify(picker).pickSubchannel( eqPickSubchannelArgs(method, headers, waitForReadyCallOptions)); fakeExecutor.runDueTasks(); assertSame(mockRealStream, wfr5.getRealStream()); assertEquals(0, delayedTransport.getPendingStreamsCount()); verify(transportListener).transportTerminated(); } @Test public void reprocess_authorityOverrideFromLb() { InOrder inOrder = inOrder(mockRealStream); DelayedStream delayedStream = (DelayedStream) delayedTransport.newStream( method, headers, callOptions.withAuthority(null), tracers); delayedStream.setAuthority("authority-override-from-calloptions"); delayedStream.start(mock(ClientStreamListener.class)); SubchannelPicker picker = mock(SubchannelPicker.class); PickResult pickResult = PickResult.withSubchannel( mockSubchannel, null, "authority-override-hostname-from-lb"); when(picker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(pickResult); when(mockRealTransport.newStream( same(method), same(headers), any(CallOptions.class), ArgumentMatchers.any())) .thenReturn(mockRealStream); delayedTransport.reprocess(picker); fakeExecutor.runDueTasks(); // Must be set before start(), and may be overwritten inOrder.verify(mockRealStream).setAuthority("authority-override-hostname-from-lb"); inOrder.verify(mockRealStream).setAuthority("authority-override-from-calloptions"); inOrder.verify(mockRealStream).start(any(ClientStreamListener.class)); } @Test public void reprocess_NoPendingStream() { SubchannelPicker picker = mock(SubchannelPicker.class); AbstractSubchannel subchannel = mock(AbstractSubchannel.class); when(subchannel.getInternalSubchannel()).thenReturn(mockInternalSubchannel); when(picker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn( PickResult.withSubchannel(subchannel)); when(mockRealTransport.newStream( any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any())) .thenReturn(mockRealStream); delayedTransport.reprocess(picker); verifyNoMoreInteractions(picker); verifyNoMoreInteractions(transportListener); // Though picker was not originally used, it will be saved and serve future streams. ClientStream stream = delayedTransport.newStream( method, headers, CallOptions.DEFAULT, tracers); verify(picker).pickSubchannel(eqPickSubchannelArgs(method, headers, CallOptions.DEFAULT)); verify(mockInternalSubchannel).obtainActiveTransport(); assertSame(mockRealStream, stream); } @Test public void newStream_authorityOverrideFromLb() { InOrder inOrder = inOrder(mockRealStream); SubchannelPicker picker = mock(SubchannelPicker.class); PickResult pickResult = PickResult.withSubchannel( mockSubchannel, null, "authority-override-hostname-from-lb"); when(picker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(pickResult); when(mockRealTransport.newStream( any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), any())) .thenReturn(mockRealStream); delayedTransport.reprocess(picker); ClientStream stream = delayedTransport.newStream(method, headers, callOptions, tracers); assertThat(stream).isSameInstanceAs(mockRealStream); stream.setAuthority("authority-override-from-calloptions"); stream.start(mock(ClientStreamListener.class)); // Must be set before start(), and may be overwritten inOrder.verify(mockRealStream).setAuthority("authority-override-hostname-from-lb"); inOrder.verify(mockRealStream).setAuthority("authority-override-from-calloptions"); inOrder.verify(mockRealStream).start(any(ClientStreamListener.class)); } @Test public void newStream_assignsTransport_authorityFromLB() { SubchannelPicker picker = mock(SubchannelPicker.class); AbstractSubchannel subchannel = mock(AbstractSubchannel.class); when(subchannel.getInternalSubchannel()).thenReturn(mockInternalSubchannel); PickResult pickResult = PickResult.withSubchannel( subchannel, null, "authority-override-hostname-from-lb"); when(picker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(pickResult); ArgumentCaptor<CallOptions> callOptionsArgumentCaptor = ArgumentCaptor.forClass(CallOptions.class); when(mockRealTransport.newStream( any(MethodDescriptor.class), any(Metadata.class), callOptionsArgumentCaptor.capture(), ArgumentMatchers.<ClientStreamTracer[]>any())) .thenReturn(mockRealStream); delayedTransport.reprocess(picker); verifyNoMoreInteractions(picker); verifyNoMoreInteractions(transportListener); CallOptions callOptions = CallOptions.DEFAULT; delayedTransport.newStream(method, headers, callOptions, tracers); assertThat(callOptionsArgumentCaptor.getValue().getAuthority()).isEqualTo( "authority-override-hostname-from-lb"); } @Test public void reprocess_newStreamRacesWithReprocess() throws Exception { final CyclicBarrier barrier = new CyclicBarrier(2); // In both phases, we only expect the first pickSubchannel() call to block on the barrier. final AtomicBoolean nextPickShouldWait = new AtomicBoolean(true); ///////// Phase 1: reprocess() twice with the same picker SubchannelPicker picker = mock(SubchannelPicker.class); doAnswer(new Answer<PickResult>() { @Override @SuppressWarnings("CatchAndPrintStackTrace") public PickResult answer(InvocationOnMock invocation) throws Throwable { if (nextPickShouldWait.compareAndSet(true, false)) { try { barrier.await(); return PickResult.withNoResult(); } catch (Exception e) { e.printStackTrace(); } } return PickResult.withNoResult(); } }).when(picker).pickSubchannel(any(PickSubchannelArgs.class)); // Because there is no pending stream yet, it will do nothing but save the picker. delayedTransport.reprocess(picker); verify(picker, never()).pickSubchannel(any(PickSubchannelArgs.class)); Thread sideThread = new Thread("sideThread") { @Override public void run() { // Will call pickSubchannel and wait on barrier delayedTransport.newStream(method, headers, callOptions, tracers); } }; sideThread.start(); PickSubchannelArgsMatcher args = new PickSubchannelArgsMatcher(method, headers, callOptions); PickSubchannelArgsMatcher args2 = new PickSubchannelArgsMatcher(method, headers2, callOptions); // Is called from sideThread verify(picker, timeout(5000)).pickSubchannel(argThat(args)); // Because stream has not been buffered (it's still stuck in newStream()), this will do nothing, // but incrementing the picker version. delayedTransport.reprocess(picker); verify(picker).pickSubchannel(argThat(args)); // Now let the stuck newStream() through barrier.await(5, TimeUnit.SECONDS); sideThread.join(5000); assertFalse("sideThread should've exited", sideThread.isAlive()); // newStream() detects that there has been a new picker while it's stuck, thus will pick again. verify(picker, times(2)).pickSubchannel(argThat(args)); barrier.reset(); nextPickShouldWait.set(true); ////////// Phase 2: reprocess() with a different picker // Create the second stream Thread sideThread2 = new Thread("sideThread2") { @Override public void run() { // Will call pickSubchannel and wait on barrier delayedTransport.newStream(method, headers2, callOptions, tracers); } }; sideThread2.start(); // The second stream will see the first picker verify(picker, timeout(5000)).pickSubchannel(argThat(args2)); // While the first stream won't use the first picker any more. verify(picker, times(2)).pickSubchannel(argThat(args)); // Now use a different picker SubchannelPicker picker2 = mock(SubchannelPicker.class); when(picker2.pickSubchannel(any(PickSubchannelArgs.class))) .thenReturn(PickResult.withNoResult()); delayedTransport.reprocess(picker2); // The pending first stream uses the new picker verify(picker2).pickSubchannel(argThat(args)); // The second stream is still pending in creation, doesn't use the new picker. verify(picker2, never()).pickSubchannel(argThat(args2)); // Now let the second stream finish creation barrier.await(5, TimeUnit.SECONDS); sideThread2.join(5000); assertFalse("sideThread2 should've exited", sideThread2.isAlive()); // The second stream should see the new picker verify(picker2, timeout(5000)).pickSubchannel(argThat(args2)); // Wrapping up verify(picker, times(2)).pickSubchannel(argThat(args)); verify(picker).pickSubchannel(argThat(args2)); verify(picker2).pickSubchannel(argThat(args)); verify(picker2).pickSubchannel(argThat(args)); } @Test public void reprocess_addOptionalLabelCallsTracer() throws Exception { delayedTransport.reprocess(new SubchannelPicker() { @Override public PickResult pickSubchannel(PickSubchannelArgs args) { args.getPickDetailsConsumer().addOptionalLabel("routed", "perfectly"); return PickResult.withError(Status.UNAVAILABLE.withDescription("expected")); } }); ClientStreamTracer tracer = mock(ClientStreamTracer.class); ClientStream stream = delayedTransport.newStream( method, headers, callOptions, new ClientStreamTracer[] {tracer}); stream.start(streamListener); verify(tracer).addOptionalLabel("routed", "perfectly"); } @Test public void newStream_racesWithReprocessIdleMode() throws Exception { SubchannelPicker picker = new SubchannelPicker() { @Override public PickResult pickSubchannel(PickSubchannelArgs args) { // Assume entering idle mode raced with the pick delayedTransport.reprocess(null); // Act like IDLE LB return PickResult.withNoResult(); } }; // Because there is no pending stream yet, it will do nothing but save the picker. delayedTransport.reprocess(picker); ClientStream stream = delayedTransport.newStream( method, headers, callOptions, tracers); stream.start(streamListener); assertTrue(delayedTransport.hasPendingStreams()); verify(transportListener).transportInUse(true); } @Test public void pendingStream_appendTimeoutInsight_waitForReady() { ClientStream stream = delayedTransport.newStream( method, headers, callOptions.withWaitForReady(), tracers); stream.start(streamListener); InsightBuilder insight = new InsightBuilder(); stream.appendTimeoutInsight(insight); assertThat(insight.toString()) .matches("\\[wait_for_ready, buffered_nanos=[0-9]+\\, waiting_for_connection]"); } @Test public void pendingStream_appendTimeoutInsight_waitForReady_withLastPickFailure() { ClientStream stream = delayedTransport.newStream( method, headers, callOptions.withWaitForReady(), tracers); stream.start(streamListener); SubchannelPicker picker = mock(SubchannelPicker.class); when(picker.pickSubchannel(any(PickSubchannelArgs.class))) .thenReturn(PickResult.withError(Status.PERMISSION_DENIED)); delayedTransport.reprocess(picker); InsightBuilder insight = new InsightBuilder(); stream.appendTimeoutInsight(insight); assertThat(insight.toString()) .matches("\\[wait_for_ready, " + "Last Pick Failure=Status\\{code=PERMISSION_DENIED, description=null, cause=null\\}," + " buffered_nanos=[0-9]+, waiting_for_connection]"); } private static TransportProvider newTransportProvider(final ClientTransport transport) { return new TransportProvider() { @Override public ClientTransport obtainActiveTransport() { return transport; } }; } }
DelayedClientTransportTest
java
apache__camel
components/camel-dataset/src/main/java/org/apache/camel/component/dataset/DataSetEndpoint.java
{ "start": 2215, "end": 11278 }
class ____ extends MockEndpoint implements Service { private final transient Logger log; private final AtomicInteger receivedCounter = new AtomicInteger(); @UriPath(name = "name", description = "Name of DataSet to lookup in the registry") @Metadata(required = true) private volatile DataSet dataSet; @UriParam(label = "consumer", defaultValue = "0") private int minRate; @UriParam(label = "consumer", defaultValue = "3", javaType = "java.time.Duration") private long produceDelay = 3; @UriParam(label = "producer", defaultValue = "0", javaType = "java.time.Duration") private long consumeDelay; @UriParam(label = "consumer", defaultValue = "0") private long preloadSize; @UriParam(label = "consumer", defaultValue = "1000", javaType = "java.time.Duration") private long initialDelay = 1000; @UriParam(enums = "strict,lenient,off", defaultValue = "lenient") private String dataSetIndex = "lenient"; public DataSetEndpoint(String endpointUri, Component component, DataSet dataSet) { super(endpointUri, component); this.dataSet = dataSet; this.log = LoggerFactory.getLogger(endpointUri); // optimize as we dont need to copy the exchange setCopyOnExchange(false); } @Override public boolean isRemote() { return false; } public static void assertEquals(String description, Object expected, Object actual, Exchange exchange) { if (!ObjectHelper.equal(expected, actual)) { throw new AssertionError( description + " does not match. Expected: " + expected + " but was: " + actual + " on " + exchange + " with headers: " + exchange.getIn().getHeaders()); } } @Override public Consumer createConsumer(Processor processor) throws Exception { Consumer answer = new DataSetConsumer(this, processor); configureConsumer(answer); return answer; } @Override public Producer createProducer() throws Exception { Producer answer = super.createProducer(); long size = getDataSet().getSize(); expectedMessageCount((int) size); return answer; } @Override public void reset() { super.reset(); if (receivedCounter != null) { receivedCounter.set(0); } } @Override public int getReceivedCounter() { return receivedCounter.get(); } /** * Creates a message exchange for the given index in the {@link DataSet} */ public Exchange createExchange(long messageIndex) throws Exception { Exchange exchange = createExchange(); getDataSet().populateMessage(exchange, messageIndex); if (!getDataSetIndex().equals("off")) { Message in = exchange.getIn(); in.setHeader(DataSetConstants.DATASET_INDEX, messageIndex); } return exchange; } @Override protected void waitForCompleteLatch(long timeout) throws InterruptedException { super.waitForCompleteLatch(timeout); if (minRate > 0) { int count = getReceivedCounter(); do { // wait as long as we get a decent message rate super.waitForCompleteLatch(1000L); count = getReceivedCounter() - count; } while (count >= minRate); } } // Properties //------------------------------------------------------------------------- public DataSet getDataSet() { return dataSet; } public void setDataSet(DataSet dataSet) { this.dataSet = dataSet; } public int getMinRate() { return minRate; } /** * Wait until the DataSet contains at least this number of messages */ public void setMinRate(int minRate) { this.minRate = minRate; } public long getPreloadSize() { return preloadSize; } /** * Sets how many messages should be preloaded (sent) before the route completes its initialization */ public void setPreloadSize(long preloadSize) { this.preloadSize = preloadSize; } public long getConsumeDelay() { return consumeDelay; } /** * Allows a delay to be specified which causes a delay when a message is consumed by the producer (to simulate slow * processing) */ public void setConsumeDelay(long consumeDelay) { this.consumeDelay = consumeDelay; } public long getProduceDelay() { return produceDelay; } /** * Allows a delay to be specified which causes a delay when a message is sent by the consumer (to simulate slow * processing) */ public void setProduceDelay(long produceDelay) { this.produceDelay = produceDelay; } public long getInitialDelay() { return initialDelay; } /** * Time period in millis to wait before starting sending messages. */ public void setInitialDelay(long initialDelay) { this.initialDelay = initialDelay; } /** * Controls the behaviour of the CamelDataSetIndex header. * * off (consumer) the header will not be set. strict (consumer) the header will be set. lenient (consumer) the * header will be set. off (producer) the header value will not be verified, and will not be set if it is not * present. strict (producer) the header value must be present and will be verified. lenient (producer) the header * value will be verified if it is present, and will be set if it is not present. */ public void setDataSetIndex(String dataSetIndex) { switch (dataSetIndex) { case "off": case "lenient": case "strict": this.dataSetIndex = dataSetIndex; break; default: throw new IllegalArgumentException( "Invalid value specified for the dataSetIndex URI parameter:" + dataSetIndex + "Supported values are strict, lenient and off "); } } public String getDataSetIndex() { return dataSetIndex; } // Implementation methods //------------------------------------------------------------------------- @Override protected void performAssertions(Exchange actual, Exchange copy) throws Exception { int receivedCount = receivedCounter.incrementAndGet(); long index = receivedCount - 1; Exchange expected = createExchange(index); // now let's assert that they are the same if (log.isDebugEnabled()) { if (copy.getIn().getHeader(DataSetConstants.DATASET_INDEX) != null) { log.debug("Received message: {} (DataSet index={}) = {}", index, copy.getIn().getHeader(DataSetConstants.DATASET_INDEX, Integer.class), copy); } else { log.debug("Received message: {} = {}", index, copy); } } assertMessageExpected(index, expected, copy); if (consumeDelay > 0) { Thread.sleep(consumeDelay); } } protected void assertMessageExpected(long index, Exchange expected, Exchange actual) throws Exception { switch (getDataSetIndex()) { case "off": break; case "strict": long actualCounter = ExchangeHelper.getMandatoryHeader(actual, DataSetConstants.DATASET_INDEX, Long.class); assertEquals("Header: " + DataSetConstants.DATASET_INDEX, index, actualCounter, actual); break; case "lenient": default: // Validate the header value if it is present Long dataSetIndexHeaderValue = actual.getIn().getHeader(DataSetConstants.DATASET_INDEX, Long.class); if (dataSetIndexHeaderValue != null) { assertEquals("Header: " + DataSetConstants.DATASET_INDEX, index, dataSetIndexHeaderValue, actual); } else { // set the header if it isn't there actual.getIn().setHeader(DataSetConstants.DATASET_INDEX, index); } break; } getDataSet().assertMessageExpected(this, expected, actual, index); } protected ThroughputLogger createReporter() { // must sanitize uri to avoid logging sensitive information String uri = URISupport.sanitizeUri(getEndpointUri()); CamelLogger logger = new CamelLogger(uri); ThroughputLogger answer = new ThroughputLogger(logger, (int) this.getDataSet().getReportCount()); answer.setAction("Received"); return answer; } @Override protected void doStart() throws Exception { super.doStart(); if (reporter == null) { reporter = createReporter(); } log.debug("{} expecting {} messages", this, getExpectedCount()); } }
DataSetEndpoint
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/DereferenceWithNullBranchTest.java
{ "start": 2674, "end": 2947 }
class ____ {} Foo.Bar bar; } """) .doTest(); } @Test public void noCrashOnQualifiedInterface() { helper .addSourceLines( "Foo.java", """ import java.util.Map;
Bar
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurerTests.java
{ "start": 4699, "end": 10860 }
class ____ { public final SpringTestContext spring = new SpringTestContext(this); @Autowired MockMvc mvc; @Test public void configureWhenRegisteringObjectPostProcessorThenInvokedOnBasicAuthenticationFilter() { this.spring.register(ObjectPostProcessorConfig.class).autowire(); verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(BasicAuthenticationFilter.class)); } @Test public void httpBasicWhenUsingDefaultsInLambdaThenResponseIncludesBasicChallenge() throws Exception { this.spring.register(DefaultsLambdaEntryPointConfig.class).autowire(); // @formatter:off this.mvc.perform(get("/")) .andExpect(status().isUnauthorized()) .andExpect(header().string("WWW-Authenticate", "Basic realm=\"Realm\"")); // @formatter:on } // SEC-2198 @Test public void httpBasicWhenUsingDefaultsThenResponseIncludesBasicChallenge() throws Exception { this.spring.register(DefaultsEntryPointConfig.class).autowire(); // @formatter:off this.mvc.perform(get("/")) .andExpect(status().isUnauthorized()) .andExpect(header().string("WWW-Authenticate", "Basic realm=\"Realm\"")); // @formatter:on } @Test public void httpBasicWhenUsingCustomAuthenticationEntryPointThenResponseIncludesBasicChallenge() throws Exception { CustomAuthenticationEntryPointConfig.ENTRY_POINT = mock(AuthenticationEntryPoint.class); this.spring.register(CustomAuthenticationEntryPointConfig.class).autowire(); this.mvc.perform(get("/")); verify(CustomAuthenticationEntryPointConfig.ENTRY_POINT).commence(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AuthenticationException.class)); } @Test public void httpBasicWhenInvokedTwiceThenUsesOriginalEntryPoint() throws Exception { this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire(); this.mvc.perform(get("/")); verify(DuplicateDoesNotOverrideConfig.ENTRY_POINT).commence(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AuthenticationException.class)); } // SEC-3019 @Test public void httpBasicWhenRememberMeConfiguredThenSetsRememberMeCookie() throws Exception { this.spring.register(BasicUsesRememberMeConfig.class, Home.class).autowire(); MockHttpServletRequestBuilder rememberMeRequest = get("/").with(httpBasic("user", "password")) .param("remember-me", "true"); this.mvc.perform(rememberMeRequest).andExpect(cookie().exists("remember-me")); } @Test public void httpBasicWhenDefaultsThenAcceptsBasicCredentials() throws Exception { this.spring.register(HttpBasic.class, Users.class, Home.class).autowire(); this.mvc.perform(get("/").with(httpBasic("user", "password"))) .andExpect(status().isOk()) .andExpect(content().string("user")); } @Test public void httpBasicWhenCustomSecurityContextHolderStrategyThenUses() throws Exception { this.spring.register(HttpBasic.class, Users.class, Home.class, SecurityContextChangedListenerConfig.class) .autowire(); this.mvc.perform(get("/").with(httpBasic("user", "password"))) .andExpect(status().isOk()) .andExpect(content().string("user")); SecurityContextChangedListener listener = this.spring.getContext() .getBean(SecurityContextChangedListener.class); verify(listener).securityContextChanged(setAuthentication(UsernamePasswordAuthenticationToken.class)); } @Test public void httpBasicWhenUsingCustomSecurityContextRepositoryThenUses() throws Exception { this.spring.register(CustomSecurityContextRepositoryConfig.class, Users.class, Home.class).autowire(); this.mvc.perform(get("/").with(httpBasic("user", "password"))) .andExpect(status().isOk()) .andExpect(content().string("user")); verify(CustomSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPOSITORY) .saveContext(any(SecurityContext.class), any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test public void httpBasicWhenObservationRegistryThenObserves() throws Exception { this.spring.register(HttpBasic.class, Users.class, Home.class, ObservationRegistryConfig.class).autowire(); ObservationHandler<Observation.Context> handler = this.spring.getContext().getBean(ObservationHandler.class); this.mvc.perform(get("/").with(httpBasic("user", "password"))) .andExpect(status().isOk()) .andExpect(content().string("user")); ArgumentCaptor<Observation.Context> context = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, atLeastOnce()).onStart(context.capture()); assertThat(context.getAllValues()).anyMatch((c) -> c instanceof AuthenticationObservationContext); verify(handler, atLeastOnce()).onStop(context.capture()); assertThat(context.getAllValues()).anyMatch((c) -> c instanceof AuthenticationObservationContext); this.mvc.perform(get("/").with(httpBasic("user", "wrong"))).andExpect(status().isUnauthorized()); verify(handler).onError(context.capture()); assertThat(context.getValue()).isInstanceOf(AuthenticationObservationContext.class); } @Test public void httpBasicWhenExcludeAuthenticationObservationsThenUnobserved() throws Exception { this.spring .register(HttpBasic.class, Users.class, Home.class, ObservationRegistryConfig.class, SelectableObservationsConfig.class) .autowire(); ObservationHandler<Observation.Context> handler = this.spring.getContext().getBean(ObservationHandler.class); this.mvc.perform(get("/").with(httpBasic("user", "password"))) .andExpect(status().isOk()) .andExpect(content().string("user")); ArgumentCaptor<Observation.Context> context = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, atLeastOnce()).onStart(context.capture()); assertThat(context.getAllValues()).noneMatch((c) -> c instanceof AuthenticationObservationContext); context = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, atLeastOnce()).onStop(context.capture()); assertThat(context.getAllValues()).noneMatch((c) -> c instanceof AuthenticationObservationContext); this.mvc.perform(get("/").with(httpBasic("user", "wrong"))).andExpect(status().isUnauthorized()); verify(handler, never()).onError(any()); } @Configuration @EnableWebSecurity static
HttpBasicConfigurerTests
java
apache__camel
components/camel-vertx/camel-vertx/src/test/java/org/apache/camel/component/vertx/VertxJsonArrayConverterTest.java
{ "start": 1142, "end": 3663 }
class ____ extends CamelTestSupport { private static final String BODY = "[\"Hello\",\"World\"]"; @Test public void testBufferToJsonArray() { JsonArray jsonArray = context.getTypeConverter().convertTo(JsonArray.class, Buffer.buffer(BODY)); Assertions.assertEquals(BODY, jsonArray.toString()); } @Test public void testStringToJsonArray() { JsonArray jsonArray = context.getTypeConverter().convertTo(JsonArray.class, BODY); Assertions.assertEquals(BODY, jsonArray.toString()); } @Test public void testByteArrayToJsonArray() { JsonArray jsonArray = context.getTypeConverter().convertTo(JsonArray.class, BODY.getBytes()); Assertions.assertEquals(BODY, jsonArray.toString()); } @Test public void testByteBufToJsonArray() { JsonArray jsonArray = context.getTypeConverter().convertTo(JsonArray.class, Unpooled.wrappedBuffer(BODY.getBytes())); Assertions.assertEquals(BODY, jsonArray.toString()); } @Test public void testListArrayToJsonArray() { JsonArray jsonArray = context.getTypeConverter().convertTo(JsonArray.class, new JsonArray(BODY).getList()); Assertions.assertEquals(BODY, jsonArray.toString()); } @Test public void testInputStreamToJsonArray() { InputStream inputStream = context.getTypeConverter().convertTo(InputStream.class, BODY); JsonArray jsonArray = context.getTypeConverter().convertTo(JsonArray.class, inputStream); Assertions.assertEquals(BODY, jsonArray.toString()); } @Test public void testJsonArrayToBuffer() { Buffer result = context.getTypeConverter().convertTo(Buffer.class, Buffer.buffer(BODY).toJsonArray()); Assertions.assertEquals(BODY, result.toString()); } @Test public void testJsonArrayToString() { String result = context.getTypeConverter().convertTo(String.class, Buffer.buffer(BODY).toJsonArray()); Assertions.assertEquals(BODY, result); } @Test public void testJsonArrayToByteArray() { byte[] result = context.getTypeConverter().convertTo(byte[].class, Buffer.buffer(BODY.getBytes()).toJsonArray()); Assertions.assertEquals(BODY, new String(result)); } @Test public void testJsonArrayToList() { List result = context.getTypeConverter().convertTo(List.class, Buffer.buffer(BODY).toJsonArray()); Assertions.assertEquals(BODY, new JsonArray(result).toString()); } }
VertxJsonArrayConverterTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/server/Server.java
{ "start": 24541, "end": 24740 }
interface ____, it will be destroyed and * removed before the given one is initialized and added. * <p> * If an exception is thrown the server is destroyed. * * @param klass service
exists
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
{ "start": 97842, "end": 98455 }
interface ____<A, B> extends Function<A, B> { default <C> ImmutableFunction<A, C> andThen(ImmutableFunction<B, C> fn) { return x -> fn.apply(apply(x)); } } } """) .doTest(); } @Test public void checksEffectiveTypeOfReceiver_whenNotDirectOuterClass() { compilationHelper .addSourceLines( "Test.java", """ import com.google.errorprone.annotations.Immutable; import java.util.function.Function; @Immutable abstract
ImmutableFunction
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/annotations/View.java
{ "start": 2253, "end": 2340 }
interface ____ { /** * The SQL query that defines the view. */ String query(); }
View
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
{ "start": 12384, "end": 14689 }
class ____ extends Nesty {", " private final @Annot(1) OuterWithTypeParam<@Annot(2) Double>" + ".@Annot(3) InnerWithTypeParam<@Annot(4) String> inner;", "", " AutoValue_Nesty(", " @Annot(1) OuterWithTypeParam<@Annot(2) Double>" + ".@Annot(3) InnerWithTypeParam<@Annot(4) String> inner) {", " if (inner == null) {", " throw new NullPointerException(\"Null inner\");", " }", " this.inner = inner;", " }", "", " @Override", " @Annot(1) OuterWithTypeParam<@Annot(2) Double>" + ".@Annot(3) InnerWithTypeParam<@Annot(4) String> inner() {", " return inner;", " }", "", " @Override", " public String toString() {", " return \"Nesty{\"", " + \"inner=\" + inner", " + \"}\";", " }", "", " @Override", " public boolean equals(Object o) {", " if (o == this) {", " return true;", " }", " if (o instanceof Nesty) {", " Nesty that = (Nesty) o;", " return this.inner.equals(that.inner());", " }", " return false;", " }", "", " @Override", " public int hashCode() {", " int h$ = 1;", " h$ *= 1000003;", " h$ ^= inner.hashCode();", " return h$;", " }", "}"); Compilation compilation = javac() .withProcessors(new AutoValueProcessor()) .withOptions( "-Xlint:-processing", "-implicit:none", "-A" + Nullables.NULLABLE_OPTION + "=") .compile(annotFileObject, outerFileObject, nestyFileObject); assertThat(compilation).succeededWithoutWarnings(); assertThat(compilation) .generatedSourceFile("com.example.AutoValue_Nesty") .hasSourceEquivalentTo(expectedOutput); } // Tests that type annotations are correctly copied from the bounds of type parameters in the // @AutoValue
AutoValue_Nesty
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/indices/alias/get/GetAliasesAction.java
{ "start": 580, "end": 851 }
class ____ extends ActionType<GetAliasesResponse> { public static final GetAliasesAction INSTANCE = new GetAliasesAction(); public static final String NAME = "indices:admin/aliases/get"; private GetAliasesAction() { super(NAME); } }
GetAliasesAction
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/type/EnumArrayTest.java
{ "start": 8091, "end": 8635 }
class ____ { @Id private Long id; @Enumerated(EnumType.ORDINAL) @Column( name = "the_array" ) private MyEnum[] theArray; public TableWithEnumArrays() { } public TableWithEnumArrays(Long id, MyEnum[] theArray) { this.id = id; this.theArray = theArray; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public MyEnum[] getTheArray() { return theArray; } public void setTheArray(MyEnum[] theArray) { this.theArray = theArray; } } public
TableWithEnumArrays
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java
{ "start": 25480, "end": 26767 }
class ____<T> { private final T mapping; private final HandlerMethod handlerMethod; private final Set<String> directPaths; private final @Nullable String mappingName; private final boolean corsConfig; public MappingRegistration(T mapping, HandlerMethod handlerMethod, @Nullable Set<String> directPaths, @Nullable String mappingName, boolean corsConfig) { Assert.notNull(mapping, "Mapping must not be null"); Assert.notNull(handlerMethod, "HandlerMethod must not be null"); this.mapping = mapping; this.handlerMethod = handlerMethod; this.directPaths = (directPaths != null ? directPaths : Collections.emptySet()); this.mappingName = mappingName; this.corsConfig = corsConfig; } public T getMapping() { return this.mapping; } public HandlerMethod getHandlerMethod() { return this.handlerMethod; } public Set<String> getDirectPaths() { return this.directPaths; } public @Nullable String getMappingName() { return this.mappingName; } public boolean hasCorsConfig() { return this.corsConfig; } } /** * A thin wrapper around a matched HandlerMethod and its mapping, for the purpose of * comparing the best match with a comparator in the context of the current request. */ private
MappingRegistration
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchRowCountWarningTest.java
{ "start": 1712, "end": 5565 }
class ____ { private TriggerOnPrefixLogListener trigger; @BeforeAll public void setUp(SessionFactoryScope scope) { trigger = new TriggerOnPrefixLogListener( "HHH100001" ); LogInspectionHelper.registerListener( trigger, JdbcLogging.JDBC_LOGGER ); scope.inTransaction( session -> { session.persist( new MyEntity( 1L, "Nicola", null ) ); session.persist( new MyEntity( 2L, "Stefano", "Ste" ) ); session.persist( new JoinTableEntity( 1L, new SpamEntity() ) ); } ); } @BeforeEach public void reset() { trigger.reset(); } @AfterAll public void tearDown(SessionFactoryScope scope) { LogInspectionHelper.clearAllListeners( JdbcLogging.JDBC_LOGGER ); scope.inTransaction( session -> { session.createMutationQuery( "delete from BaseEntity" ).executeUpdate(); session.createQuery( "from JoinTableEntity", JoinTableEntity.class ) .getResultList() .forEach( session::remove ); } ); } @Test public void testPersistBase(SessionFactoryScope scope) { scope.inTransaction( session -> session.persist( new BaseEntity( 10L ) ) ); scope.inTransaction( session -> assertThat( session.find( BaseEntity.class, 10L ) ).isNotNull() ); assertThat( trigger.wasTriggered() ).as( "Warning message was triggered" ).isFalse(); } @Test public void testPersistJoined(SessionFactoryScope scope) { scope.inTransaction( session -> session.persist( new MyEntity( 3L, "Vittorio", "Vitto" ) ) ); scope.inTransaction( session -> assertThat( session.find( MyEntity.class, 3L ) .getName() ).isEqualTo( "Vittorio" ) ); assertThat( trigger.wasTriggered() ).as( "Warning message was triggered" ).isFalse(); } @Test public void testPersistJoinTable(SessionFactoryScope scope) { scope.inTransaction( session -> session.persist( new JoinTableEntity( 2L, new SpamEntity() ) ) ); scope.inTransaction( session -> assertThat( session.find( JoinTableEntity.class, 2L ) .getSpamEntity() ).isNotNull() ); assertThat( trigger.wasTriggered() ).as( "Warning message was triggered" ).isFalse(); } @Test public void testPersistMultipleJoined(SessionFactoryScope scope) { scope.inTransaction( session -> { session.persist( new MyEntity( 96L, "multi_1", null ) ); session.persist( new MyEntity( 97L, "multi_2", null ) ); session.persist( new MyEntity( 98L, "multi_3", null ) ); session.persist( new MyEntity( 99L, "multi_4", null ) ); } ); assertThat( trigger.wasTriggered() ).as( "Warning message was triggered" ).isFalse(); } @Test public void testUpdateJoined(SessionFactoryScope scope) { scope.inTransaction( session -> { final MyEntity entity = session.find( MyEntity.class, 1L ); entity.setNickname( "Nico" ); } ); scope.inTransaction( session -> assertThat( session.find( MyEntity.class, 1L ) .getNickname() ).isEqualTo( "Nico" ) ); assertThat( trigger.wasTriggered() ).as( "Warning message was triggered" ).isFalse(); } @Test public void testDeleteJoined(SessionFactoryScope scope) { scope.inTransaction( session -> { final MyEntity entity = session.find( MyEntity.class, 2L ); session.remove( entity ); } ); scope.inTransaction( session -> assertThat( session.find( MyEntity.class, 2L ) ).isNull() ); assertThat( trigger.wasTriggered() ).as( "Warning message was triggered" ).isFalse(); } @Test public void testDeleteJoinTable(SessionFactoryScope scope) { scope.inTransaction( session -> { final JoinTableEntity entity = session.find( JoinTableEntity.class, 1L ); session.remove( entity ); } ); scope.inTransaction( session -> assertThat( session.find( JoinTableEntity.class, 1L ) ).isNull() ); assertThat( trigger.wasTriggered() ).as( "Warning message was triggered" ).isFalse(); } @Entity( name = "BaseEntity" ) @Inheritance( strategy = InheritanceType.JOINED ) public static
BatchRowCountWarningTest
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/expressions/parser/ast/operator/binary/NumericComparisonOperation.java
{ "start": 1509, "end": 2710 }
class ____ extends ExpressionNode { private final ExpressionNode leftOperand; private final ExpressionNode rightOperand; private final ExpressionDef.ComparisonOperation.OpType type; public NumericComparisonOperation(ExpressionNode leftOperand, ExpressionNode rightOperand, ExpressionDef.ComparisonOperation.OpType type) { this.leftOperand = leftOperand; this.rightOperand = rightOperand; this.type = type; } @Override protected TypeDef doResolveType(@NonNull ExpressionVisitorContext ctx) { TypeDef leftType = leftOperand.resolveType(ctx); TypeDef rightType = rightOperand.resolveType(ctx); if (!isNumeric(leftType) || !isNumeric(rightType)) { throw new ExpressionCompilationException( "Numeric comparison operation can only be applied to numeric types"); } return BOOLEAN; } @Override public ExpressionDef generateExpression(ExpressionCompilationContext ctx) { return leftOperand.compile(ctx) .compare(type, rightOperand.compile(ctx)); } }
NumericComparisonOperation
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cdi/lifecycle/ExtendedBeanManagerNotAvailableDuringTypeResolutionTest.java
{ "start": 3363, "end": 3416 }
enum ____ { VALUE1, VALUE2; } public static
MyEnum
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ForEachIterableTest.java
{ "start": 4628, "end": 5084 }
class ____ { abstract void doSomething(Object element); void iteratorWhile(Iterable<?> list) { Iterator<?> iterator = list.iterator(); while (iterator.hasNext()) { iterator.next(); } } } """) .addOutputLines( "out/Test.java", """ import java.util.Iterator; abstract
Test
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemamanager/SchemaManagerExplicitSchemaTest.java
{ "start": 1687, "end": 2943 }
class ____ { @BeforeEach public void clean(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().dropMappedObjects(true); } private Long countBooks(SessionImplementor s) { return s.createQuery("select count(*) from BookForTesting", Long.class).getSingleResult(); } @Test public void testExportValidateTruncateDrop(SessionFactoryScope scope) { SessionFactoryImplementor factory = scope.getSessionFactory(); factory.getSchemaManager().exportMappedObjects(true); scope.inTransaction( s -> s.persist( new Book() ) ); factory.getSchemaManager().validateMappedObjects(); scope.inTransaction( s -> assertEquals( 1, countBooks(s) ) ); factory.getSchemaManager().truncateMappedObjects(); scope.inTransaction( s -> assertEquals( 0, countBooks(s) ) ); factory.getSchemaManager().dropMappedObjects(true); try { factory.getSchemaManager().validateMappedObjects(); fail(); } catch (SchemaManagementException e) { assertTrue( e.getMessage().contains("ForTesting") ); } try { factory.getSchemaManager().validate(); fail(); } catch (SchemaValidationException e) { assertTrue( e.getMessage().contains("ForTesting") ); } } @Entity(name="BookForTesting") static
SchemaManagerExplicitSchemaTest
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeConverters.java
{ "start": 7423, "end": 7608 }
class ____ implements Converter<Long, Instant> { @Override public Instant convert(Long source) { return Instant.ofEpochMilli(source); } } private static
LongToInstantConverter
java
apache__dubbo
dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/DefaultHttp1Request.java
{ "start": 1087, "end": 2105 }
class ____ implements Http1Request { private final RequestMetadata httpMetadata; private final HttpInputMessage httpInputMessage; public DefaultHttp1Request(RequestMetadata httpMetadata, HttpInputMessage httpInputMessage) { this.httpMetadata = httpMetadata; this.httpInputMessage = httpInputMessage; } @Override public InputStream getBody() { return httpInputMessage.getBody(); } @Override public HttpHeaders headers() { return httpMetadata.headers(); } @Override public String method() { return httpMetadata.method(); } @Override public String path() { return httpMetadata.path(); } @Override public void close() throws IOException { httpInputMessage.close(); } @Override public String toString() { return "Http1Request{method='" + method() + '\'' + ", path='" + path() + '\'' + ", contentType='" + contentType() + "'}"; } }
DefaultHttp1Request
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/defaultbean/DefaultBeanPriorityTest.java
{ "start": 2536, "end": 2696 }
class ____ implements BarInterface { @Override public String ping() { return BarImpl2.class.getSimpleName(); } } }
BarImpl2
java
apache__camel
components/camel-jpa/src/test/java/org/apache/camel/examples/MultiSteps.java
{ "start": 1554, "end": 3436 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(MultiSteps.class); private Long id; private String address; private int step; public MultiSteps() { } public MultiSteps(String address) { setAddress(address); setStep(1); } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getStep() { return step; } public void setStep(int step) { this.step = step; } @PreConsumed public void beforeGoToNextStep(Exchange exchange) { // we could do some thing to update the entity by using the exchange property assertNotNull(exchange); LOG.info("Calling beforeGoToNextStep"); } /** * This method is invoked after the entity bean is processed successfully by a Camel endpoint */ @Consumed public void goToNextStep() { setStep(getStep() + 1); LOG.info("Invoked the completion complete method. Now updated the step to: {}", getStep()); } @Override public String toString() { // OpenJPA warns about fields being accessed directly in methods if NOT using the corresponding getters: // 115 camel WARN [main] openjpa.Enhance - Detected the following possible violations of the restrictions placed on property access persistent types: // "org.apache.camel.examples.MultiSteps" uses property access, but its field "step" is accessed directly in method "toString" defined in "org.apache.camel.examples.MultiSteps". return "MultiSteps[id: " + getId() + ", address: " + getAddress() + ", step: " + getStep() + "]"; } }
MultiSteps
java
netty__netty
microbench/src/main/java/io/netty/microbench/concurrent/ScheduledFutureTaskBenchmark.java
{ "start": 1360, "end": 1535 }
class ____ extends AbstractMicrobenchmark { static final EventLoop executor = new DefaultEventLoop(); @State(Scope.Thread) public static
ScheduledFutureTaskBenchmark
java
apache__camel
components/camel-cxf/camel-cxf-soap/src/test/java/org/apache/camel/component/cxf/jaxws/CxfConsumerPayLoadMarshalFaultTest.java
{ "start": 1255, "end": 2531 }
class ____ extends CxfConsumerPayloadFaultTest { protected static final String DETAILS = "<detail></detail>"; @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(fromURI).process(new Processor() { public void process(final Exchange exchange) throws Exception { JAXBContext context = JAXBContext.newInstance("org.apache.camel.wsdl_first.types"); QName faultCode = new QName("http://schemas.xmlsoap.org/soap/envelope/", "Server"); SoapFault fault = new SoapFault("Get the null value of person name", faultCode); Element details = StaxUtils.read(new StringReader(DETAILS)).getDocumentElement(); UnknownPersonFault unknowPersonFault = new UnknownPersonFault(); unknowPersonFault.setPersonId(""); context.createMarshaller().marshal(unknowPersonFault, details); fault.setDetail(details); exchange.getMessage().setBody(fault); } }); } }; } }
CxfConsumerPayLoadMarshalFaultTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Component.java
{ "start": 194, "end": 643 }
class ____ { private String _name; private SubComponent _subComponent; /** * @return */ public String getName() { return _name; } /** * @param string */ public void setName(String string) { _name = string; } /** * @return */ public SubComponent getSubComponent() { return _subComponent; } /** * @param component */ public void setSubComponent(SubComponent component) { _subComponent = component; } }
Component
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/exec/internal/lock/FollowOnLockingAction.java
{ "start": 11592, "end": 13215 }
class ____ implements LoadedValuesCollector { private final Collection<NavigablePath> pathsToLock; private List<LoadedEntityRegistration> entitiesToLock; private List<LoadedCollectionRegistration> collectionsToLock; public LoadedValuesCollectorImpl(LockingClauseStrategy lockingClauseStrategy) { pathsToLock = LockingHelper.extractPathsToLock( lockingClauseStrategy ); } @Override public void registerEntity(NavigablePath navigablePath, EntityMappingType entityDescriptor, EntityKey entityKey) { if ( pathsToLock.contains( navigablePath ) ) { if ( entitiesToLock == null ) { entitiesToLock = new ArrayList<>(); } entitiesToLock.add( new LoadedEntityRegistration( navigablePath, entityDescriptor, entityKey ) ); } } @Override public void registerCollection(NavigablePath navigablePath, PluralAttributeMapping collectionDescriptor, CollectionKey collectionKey) { if ( pathsToLock.contains( navigablePath ) ) { if ( collectionsToLock == null ) { collectionsToLock = new ArrayList<>(); } collectionsToLock.add( new LoadedCollectionRegistration( navigablePath, collectionDescriptor, collectionKey ) ); } } @Override public void clear() { if ( entitiesToLock != null ) { entitiesToLock.clear(); } if ( collectionsToLock != null ) { collectionsToLock.clear(); } } @Override public List<LoadedEntityRegistration> getCollectedEntities() { return entitiesToLock; } @Override public List<LoadedCollectionRegistration> getCollectedCollections() { return collectionsToLock; } } }
LoadedValuesCollectorImpl
java
grpc__grpc-java
core/src/test/java/io/grpc/internal/DnsNameResolverTest.java
{ "start": 3665, "end": 4865 }
class ____ { @Rule public final TestRule globalTimeout = new DisableOnDebug(Timeout.seconds(10)); @Rule public final MockitoRule mocks = MockitoJUnit.rule(); private final Map<String, ?> serviceConfig = new LinkedHashMap<>(); private static final int DEFAULT_PORT = 887; private final SynchronizationContext syncContext = new SynchronizationContext( new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { throw new AssertionError(e); } }); private final DnsNameResolverProvider provider = new DnsNameResolverProvider(); private final FakeClock fakeClock = new FakeClock(); private final FakeClock fakeExecutor = new FakeClock(); private static final FakeClock.TaskFilter NAME_RESOLVER_REFRESH_TASK_FILTER = new FakeClock.TaskFilter() { @Override public boolean shouldAccept(Runnable command) { return command.toString().contains( RetryingNameResolver.DelayedNameResolverRefresh.class.getName()); } }; private final FakeExecutorResource fakeExecutorResource = new FakeExecutorResource(); private final
DnsNameResolverTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/nested/MonetaryAmount.java
{ "start": 456, "end": 874 }
enum ____ { USD, EUR } private BigDecimal amount; private CurrencyCode currency; public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } @Column(length = 3) @Enumerated(EnumType.STRING) public CurrencyCode getCurrency() { return currency; } public void setCurrency(CurrencyCode currency) { this.currency = currency; } }
CurrencyCode
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Preisregelung.java
{ "start": 383, "end": 828 }
class ____ { private Long id; private Tranchenmodell tranchenmodell; @Id public Long getId() { return id; } public void setId(Long id) { this.id = id; } @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) public Tranchenmodell getTranchenmodell() { return tranchenmodell; } public void setTranchenmodell(Tranchenmodell tranchenmodell) { this.tranchenmodell = tranchenmodell; } }
Preisregelung
java
apache__camel
core/camel-core-processor/src/main/java/org/apache/camel/processor/loadbalancer/QueueLoadBalancer.java
{ "start": 981, "end": 1128 }
class ____ {@link LoadBalancer} implementations which choose a single destination for each exchange (rather * like JMS Queues) */ public abstract
for
java
spring-projects__spring-boot
core/spring-boot-testcontainers/src/testFixtures/java/org/springframework/boot/testcontainers/service/connection/ContainerConnectionDetailsFactoryHints.java
{ "start": 908, "end": 1242 }
class ____ { private ContainerConnectionDetailsFactoryHints() { } public static RuntimeHints getRegisteredHints(ClassLoader classLoader) { RuntimeHints hints = new RuntimeHints(); new ContainerConnectionDetailsFactoriesRuntimeHints().registerHints(hints, classLoader); return hints; } }
ContainerConnectionDetailsFactoryHints
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/processors/SerializedProcessor.java
{ "start": 1009, "end": 5667 }
class ____<T> extends FlowableProcessor<T> { /** The actual subscriber to serialize Subscriber calls to. */ final FlowableProcessor<T> actual; /** Indicates an emission is going on, guarded by this. */ boolean emitting; /** If not null, it holds the missed NotificationLite events. */ AppendOnlyLinkedArrayList<Object> queue; /** Indicates a terminal event has been received and all further events will be dropped. */ volatile boolean done; /** * Constructor that wraps an actual subject. * @param actual the subject wrapped */ SerializedProcessor(final FlowableProcessor<T> actual) { this.actual = actual; } @Override protected void subscribeActual(Subscriber<? super T> s) { actual.subscribe(s); } @Override public void onSubscribe(Subscription s) { boolean cancel; if (!done) { synchronized (this) { if (done) { cancel = true; } else { if (emitting) { AppendOnlyLinkedArrayList<Object> q = queue; if (q == null) { q = new AppendOnlyLinkedArrayList<>(4); queue = q; } q.add(NotificationLite.subscription(s)); return; } emitting = true; cancel = false; } } } else { cancel = true; } if (cancel) { s.cancel(); } else { actual.onSubscribe(s); emitLoop(); } } @Override public void onNext(T t) { if (done) { return; } synchronized (this) { if (done) { return; } if (emitting) { AppendOnlyLinkedArrayList<Object> q = queue; if (q == null) { q = new AppendOnlyLinkedArrayList<>(4); queue = q; } q.add(NotificationLite.next(t)); return; } emitting = true; } actual.onNext(t); emitLoop(); } @Override public void onError(Throwable t) { if (done) { RxJavaPlugins.onError(t); return; } boolean reportError; synchronized (this) { if (done) { reportError = true; } else { done = true; if (emitting) { AppendOnlyLinkedArrayList<Object> q = queue; if (q == null) { q = new AppendOnlyLinkedArrayList<>(4); queue = q; } q.setFirst(NotificationLite.error(t)); return; } reportError = false; emitting = true; } } if (reportError) { RxJavaPlugins.onError(t); return; } actual.onError(t); } @Override public void onComplete() { if (done) { return; } synchronized (this) { if (done) { return; } done = true; if (emitting) { AppendOnlyLinkedArrayList<Object> q = queue; if (q == null) { q = new AppendOnlyLinkedArrayList<>(4); queue = q; } q.add(NotificationLite.complete()); return; } emitting = true; } actual.onComplete(); } /** Loops until all notifications in the queue has been processed. */ void emitLoop() { for (;;) { AppendOnlyLinkedArrayList<Object> q; synchronized (this) { q = queue; if (q == null) { emitting = false; return; } queue = null; } q.accept(actual); } } @Override public boolean hasSubscribers() { return actual.hasSubscribers(); } @Override public boolean hasThrowable() { return actual.hasThrowable(); } @Override @Nullable public Throwable getThrowable() { return actual.getThrowable(); } @Override public boolean hasComplete() { return actual.hasComplete(); } }
SerializedProcessor
java
apache__spark
common/network-common/src/main/java/org/apache/spark/network/shuffledb/LevelDB.java
{ "start": 883, "end": 1487 }
class ____ implements DB { private final org.iq80.leveldb.DB db; public LevelDB(org.iq80.leveldb.DB db) { this.db = db; } @Override public void put(byte[] key, byte[] value) { db.put(key, value); } @Override public byte[] get(byte[] key) { return db.get(key); } @Override public void delete(byte[] key) { db.delete(key); } @Override public void close() throws IOException { db.close(); } @Override public DBIterator iterator() { return new LevelDBIterator(db.iterator()); } }
LevelDB
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/support/EnvironmentPostProcessorApplicationListener.java
{ "start": 2706, "end": 7968 }
class ____ implements SmartApplicationListener, Ordered { private static final String AOT_FEATURE_NAME = "EnvironmentPostProcessor"; /** * The default order for the processor. */ public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 10; private final DeferredLogs deferredLogs; private int order = DEFAULT_ORDER; private final Function<@Nullable ClassLoader, EnvironmentPostProcessorsFactory> postProcessorsFactory; /** * Create a new {@link EnvironmentPostProcessorApplicationListener} with * {@link EnvironmentPostProcessor} classes loaded through {@code spring.factories}. */ public EnvironmentPostProcessorApplicationListener() { this(EnvironmentPostProcessorsFactory::fromSpringFactories); } /** * Create a new {@link EnvironmentPostProcessorApplicationListener} with post * processors created by the given factory. * @param postProcessorsFactory the post processors factory */ private EnvironmentPostProcessorApplicationListener( Function<@Nullable ClassLoader, EnvironmentPostProcessorsFactory> postProcessorsFactory) { this.postProcessorsFactory = postProcessorsFactory; this.deferredLogs = new DeferredLogs(); } /** * Factory method that creates an {@link EnvironmentPostProcessorApplicationListener} * with a specific {@link EnvironmentPostProcessorsFactory}. * @param postProcessorsFactory the environment post processor factory * @return an {@link EnvironmentPostProcessorApplicationListener} instance */ public static EnvironmentPostProcessorApplicationListener with( EnvironmentPostProcessorsFactory postProcessorsFactory) { return new EnvironmentPostProcessorApplicationListener((classloader) -> postProcessorsFactory); } @Override public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(eventType) || ApplicationPreparedEvent.class.isAssignableFrom(eventType) || ApplicationFailedEvent.class.isAssignableFrom(eventType); } @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent environmentPreparedEvent) { onApplicationEnvironmentPreparedEvent(environmentPreparedEvent); } if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent(); } if (event instanceof ApplicationFailedEvent) { onApplicationFailedEvent(); } } private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); SpringApplication application = event.getSpringApplication(); List<EnvironmentPostProcessor> postProcessors = getEnvironmentPostProcessors(application.getResourceLoader(), event.getBootstrapContext()); addAotGeneratedEnvironmentPostProcessorIfNecessary(postProcessors, application); for (EnvironmentPostProcessor postProcessor : postProcessors) { postProcessor.postProcessEnvironment(environment, application); } } private void onApplicationPreparedEvent() { finish(); } private void onApplicationFailedEvent() { finish(); } private void finish() { this.deferredLogs.switchOverAll(); } List<EnvironmentPostProcessor> getEnvironmentPostProcessors(@Nullable ResourceLoader resourceLoader, ConfigurableBootstrapContext bootstrapContext) { ClassLoader classLoader = (resourceLoader != null) ? resourceLoader.getClassLoader() : null; EnvironmentPostProcessorsFactory postProcessorsFactory = this.postProcessorsFactory.apply(classLoader); return postProcessorsFactory.getEnvironmentPostProcessors(this.deferredLogs, bootstrapContext); } private void addAotGeneratedEnvironmentPostProcessorIfNecessary(List<EnvironmentPostProcessor> postProcessors, SpringApplication springApplication) { if (AotDetector.useGeneratedArtifacts()) { ClassLoader classLoader = (springApplication.getResourceLoader() != null) ? springApplication.getResourceLoader().getClassLoader() : null; Class<?> mainApplicationClass = springApplication.getMainApplicationClass(); Assert.state(mainApplicationClass != null, "mainApplicationClass not found"); String postProcessorClassName = mainApplicationClass.getName() + "__" + AOT_FEATURE_NAME; if (ClassUtils.isPresent(postProcessorClassName, classLoader)) { postProcessors.add(0, instantiateEnvironmentPostProcessor(postProcessorClassName, classLoader)); } } } private EnvironmentPostProcessor instantiateEnvironmentPostProcessor(String postProcessorClassName, @Nullable ClassLoader classLoader) { try { Class<?> initializerClass = ClassUtils.resolveClassName(postProcessorClassName, classLoader); Assert.isAssignable(EnvironmentPostProcessor.class, initializerClass); return (EnvironmentPostProcessor) BeanUtils.instantiateClass(initializerClass); } catch (BeanInstantiationException ex) { throw new IllegalArgumentException( "Failed to instantiate EnvironmentPostProcessor: " + postProcessorClassName, ex); } } @Override public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } /** * Contribute a {@code <Application>__EnvironmentPostProcessor}
EnvironmentPostProcessorApplicationListener
java
bumptech__glide
annotation/src/main/java/com/bumptech/glide/annotation/GlideOption.java
{ "start": 3538, "end": 5086 }
class ____, a compile time error will result. */ int override() default OVERRIDE_NONE; /** * Sets the name for the generated static version of this method. * * <p>If this value is not set, the static method name is just the original method name with "Of" * appended. */ String staticMethodName() default ""; /** * {@code true} to indicate that it's safe to statically memoize the result of this method using * {@code com.bumptech.glide.request.RequestOptions#autoClone()}. * * <p>This method should only be used for no-arg methods where there's only a single possible * value. * * <p>Memoization can save object allocations for frequently used options. */ boolean memoizeStaticMethod() default false; /** * {@code true} to prevent a static builder method from being generated. * * <p>By default static methods are generated for all methods annotated with {@link GlideOption}. * These static factory methods allow for a cleaner API when used with {@code * com.bumptech.glide.RequestBuilder#apply}. The static factory method by default simply creates a * new {@code com.bumptech.glide.request.RequestOptions} object, calls the instance version of the * method on it and returns it. For example: * * <pre> * <code> * public static GlideOptions noAnimation() { * return new GlideOptions().dontAnimate(); * } * </code> * </pre> * * @see #memoizeStaticMethod() * @see #staticMethodName() */ boolean skipStaticMethod() default false; }
match
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tuple/internal/AnonymousTupleSqmAssociationPathSourceNew.java
{ "start": 1000, "end": 3077 }
class ____<O, J> extends AnonymousTupleSqmPathSourceNew<J> implements SqmSingularPersistentAttribute<O, J> { private final SimpleDomainType<J> domainType; public AnonymousTupleSqmAssociationPathSourceNew( String localPathName, SqmPathSource<J> pathSource, SqmDomainType<J> sqmPathType, SimpleDomainType<J> domainType) { super( localPathName, pathSource, sqmPathType ); this.domainType = domainType; } @Override public SqmJoin<O, J> createSqmJoin( SqmFrom<?, O> lhs, SqmJoinType joinType, @Nullable String alias, boolean fetched, SqmCreationState creationState) { return new SqmSingularJoin<>( lhs, this, alias, joinType, fetched, creationState.getCreationContext().getNodeBuilder() ); } @Override public Class<J> getBindableJavaType() { return domainType.getJavaType(); } @Override public Class<J> getJavaType() { return domainType.getJavaType(); } @Override public SimpleDomainType<J> getType() { return domainType; } @Override public ManagedDomainType<O> getDeclaringType() { return null; } @Override public SqmPathSource<J> getSqmPathSource() { return this; } @Override public boolean isId() { return false; } @Override public boolean isVersion() { return false; } @Override public boolean isOptional() { return true; } @Override public JavaType<J> getAttributeJavaType() { return domainType.getExpressibleJavaType(); } @Override public AttributeClassification getAttributeClassification() { return AttributeClassification.MANY_TO_ONE; } @Override public SimpleDomainType<?> getKeyGraphType() { return domainType; } @Override public String getName() { return getPathName(); } @Override public PersistentAttributeType getPersistentAttributeType() { return PersistentAttributeType.MANY_TO_ONE; } @Override public Member getJavaMember() { return null; } @Override public boolean isAssociation() { return true; } @Override public boolean isCollection() { return false; } }
AnonymousTupleSqmAssociationPathSourceNew
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosAuthenticationToken.java
{ "start": 588, "end": 1120 }
class ____ an AuthenticationToken for Kerberos authentication * using SPNEGO. The token stores base 64 decoded token bytes, extracted from * the Authorization header with auth scheme 'Negotiate'. * <p> * Example Authorization header "Authorization: Negotiate * YIIChgYGKwYBBQUCoII..." * <p> * If there is any error handling during extraction of 'Negotiate' header then * it throws {@link ElasticsearchSecurityException} with * {@link RestStatus#UNAUTHORIZED} and header 'WWW-Authenticate: Negotiate' */ public final
represents