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
micronaut-projects__micronaut-core
inject-java/src/main/java/io/micronaut/annotation/processing/visitor/JavaElementFactory.java
{ "start": 7596, "end": 9584 }
class ____ be a JavaEnumElement"); } failIfPostponeIsNeeded(owningType, enumConstant); return new JavaEnumConstantElement( (JavaEnumElement) owningType, new JavaNativeElement.Variable(enumConstant), annotationMetadataFactory, visitorContext ); } @NonNull @Override public JavaFieldElement newFieldElement(@NonNull ClassElement owningType, @NonNull VariableElement field, @NonNull ElementAnnotationMetadataFactory annotationMetadataFactory) { failIfPostponeIsNeeded(owningType, field); return new JavaFieldElement( (JavaClassElement) owningType, new JavaNativeElement.Variable(field), annotationMetadataFactory, visitorContext ); } private void failIfPostponeIsNeeded(TypedElement member, ExecutableElement executableElement) { List<? extends VariableElement> parameters = executableElement.getParameters(); for (VariableElement parameter : parameters) { failIfPostponeIsNeeded(member, parameter); } TypeMirror returnType = executableElement.getReturnType(); TypeKind returnKind = returnType.getKind(); if (returnKind == TypeKind.ERROR) { throw new PostponeToNextRoundException(member, member.getName() + " " + executableElement); } } private void failIfPostponeIsNeeded(TypedElement member, VariableElement variableElement) { TypeMirror type = variableElement.asType(); if (type.getKind() == TypeKind.ERROR) { throw new PostponeToNextRoundException(member, member.getName() + " " + variableElement); } } private static void validateOwningClass(ClassElement owningClass) { if (!(owningClass instanceof JavaClassElement)) { throw new IllegalArgumentException("Declaring
must
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/PostDataFlushRequestTests.java
{ "start": 496, "end": 1530 }
class ____ extends AbstractWireSerializingTestCase<Request> { @Override protected Request createTestInstance() { Request request = new Request(randomAlphaOfLengthBetween(1, 20)); request.setCalcInterim(randomBoolean()); if (randomBoolean()) { request.setStart(randomAlphaOfLengthBetween(1, 20)); } if (randomBoolean()) { request.setEnd(randomAlphaOfLengthBetween(1, 20)); } if (randomBoolean()) { request.setAdvanceTime(randomAlphaOfLengthBetween(1, 20)); } return request; } @Override protected Request mutateInstance(Request instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Writeable.Reader<Request> instanceReader() { return Request::new; } public void testNullJobIdThrows() { expectThrows(IllegalArgumentException.class, () -> new Request((String) null)); } }
PostDataFlushRequestTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/FrequencyCappedAction.java
{ "start": 654, "end": 1453 }
class ____ { private final LongSupplier currentTimeMillisSupplier; private TimeValue minInterval; private long next; public FrequencyCappedAction(LongSupplier currentTimeMillisSupplier, TimeValue initialDelay) { this.currentTimeMillisSupplier = currentTimeMillisSupplier; this.minInterval = TimeValue.MAX_VALUE; this.next = currentTimeMillisSupplier.getAsLong() + initialDelay.getMillis(); } public void setMinInterval(TimeValue minInterval) { this.minInterval = minInterval; } public void maybeExecute(Runnable runnable) { var current = currentTimeMillisSupplier.getAsLong(); if (current >= next) { next = current + minInterval.millis(); runnable.run(); } } }
FrequencyCappedAction
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/script/field/IpDocValuesField.java
{ "start": 1322, "end": 1711 }
class ____ extends AbstractScriptFieldFactory<IPAddress> implements Field<IPAddress>, DocValuesScriptFieldFactory, ScriptDocValues.Supplier<String> { protected final String name; protected final ScriptDocValues.Supplier<InetAddress> raw; // used for backwards compatibility for old-style "doc" access // as a delegate to this field
IpDocValuesField
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/kotlin/ClassWithTripleTest.java
{ "start": 768, "end": 1298 }
class ____ extends ClassLoader { public ExtClassLoader() throws IOException { super(Thread.currentThread().getContextClassLoader()); { byte[] bytes; InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/ClassWithTriple.clazz"); bytes = IOUtils.toByteArray(is); is.close(); super.defineClass("ClassWithTriple", bytes, 0, bytes.length); } } } }
ExtClassLoader
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/method/RequestMappingInfo.java
{ "start": 16367, "end": 20427 }
class ____ implements Builder { private String[] paths; private RequestMethod @Nullable [] methods; private String @Nullable [] params; private String @Nullable [] headers; private String @Nullable [] consumes; private String @Nullable [] produces; private @Nullable String version; private boolean hasContentType; private boolean hasAccept; private @Nullable String mappingName; private @Nullable RequestCondition<?> customCondition; private BuilderConfiguration options = new BuilderConfiguration(); public DefaultBuilder(String... paths) { this.paths = paths; } @Override public Builder paths(String... paths) { this.paths = paths; return this; } @Override public DefaultBuilder methods(RequestMethod... methods) { this.methods = methods; return this; } @Override public DefaultBuilder params(String... params) { this.params = params; return this; } @Override public DefaultBuilder headers(String... headers) { for (String header : headers) { this.hasContentType = this.hasContentType || header.contains("Content-Type") || header.contains("content-type"); this.hasAccept = this.hasAccept || header.contains("Accept") || header.contains("accept"); } this.headers = headers; return this; } @Override public DefaultBuilder consumes(String... consumes) { this.consumes = consumes; return this; } @Override public DefaultBuilder produces(String... produces) { this.produces = produces; return this; } @Override public Builder version(String version) { this.version = version; return this; } @Override public DefaultBuilder mappingName(String name) { this.mappingName = name; return this; } @Override public DefaultBuilder customCondition(RequestCondition<?> condition) { this.customCondition = condition; return this; } @Override public Builder options(BuilderConfiguration options) { this.options = options; return this; } @Override public RequestMappingInfo build() { PathPatternParser parser = (this.options.getPatternParser() != null ? this.options.getPatternParser() : PathPatternParser.defaultInstance); RequestedContentTypeResolver contentTypeResolver = this.options.getContentTypeResolver(); ApiVersionStrategy strategy = this.options.getApiVersionStrategy(); Assert.state(strategy != null || !StringUtils.hasText(this.version), "API version specified, but no ApiVersionStrategy configured"); VersionRequestCondition versionCondition = new VersionRequestCondition(this.version, strategy); return new RequestMappingInfo(this.mappingName, isEmpty(this.paths) ? null : new PatternsRequestCondition(parse(this.paths, parser)), ObjectUtils.isEmpty(this.methods) ? null : new RequestMethodsRequestCondition(this.methods), ObjectUtils.isEmpty(this.params) ? null : new ParamsRequestCondition(this.params), ObjectUtils.isEmpty(this.headers) ? null : new HeadersRequestCondition(this.headers), ObjectUtils.isEmpty(this.consumes) && !this.hasContentType ? null : new ConsumesRequestCondition(this.consumes, this.headers), ObjectUtils.isEmpty(this.produces) && !this.hasAccept ? null : new ProducesRequestCondition(this.produces, this.headers, contentTypeResolver), versionCondition, this.customCondition, this.options); } static List<PathPattern> parse(String[] patterns, PathPatternParser parser) { if (isEmpty(patterns)) { return Collections.emptyList(); } List<PathPattern> result = new ArrayList<>(patterns.length); for (String pattern : patterns) { pattern = parser.initFullPathPattern(pattern); result.add(parser.parse(pattern)); } return result; } static boolean isEmpty(String[] patterns) { if (!ObjectUtils.isEmpty(patterns)) { for (String pattern : patterns) { if (StringUtils.hasText(pattern)) { return false; } } } return true; } } private static
DefaultBuilder
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/service/invoker/HttpServiceMethodTests.java
{ "start": 2578, "end": 10891 }
class ____ { private static final ParameterizedTypeReference<String> BODY_TYPE = new ParameterizedTypeReference<>() {}; private final TestExchangeAdapter client = new TestExchangeAdapter(); private final TestReactorExchangeAdapter reactorClient = new TestReactorExchangeAdapter(); private final HttpServiceProxyFactory proxyFactory = HttpServiceProxyFactory.builder().exchangeAdapter(this.client).build(); private final HttpServiceProxyFactory reactorProxyFactory = HttpServiceProxyFactory.builder().exchangeAdapter(this.reactorClient).build(); @Test void service() { Service service = this.proxyFactory.createClient(Service.class); service.execute(); HttpHeaders headers = service.getHeaders(); assertThat(headers).isNotNull(); String body = service.getBody(); assertThat(body).isEqualTo(this.client.getInvokedMethodName()); Optional<String> optional = service.getBodyOptional(); assertThat(optional.get()).isEqualTo("exchangeForBody"); ResponseEntity<String> entity = service.getEntity(); assertThat(entity.getBody()).isEqualTo("exchangeForEntity"); ResponseEntity<Void> voidEntity = service.getVoidEntity(); assertThat(voidEntity.getBody()).isNull(); List<String> list = service.getList(); assertThat(list).containsOnly("exchangeForBody"); } @Test void reactorService() { ReactorService service = this.reactorProxyFactory.createClient(ReactorService.class); Mono<Void> voidMono = service.execute(); StepVerifier.create(voidMono).verifyComplete(); verifyReactorClientInvocation("exchangeForMono", null); Mono<HttpHeaders> headersMono = service.getHeaders(); StepVerifier.create(headersMono).expectNextCount(1).verifyComplete(); verifyReactorClientInvocation("exchangeForHeadersMono", null); Mono<String> body = service.getBody(); StepVerifier.create(body).expectNext("exchangeForBodyMono").verifyComplete(); verifyReactorClientInvocation("exchangeForBodyMono", BODY_TYPE); Flux<String> fluxBody = service.getFluxBody(); StepVerifier.create(fluxBody).expectNext("exchange", "For", "Body", "Flux").verifyComplete(); verifyReactorClientInvocation("exchangeForBodyFlux", BODY_TYPE); Mono<ResponseEntity<Void>> voidEntity = service.getVoidEntity(); StepVerifier.create(voidEntity).expectNext(ResponseEntity.ok().build()).verifyComplete(); verifyReactorClientInvocation("exchangeForBodilessEntityMono", null); Mono<ResponseEntity<String>> entity = service.getEntity(); StepVerifier.create(entity).expectNext(ResponseEntity.ok("exchangeForEntityMono")); verifyReactorClientInvocation("exchangeForEntityMono", BODY_TYPE); Mono<ResponseEntity<Flux<String>>> fluxEntity = service.getFluxEntity(); StepVerifier.create(fluxEntity.flatMapMany(HttpEntity::getBody)) .expectNext("exchange", "For", "Entity", "Flux") .verifyComplete(); verifyReactorClientInvocation("exchangeForEntityFlux", BODY_TYPE); assertThat(service.getDefaultMethodValue()).isEqualTo("default value"); } @Test void rxJavaService() { RxJavaService service = this.reactorProxyFactory.createClient(RxJavaService.class); Completable completable = service.execute(); assertThat(completable).isNotNull(); Single<HttpHeaders> headersSingle = service.getHeaders(); assertThat(headersSingle.blockingGet()).isNotNull(); Single<String> bodySingle = service.getBody(); assertThat(bodySingle.blockingGet()).isEqualTo("exchangeForBodyMono"); Flowable<String> bodyFlow = service.getFlowableBody(); assertThat(bodyFlow.toList().blockingGet()).containsExactly("exchange", "For", "Body", "Flux"); Single<ResponseEntity<Void>> voidEntity = service.getVoidEntity(); assertThat(voidEntity.blockingGet().getBody()).isNull(); Single<ResponseEntity<String>> entitySingle = service.getEntity(); assertThat(entitySingle.blockingGet().getBody()).isEqualTo("exchangeForEntityMono"); Single<ResponseEntity<Flowable<String>>> entityFlow = service.getFlowableEntity(); Flowable<String> body = (entityFlow.blockingGet()).getBody(); assertThat(body.toList().blockingGet()).containsExactly("exchange", "For", "Entity", "Flux"); } @Test void methodAnnotatedService() { MethodLevelAnnotatedService service = this.proxyFactory.createClient(MethodLevelAnnotatedService.class); service.performGet(); HttpRequestValues requestValues = this.client.getRequestValues(); assertThat(requestValues.getHttpMethod()).isEqualTo(HttpMethod.GET); assertThat(requestValues.getUriTemplate()).isEmpty(); assertThat(requestValues.getHeaders().getContentType()).isNull(); assertThat(requestValues.getHeaders().getAccept()).isEmpty(); service.performPost(); requestValues = this.client.getRequestValues(); assertThat(requestValues.getHttpMethod()).isEqualTo(HttpMethod.POST); assertThat(requestValues.getUriTemplate()).isEqualTo("/url"); assertThat(requestValues.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON); assertThat(requestValues.getHeaders().getAccept()).containsOnly(MediaType.APPLICATION_JSON); service.performGetWithHeaders(); requestValues = this.client.getRequestValues(); assertThat(requestValues.getHttpMethod()).isEqualTo(HttpMethod.GET); assertThat(requestValues.getUriTemplate()).isEmpty(); assertThat(requestValues.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON); assertThat(requestValues.getHeaders().getAccept()).isEmpty(); assertThat(requestValues.getHeaders().get("CustomHeader")).containsExactly("a", "b", "c"); } @Test void typeAndMethodAnnotatedService() { MethodLevelAnnotatedService service = HttpServiceProxyFactory.builder() .exchangeAdapter(this.client) .embeddedValueResolver(value -> (value.equals("${baseUrl}") ? "/base" : value)) .build() .createClient(TypeAndMethodLevelAnnotatedService.class); service.performGet(); HttpRequestValues requestValues = this.client.getRequestValues(); assertThat(requestValues.getHttpMethod()).isEqualTo(HttpMethod.GET); assertThat(requestValues.getUriTemplate()).isEqualTo("/base"); assertThat(requestValues.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_CBOR); assertThat(requestValues.getHeaders().getAccept()).containsOnly(MediaType.APPLICATION_CBOR); service.performPost(); requestValues = this.client.getRequestValues(); assertThat(requestValues.getHttpMethod()).isEqualTo(HttpMethod.POST); assertThat(requestValues.getUriTemplate()).isEqualTo("/base/url"); assertThat(requestValues.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON); assertThat(requestValues.getHeaders().getAccept()).containsOnly(MediaType.APPLICATION_JSON); } @Test void httpRequestValuesProcessor() { HttpServiceProxyFactory.builder() .exchangeAdapter(this.client) .httpRequestValuesProcessor((m, p, a, builder) -> builder.addAttribute("foo", "a")) .build() .createClient(Service.class) .execute(); assertThat(this.client.getRequestValues().getAttributes().get("foo")).isEqualTo("a"); } @Test // gh-32049 void multipleAnnotationsAtClassLevel() { Class<?> serviceInterface = MultipleClassLevelAnnotationsService.class; assertThatIllegalStateException() .isThrownBy(() -> this.proxyFactory.createClient(serviceInterface)) .withMessageContainingAll( "Multiple @HttpExchange annotations found on " + serviceInterface, HttpExchange.class.getSimpleName(), ExtraHttpExchange.class.getSimpleName() ); } @Test // gh-32049 void multipleAnnotationsAtMethodLevel() throws NoSuchMethodException { Class<?> serviceInterface = MultipleMethodLevelAnnotationsService.class; Method method = serviceInterface.getMethod("post"); assertThatIllegalStateException() .isThrownBy(() -> this.proxyFactory.createClient(serviceInterface)) .withMessageContainingAll( "Multiple @HttpExchange annotations found on method " + method, PostExchange.class.getSimpleName(), PutExchange.class.getSimpleName() ); } protected void verifyReactorClientInvocation(String methodName, @Nullable ParameterizedTypeReference<?> expectedBodyType) { assertThat(this.reactorClient.getInvokedMethodName()).isEqualTo(methodName); assertThat(this.reactorClient.getBodyType()).isEqualTo(expectedBodyType); } @SuppressWarnings("unused") private
HttpServiceMethodTests
java
apache__camel
components/camel-ai/camel-langchain4j-tokenizer/src/main/java/org/apache/camel/component/langchain4j/tokenizer/util/SplitterUtil.java
{ "start": 1841, "end": 5405 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(SplitterUtil.class); private SplitterUtil() { } public static DocumentSplitter byName(String name, LangChain4JConfiguration configuration) { assert name != null : "The splitter name must be provided"; int maxTokens = configuration.getMaxTokens(); int maxOverlap = configuration.getMaxOverlap(); String type = configuration.getType(); final TokenCountEstimator countEstimator = buildTokenizer(configuration, type); LOG.debug("Creating a {} splitter", name); switch (name) { case SplitterTypes.SENTENCE -> { return new DocumentBySentenceSplitter(maxTokens, maxOverlap, countEstimator); } case SplitterTypes.PARAGRAPH -> { return new DocumentByParagraphSplitter(maxTokens, maxOverlap, countEstimator); } case SplitterTypes.CHARACTER -> { return new DocumentByCharacterSplitter(maxTokens, maxOverlap, countEstimator); } case SplitterTypes.WORD -> { return new DocumentByWordSplitter(maxTokens, maxOverlap, countEstimator); } case SplitterTypes.LINE -> { return new DocumentByLineSplitter(maxTokens, maxOverlap, countEstimator); } default -> throw new IllegalArgumentException("Unknown splitter name: " + name); } } private static TokenCountEstimator buildTokenizer(LangChain4JConfiguration configuration, String type) { if (type == null) { throw new RuntimeCamelException("Invalid tokenizer type: null"); } String model = configuration.getModelName(); if (model == null) { return null; } return switch (type) { case TokenizerTypes.OPEN_AI -> new OpenAiTokenCountEstimator(model); case TokenizerTypes.AZURE -> new AzureOpenAiTokenCountEstimator(model); case TokenizerTypes.QWEN -> createQwenTokenizer(configuration); default -> throw new RuntimeCamelException("Unknown tokenizer type: " + type); }; } private static QwenTokenCountEstimator createQwenTokenizer(LangChain4JConfiguration configuration) { if (configuration instanceof LangChain4JQwenConfiguration qwenConfiguration) { return new QwenTokenCountEstimator(qwenConfiguration.getApiKey(), qwenConfiguration.getModelName()); } throw new RuntimeCamelException( "Invalid configuration type for the QwenTokenCountEstimator: " + configuration.getClass().getSimpleName() + ". Use LangChain4JQwenConfiguration"); } public static String[] split(DocumentSplitter splitter, String body) { if (splitter instanceof DocumentBySentenceSplitter ds) { return ds.split(body); } if (splitter instanceof DocumentByParagraphSplitter dp) { return dp.split(body); } if (splitter instanceof DocumentByCharacterSplitter dc) { return dc.split(body); } if (splitter instanceof DocumentByWordSplitter dw) { return dw.split(body); } if (splitter instanceof DocumentByLineSplitter dl) { return dl.split(body); } throw new RuntimeCamelException("Unsupported splitter type: " + splitter.getClass().getSimpleName()); } }
SplitterUtil
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/reactive/execution/ReactiveExecutionFlow.java
{ "start": 1326, "end": 4642 }
interface ____<T> extends ExecutionFlow<T> permits ReactorExecutionFlowImpl { /** * Creates a new reactive flow from a publisher. * * @param publisher The publisher * @param <K> THe flow value type * @return a new flow */ @NonNull static <K> ReactiveExecutionFlow<K> fromPublisher(@NonNull Publisher<K> publisher) { return (ReactiveExecutionFlow<K>) new ReactorExecutionFlowImpl(publisher); } /** * Creates a new reactive flow from a publisher. This method eagerly subscribes to the * publisher, and may return an immediate {@link ExecutionFlow} if possible. * * @param publisher The publisher * @param propagatedContext A context to propagate in the reactor context and as a thread-local * in the subscribe operation. * @param <K> The flow value type * @return a new flow * @since 4.8.0 */ @NonNull static <K> ExecutionFlow<K> fromPublisherEager(@NonNull Publisher<K> publisher, @NonNull PropagatedContext propagatedContext) { return ReactorExecutionFlowImpl.defuse(publisher, propagatedContext); } /** * Create a new reactive flow by invoking a supplier asynchronously. * * @param executor The executor * @param supplier The supplier * @param <K> The flow value type * @return a new flow */ @NonNull static <K> ReactiveExecutionFlow<K> async(@NonNull Executor executor, @NonNull Supplier<ExecutionFlow<K>> supplier) { Scheduler scheduler = Schedulers.fromExecutor(executor); return (ReactiveExecutionFlow<K>) new ReactorExecutionFlowImpl( Mono.fromSupplier(supplier).flatMap(ReactorExecutionFlowImpl::toMono).subscribeOn(scheduler) ); } /** * Creates a new reactive flow from other flow. * * @param flow The flow * @param <K> THe flow value type * @return a new flow */ @NonNull static <K> ReactiveExecutionFlow<K> fromFlow(@NonNull ExecutionFlow<K> flow) { if (flow instanceof ReactiveExecutionFlow<K> executionFlow) { return executionFlow; } return (ReactiveExecutionFlow<K>) new ReactorExecutionFlowImpl(ReactorExecutionFlowImpl.toMono(flow)); } /** * Returns the reactive flow represented by a publisher. * * @return The publisher */ @NonNull Publisher<T> toPublisher(); /** * Convert the given flow to a reactive publisher. The supplier is called for every * subscription to the publisher. * * @param flowSupplier The flow supplier * @param <K> The element type * @return The publisher */ @NonNull @SingleResult static <K> Publisher<K> toPublisher(@NonNull Supplier<@NonNull ExecutionFlow<K>> flowSupplier) { return (Publisher<K>) ReactorExecutionFlowImpl.toMono(flowSupplier); } /** * Convert the given flow to a reactive publisher. * * @param flow The flow * @param <K> The element type * @return The publisher */ @NonNull @SingleResult static <K> Publisher<K> toPublisher(@NonNull ExecutionFlow<K> flow) { return (Publisher<K>) ReactorExecutionFlowImpl.toMono(flow); } }
ReactiveExecutionFlow
java
apache__camel
components/camel-aws/camel-aws2-ddb/src/test/java/org/apache/camel/component/aws2/ddbstream/ShardTreeTest.java
{ "start": 1174, "end": 2724 }
class ____ { private final ShardTree underTest = new ShardTree(); @Test void shouldGetLeafShards() { underTest.populate(Arrays.asList(SHARD_0, SHARD_1, SHARD_2, SHARD_3, SHARD_4, SHARD_5, SHARD_6)); assertEquals(Arrays.asList(SHARD_5, SHARD_6, SHARD_3, SHARD_4), underTest.getLeaves()); } @Test void shouldReturnEmptyListIfAllShardsHaveAnEndingSequenceNumber() { underTest.populate(Arrays.asList(SHARD_0, SHARD_1, SHARD_2)); assertEquals(Arrays.asList(), underTest.getLeaves()); } @Test void shouldGetRootShards() { underTest.populate(Arrays.asList(SHARD_1, SHARD_2, SHARD_3, SHARD_4, SHARD_5, SHARD_6)); assertEquals(Arrays.asList(SHARD_1, SHARD_2), underTest.getRoots()); } @Test void shouldThrowIfNoUnparentedShardsCanBeFound() { Shard selfParentingShard = Shard.builder().shardId("SHARD_X").parentShardId("SHARD_X").build(); underTest.populate(Arrays.asList(selfParentingShard)); assertThrows(IllegalStateException.class, () -> underTest.getRoots()); } @Test void shouldGetChildShards() { underTest.populate(Arrays.asList(SHARD_0, SHARD_1, SHARD_2, SHARD_3, SHARD_4, SHARD_5, SHARD_6)); assertEquals(Arrays.asList(SHARD_5, SHARD_6), underTest.getChildren("SHARD_2")); } @Test void shouldReturnEmptyListIfTheShardHasNoChildren() { underTest.populate(Arrays.asList(SHARD_6)); assertEquals(Arrays.asList(), underTest.getChildren("SHARD_6")); } }
ShardTreeTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/mover/Mover.java
{ "start": 3418, "end": 10628 }
class ____ { private final StorageGroupMap<Source> sources = new StorageGroupMap<Source>(); private final StorageGroupMap<StorageGroup> targets = new StorageGroupMap<StorageGroup>(); private final EnumMap<StorageType, List<StorageGroup>> targetStorageTypeMap = new EnumMap<StorageType, List<StorageGroup>>(StorageType.class); private StorageMap() { for(StorageType t : StorageType.getMovableTypes()) { targetStorageTypeMap.put(t, new LinkedList<StorageGroup>()); } } private void add(Source source, StorageGroup target) { sources.put(source); if (target != null) { targets.put(target); getTargetStorages(target.getStorageType()).add(target); } } private Source getSource(MLocation ml) { return get(sources, ml); } private StorageGroup getTarget(String uuid, StorageType storageType) { return targets.get(uuid, storageType); } private static <G extends StorageGroup> G get(StorageGroupMap<G> map, MLocation ml) { return map.get(ml.datanode.getDatanodeUuid(), ml.storageType); } private List<StorageGroup> getTargetStorages(StorageType t) { return targetStorageTypeMap.get(t); } } private final Dispatcher dispatcher; private final StorageMap storages; private final List<Path> targetPaths; private final int retryMaxAttempts; private final AtomicInteger retryCount; private final Map<Long, Set<DatanodeInfo>> excludedPinnedBlocks; private final MoverMetrics metrics; private final NameNodeConnector nnc; private final BlockStoragePolicy[] blockStoragePolicies; Mover(NameNodeConnector nnc, Configuration conf, AtomicInteger retryCount, Map<Long, Set<DatanodeInfo>> excludedPinnedBlocks) { final long movedWinWidth = conf.getLong( DFSConfigKeys.DFS_MOVER_MOVEDWINWIDTH_KEY, DFSConfigKeys.DFS_MOVER_MOVEDWINWIDTH_DEFAULT); final int moverThreads = conf.getInt( DFSConfigKeys.DFS_MOVER_MOVERTHREADS_KEY, DFSConfigKeys.DFS_MOVER_MOVERTHREADS_DEFAULT); final int maxConcurrentMovesPerNode = conf.getInt( DFSConfigKeys.DFS_DATANODE_BALANCE_MAX_NUM_CONCURRENT_MOVES_KEY, DFSConfigKeys.DFS_DATANODE_BALANCE_MAX_NUM_CONCURRENT_MOVES_DEFAULT); final int maxNoMoveInterval = conf.getInt( DFSConfigKeys.DFS_MOVER_MAX_NO_MOVE_INTERVAL_KEY, DFSConfigKeys.DFS_MOVER_MAX_NO_MOVE_INTERVAL_DEFAULT); final int maxAttempts = conf.getInt( DFSConfigKeys.DFS_MOVER_RETRY_MAX_ATTEMPTS_KEY, DFSConfigKeys.DFS_MOVER_RETRY_MAX_ATTEMPTS_DEFAULT); if (maxAttempts >= 0) { this.retryMaxAttempts = maxAttempts; } else { LOG.warn(DFSConfigKeys.DFS_MOVER_RETRY_MAX_ATTEMPTS_KEY + " is " + "configured with a negative value, using default value of " + DFSConfigKeys.DFS_MOVER_RETRY_MAX_ATTEMPTS_DEFAULT); this.retryMaxAttempts = DFSConfigKeys.DFS_MOVER_RETRY_MAX_ATTEMPTS_DEFAULT; } this.retryCount = retryCount; this.dispatcher = new Dispatcher(nnc, Collections.<String> emptySet(), Collections.<String> emptySet(), movedWinWidth, moverThreads, 0, maxConcurrentMovesPerNode, maxNoMoveInterval, conf); this.storages = new StorageMap(); this.targetPaths = nnc.getTargetPaths(); this.blockStoragePolicies = new BlockStoragePolicy[1 << BlockStoragePolicySuite.ID_BIT_LENGTH]; this.excludedPinnedBlocks = excludedPinnedBlocks; this.nnc = nnc; this.metrics = MoverMetrics.create(this); } void init() throws IOException { initStoragePolicies(); final List<DatanodeStorageReport> reports = dispatcher.init(); for(DatanodeStorageReport r : reports) { final DDatanode dn = dispatcher.newDatanode(r.getDatanodeInfo()); for(StorageType t : StorageType.getMovableTypes()) { final Source source = dn.addSource(t, Long.MAX_VALUE, dispatcher); final long maxRemaining = getMaxRemaining(r, t); final StorageGroup target = maxRemaining > 0L ? dn.addTarget(t, maxRemaining) : null; storages.add(source, target); } } } private void initStoragePolicies() throws IOException { Collection<BlockStoragePolicy> policies = dispatcher.getDistributedFileSystem().getAllStoragePolicies(); for (BlockStoragePolicy policy : policies) { this.blockStoragePolicies[policy.getId()] = policy; } } private ExitStatus run() { try { init(); return new Processor().processNamespace().getExitStatus(); } catch (IllegalArgumentException e) { System.out.println(e + ". Exiting ..."); return ExitStatus.ILLEGAL_ARGUMENTS; } catch (IOException e) { System.out.println(e + ". Exiting ..."); LOG.error(e + ". Exiting ..."); return ExitStatus.IO_EXCEPTION; } finally { dispatcher.shutdownNow(); } } public NameNodeConnector getNnc() { return nnc; } DBlock newDBlock(LocatedBlock lb, List<MLocation> locations, ErasureCodingPolicy ecPolicy) { Block blk = lb.getBlock().getLocalBlock(); DBlock db; if (lb.isStriped()) { LocatedStripedBlock lsb = (LocatedStripedBlock) lb; byte[] indices = new byte[lsb.getBlockIndices().length]; for (int i = 0; i < indices.length; i++) { indices[i] = (byte) lsb.getBlockIndices()[i]; } db = new DBlockStriped(blk, indices, (short) ecPolicy.getNumDataUnits(), ecPolicy.getCellSize()); } else { db = new DBlock(blk); } List<Integer> adjustList = new ArrayList<>(); for (int i = 0; i < locations.size(); i++) { MLocation ml = locations.get(i); StorageGroup source = storages.getSource(ml); if (source != null) { db.addLocation(source); } else if (lb.isStriped()) { // some datanode may not in storages due to decommission or maintenance operation // or balancer cli with "-exclude" parameter adjustList.add(i); } } if (!adjustList.isEmpty()) { // block.locations mismatch with block.indices // adjust indices to get correct internalBlock ((DBlockStriped) db).adjustIndices(adjustList); Preconditions.checkArgument(((DBlockStriped) db).getIndices().length == db.getLocations().size()); } return db; } private static long getMaxRemaining(DatanodeStorageReport report, StorageType t) { long max = 0L; for(StorageReport r : report.getStorageReports()) { if (r.getStorage().getStorageType() == t) { if (r.getRemaining() > max) { max = r.getRemaining(); } } } return max; } /** * convert a snapshot path to non-snapshot path. E.g., * /foo/.snapshot/snapshot-name/bar --> /foo/bar */ private static String convertSnapshotPath(String[] pathComponents) { StringBuilder sb = new StringBuilder(Path.SEPARATOR); for (int i = 0; i < pathComponents.length; i++) { if (pathComponents[i].equals(HdfsConstants.DOT_SNAPSHOT_DIR)) { i++; } else { sb.append(pathComponents[i]); } } return sb.toString(); }
StorageMap
java
grpc__grpc-java
api/src/main/java/io/grpc/EquivalentAddressGroup.java
{ "start": 1317, "end": 5527 }
class ____ { /** * The authority to be used when constructing Subchannels for this EquivalentAddressGroup. * However, if the channel has overridden authority via * {@link ManagedChannelBuilder#overrideAuthority(String)}, the transport will use the channel's * authority override. * * <p>The authority <strong>must</strong> be from a trusted source, because if the authority is * tampered with, RPCs may be sent to attackers which may leak sensitive user data. If the * authority was acquired by doing I/O, the communication must be authenticated (e.g., via TLS). * Recognize that the server that provided the authority can trivially impersonate the service. */ @Attr @ExperimentalApi("https://github.com/grpc/grpc-java/issues/6138") public static final Attributes.Key<String> ATTR_AUTHORITY_OVERRIDE = Attributes.Key.create("io.grpc.EquivalentAddressGroup.ATTR_AUTHORITY_OVERRIDE"); /** * The name of the locality that this EquivalentAddressGroup is in. */ public static final Attributes.Key<String> ATTR_LOCALITY_NAME = Attributes.Key.create("io.grpc.EquivalentAddressGroup.LOCALITY"); private final List<SocketAddress> addrs; private final Attributes attrs; /** * {@link SocketAddress} docs say that the addresses are immutable, so we cache the hashCode. */ private final int hashCode; /** * List constructor without {@link Attributes}. */ public EquivalentAddressGroup(List<SocketAddress> addrs) { this(addrs, Attributes.EMPTY); } /** * List constructor with {@link Attributes}. */ public EquivalentAddressGroup(List<SocketAddress> addrs, @Attr Attributes attrs) { Preconditions.checkArgument(!addrs.isEmpty(), "addrs is empty"); this.addrs = Collections.unmodifiableList(new ArrayList<>(addrs)); this.attrs = Preconditions.checkNotNull(attrs, "attrs"); // Attributes may contain mutable objects, which means Attributes' hashCode may change over // time, thus we don't cache Attributes' hashCode. hashCode = this.addrs.hashCode(); } /** * Singleton constructor without Attributes. */ public EquivalentAddressGroup(SocketAddress addr) { this(addr, Attributes.EMPTY); } /** * Singleton constructor with Attributes. */ public EquivalentAddressGroup(SocketAddress addr, @Attr Attributes attrs) { this(Collections.singletonList(addr), attrs); } /** * Returns an immutable list of the addresses. */ public List<SocketAddress> getAddresses() { return addrs; } /** * Returns the attributes. */ @Attr public Attributes getAttributes() { return attrs; } @Override public String toString() { // TODO(zpencer): Summarize return value if addr is very large return "[" + addrs + "/" + attrs + "]"; } @Override public int hashCode() { // Avoids creating an iterator on the underlying array list. return hashCode; } /** * Returns true if the given object is also an {@link EquivalentAddressGroup} with an equal * address list and equal attribute values. * * <p>Note that if the attributes include mutable values, it is possible for two objects to be * considered equal at one point in time and not equal at another (due to concurrent mutation of * attribute values). */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof EquivalentAddressGroup)) { return false; } EquivalentAddressGroup that = (EquivalentAddressGroup) other; if (addrs.size() != that.addrs.size()) { return false; } // Avoids creating an iterator on the underlying array list. for (int i = 0; i < addrs.size(); i++) { if (!addrs.get(i).equals(that.addrs.get(i))) { return false; } } if (!attrs.equals(that.attrs)) { return false; } return true; } /** * Annotation for {@link EquivalentAddressGroup}'s attributes. It follows the annotation semantics * defined by {@link Attributes}. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4972") @Retention(RetentionPolicy.SOURCE) @Documented public @
EquivalentAddressGroup
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/security/CredentialsTestJob.java
{ "start": 2890, "end": 3319 }
class ____ extends Mapper<IntWritable, IntWritable, IntWritable, NullWritable> { Credentials ts; protected void setup(Context context) throws IOException, InterruptedException { ts = context.getCredentials(); } public void map(IntWritable key, IntWritable value, Context context ) throws IOException, InterruptedException { checkSecrets(ts); } } public static
CredentialsTestMapper
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 18139, "end": 18333 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return dialect.getGlobalTemporaryTableStrategy() != null; } } public static
SupportsGlobalTemporaryTable
java
apache__camel
components/camel-aws/camel-aws2-sqs/src/test/java/org/apache/camel/component/aws2/sqs/SqsProducerDeleteQueueTest.java
{ "start": 1369, "end": 2443 }
class ____ extends CamelTestSupport { @BindToRegistry("client") AmazonSQSClientMock mock = new AmazonSQSClientMock("camel-1"); @EndpointInject("direct:start") private ProducerTemplate template; @EndpointInject("mock:result") private MockEndpoint result; @Test public void deleteMessage() throws Exception { result.expectedMessageCount(1); template.send("direct:start", new Processor() { @Override public void process(Exchange exchange) { } }); MockEndpoint.assertIsSatisfied(context); DeleteQueueResponse res = result.getExchanges().get(0).getIn().getBody(DeleteQueueResponse.class); assertNotNull(res); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").to("aws2-sqs://camel-1?amazonSQSClient=#client&operation=deleteQueue").to("mock:result"); } }; } }
SqsProducerDeleteQueueTest
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/slm/action/GetSnapshotLifecycleAction.java
{ "start": 1282, "end": 2561 }
class ____ extends AcknowledgedRequest<GetSnapshotLifecycleAction.Request> { private final String[] lifecycleIds; public Request(TimeValue masterNodeTimeout, TimeValue ackTimeout, String... lifecycleIds) { super(masterNodeTimeout, ackTimeout); this.lifecycleIds = Objects.requireNonNull(lifecycleIds, "ids may not be null"); } public Request(StreamInput in) throws IOException { super(in); lifecycleIds = in.readStringArray(); } public String[] getLifecycleIds() { return this.lifecycleIds; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArray(lifecycleIds); } @Override public int hashCode() { return Arrays.hashCode(lifecycleIds); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj.getClass() != getClass()) { return false; } Request other = (Request) obj; return Arrays.equals(lifecycleIds, other.lifecycleIds); } } public static
Request
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/arm-java/org/apache/hadoop/ipc/protobuf/TestRpcServiceProtosLegacy.java
{ "start": 76469, "end": 87350 }
interface ____ { /** * <code>rpc ping2(.hadoop.common.EmptyRequestProto) returns (.hadoop.common.EmptyResponseProto);</code> */ public abstract void ping2( com.google.protobuf.RpcController controller, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request, com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto> done); /** * <code>rpc echo2(.hadoop.common.EchoRequestProto) returns (.hadoop.common.EchoResponseProto);</code> */ public abstract void echo2( com.google.protobuf.RpcController controller, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoRequestProto request, com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto> done); /** * <code>rpc sleep(.hadoop.common.SleepRequestProto) returns (.hadoop.common.SleepResponseProto);</code> */ public abstract void sleep( com.google.protobuf.RpcController controller, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto request, com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepResponseProto> done); } public static com.google.protobuf.Service newReflectiveService( final Interface impl) { return new TestProtobufRpc2Proto() { @java.lang.Override public void ping2( com.google.protobuf.RpcController controller, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request, com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto> done) { impl.ping2(controller, request, done); } @java.lang.Override public void echo2( com.google.protobuf.RpcController controller, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoRequestProto request, com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto> done) { impl.echo2(controller, request, done); } @java.lang.Override public void sleep( com.google.protobuf.RpcController controller, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto request, com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepResponseProto> done) { impl.sleep(controller, request, done); } }; } public static com.google.protobuf.BlockingService newReflectiveBlockingService(final BlockingInterface impl) { return new com.google.protobuf.BlockingService() { public final com.google.protobuf.Descriptors.ServiceDescriptor getDescriptorForType() { return getDescriptor(); } public final com.google.protobuf.Message callBlockingMethod( com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException { if (method.getService() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "Service.callBlockingMethod() given method descriptor for " + "wrong service type."); } switch(method.getIndex()) { case 0: return impl.ping2(controller, (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto)request); case 1: return impl.echo2(controller, (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoRequestProto)request); case 2: return impl.sleep(controller, (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto)request); default: throw new java.lang.AssertionError("Can't get here."); } } public final com.google.protobuf.Message getRequestPrototype( com.google.protobuf.Descriptors.MethodDescriptor method) { if (method.getService() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "Service.getRequestPrototype() given method " + "descriptor for wrong service type."); } switch(method.getIndex()) { case 0: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto.getDefaultInstance(); case 1: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoRequestProto.getDefaultInstance(); case 2: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto.getDefaultInstance(); default: throw new java.lang.AssertionError("Can't get here."); } } public final com.google.protobuf.Message getResponsePrototype( com.google.protobuf.Descriptors.MethodDescriptor method) { if (method.getService() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "Service.getResponsePrototype() given method " + "descriptor for wrong service type."); } switch(method.getIndex()) { case 0: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.getDefaultInstance(); case 1: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto.getDefaultInstance(); case 2: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepResponseProto.getDefaultInstance(); default: throw new java.lang.AssertionError("Can't get here."); } } }; } /** * <code>rpc ping2(.hadoop.common.EmptyRequestProto) returns (.hadoop.common.EmptyResponseProto);</code> */ public abstract void ping2( com.google.protobuf.RpcController controller, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request, com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto> done); /** * <code>rpc echo2(.hadoop.common.EchoRequestProto) returns (.hadoop.common.EchoResponseProto);</code> */ public abstract void echo2( com.google.protobuf.RpcController controller, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoRequestProto request, com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto> done); /** * <code>rpc sleep(.hadoop.common.SleepRequestProto) returns (.hadoop.common.SleepResponseProto);</code> */ public abstract void sleep( com.google.protobuf.RpcController controller, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto request, com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepResponseProto> done); public static final com.google.protobuf.Descriptors.ServiceDescriptor getDescriptor() { return org.apache.hadoop.ipc.protobuf.TestRpcServiceProtosLegacy.getDescriptor().getServices().get(1); } public final com.google.protobuf.Descriptors.ServiceDescriptor getDescriptorForType() { return getDescriptor(); } public final void callMethod( com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request, com.google.protobuf.RpcCallback< com.google.protobuf.Message> done) { if (method.getService() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "Service.callMethod() given method descriptor for wrong " + "service type."); } switch(method.getIndex()) { case 0: this.ping2(controller, (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto)request, com.google.protobuf.RpcUtil.<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto>specializeCallback( done)); return; case 1: this.echo2(controller, (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoRequestProto)request, com.google.protobuf.RpcUtil.<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto>specializeCallback( done)); return; case 2: this.sleep(controller, (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto)request, com.google.protobuf.RpcUtil.<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepResponseProto>specializeCallback( done)); return; default: throw new java.lang.AssertionError("Can't get here."); } } public final com.google.protobuf.Message getRequestPrototype( com.google.protobuf.Descriptors.MethodDescriptor method) { if (method.getService() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "Service.getRequestPrototype() given method " + "descriptor for wrong service type."); } switch(method.getIndex()) { case 0: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto.getDefaultInstance(); case 1: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoRequestProto.getDefaultInstance(); case 2: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto.getDefaultInstance(); default: throw new java.lang.AssertionError("Can't get here."); } } public final com.google.protobuf.Message getResponsePrototype( com.google.protobuf.Descriptors.MethodDescriptor method) { if (method.getService() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "Service.getResponsePrototype() given method " + "descriptor for wrong service type."); } switch(method.getIndex()) { case 0: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.getDefaultInstance(); case 1: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto.getDefaultInstance(); case 2: return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepResponseProto.getDefaultInstance(); default: throw new java.lang.AssertionError("Can't get here."); } } public static Stub newStub( com.google.protobuf.RpcChannel channel) { return new Stub(channel); } public static final
Interface
java
quarkusio__quarkus
test-framework/junit5-component/src/main/java/io/quarkus/test/component/TestConfigProperty.java
{ "start": 1398, "end": 1480 }
interface ____ { TestConfigProperty[] value(); } }
TestConfigProperties
java
google__guice
core/src/com/google/inject/internal/InternalFlags.java
{ "start": 2711, "end": 2967 }
class ____ and the resulting classes are easier to unload. * * <p>Note: with this option you cannot look up fast/enhanced types by name or mock/spy them. */ ANONYMOUS, /** * Attempt to define fast/enhanced types in the same
loading
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/google/MultimapAsMapGetTester.java
{ "start": 2098, "end": 5246 }
class ____<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> { @CollectionSize.Require(SEVERAL) @MapFeature.Require(SUPPORTS_REMOVE) public void testPropagatesRemoveToMultimap() { resetContainer(mapEntry(k0(), v0()), mapEntry(k0(), v3()), mapEntry(k0(), v2())); Collection<V> result = multimap().asMap().get(k0()); assertTrue(result.remove(v0())); assertFalse(multimap().containsEntry(k0(), v0())); assertEquals(2, multimap().size()); } @CollectionSize.Require(absent = ZERO) @MapFeature.Require(SUPPORTS_REMOVE) public void testPropagatesRemoveLastElementToMultimap() { Collection<V> result = multimap().asMap().get(k0()); assertTrue(result.remove(v0())); assertGet(k0()); } @CollectionSize.Require(absent = ZERO) @MapFeature.Require(SUPPORTS_REMOVE) public void testPropagatesClearToMultimap() { Collection<V> result = multimap().asMap().get(k0()); result.clear(); assertGet(k0()); assertEmpty(result); } @CollectionSize.Require(absent = ZERO) @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES}) public void testAddNullValue() { Collection<V> result = multimap().asMap().get(k0()); assertTrue(result.add(null)); assertTrue(multimap().containsEntry(k0(), null)); } @CollectionSize.Require(absent = ZERO) @MapFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUE_QUERIES}) public void testRemoveNullValue() { Collection<V> result = multimap().asMap().get(k0()); assertFalse(result.remove(null)); } @CollectionSize.Require(absent = ZERO) @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES) public void testAddNullValueUnsupported() { Collection<V> result = multimap().asMap().get(k0()); assertThrows(NullPointerException.class, () -> result.add(null)); } @CollectionSize.Require(absent = ZERO) @MapFeature.Require(SUPPORTS_PUT) public void testPropagatesAddToMultimap() { Collection<V> result = multimap().asMap().get(k0()); result.add(v3()); assertContentsAnyOrder(multimap().get(k0()), v0(), v3()); } @CollectionSize.Require(absent = ZERO) @MapFeature.Require({SUPPORTS_REMOVE, SUPPORTS_PUT}) public void testPropagatesRemoveThenAddToMultimap() { int oldSize = getNumElements(); Collection<V> result = multimap().asMap().get(k0()); assertTrue(result.remove(v0())); assertFalse(multimap().containsKey(k0())); assertFalse(multimap().containsEntry(k0(), v0())); assertEmpty(result); assertTrue(result.add(v1())); assertTrue(result.add(v2())); assertContentsAnyOrder(result, v1(), v2()); assertContentsAnyOrder(multimap().get(k0()), v1(), v2()); assertTrue(multimap().containsKey(k0())); assertFalse(multimap().containsEntry(k0(), v0())); assertTrue(multimap().containsEntry(k0(), v2())); assertEquals(oldSize + 1, multimap().size()); } @CollectionSize.Require(absent = ZERO) @MapFeature.Require(SUPPORTS_REMOVE) public void testReflectsMultimapRemove() { Collection<V> result = multimap().asMap().get(k0()); multimap().removeAll(k0()); assertEmpty(result); } }
MultimapAsMapGetTester
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/FileMoveWithInMessageTest.java
{ "start": 1262, "end": 2564 }
class ____ extends ContextTestSupport { @Test public void testMove() { String uri = fileUri(); template.sendBodyAndHeader(uri, "Hello World1", Exchange.FILE_NAME, "hello1.txt"); template.sendBodyAndHeader(uri, "Hello World2", Exchange.FILE_NAME, "hello2.txt"); // trigger template.sendBody("seda:triggerIn", ""); File file1 = new File(testDirectory().toFile(), "archive/hello1.txt"); await().atMost(10, TimeUnit.SECONDS) .untilAsserted(() -> assertTrue(file1.exists(), "The file should exist in the archive folder")); File file2 = new File(testDirectory().toFile(), "archive/hello2.txt"); await().atMost(10, TimeUnit.SECONDS) .untilAsserted(() -> assertTrue(file2.exists(), "The file should exist in the archive folder")); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("seda:triggerIn") .pollEnrich(fileUri() + "?move=archive") .pollEnrich(fileUri() + "?move=archive") .process(new TestProcessor()); } }; } private static
FileMoveWithInMessageTest
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/dynamic/RedisCommandsClusterIntegrationTests.java
{ "start": 793, "end": 2334 }
class ____ extends TestSupport { private final StatefulRedisClusterConnection<String, String> connection; @Inject RedisCommandsClusterIntegrationTests(StatefulRedisClusterConnection<String, String> connection) { this.connection = connection; this.connection.sync().flushall(); } @Test void future() throws ExecutionException, InterruptedException { RedisCommandFactory factory = new RedisCommandFactory(connection); SynchronousCommands api = factory.getCommands(SynchronousCommands.class); api.setSync(key, value, Timeout.create(Duration.ofSeconds(10))); assertThat(api.get("key").get()).isEqualTo("value"); assertThat(api.getAsBytes("key")).isEqualTo("value".getBytes()); } @Test void shouldRouteBinaryKey() { connection.sync().set(key, value); RedisCommandFactory factory = new RedisCommandFactory(connection); SynchronousCommands api = factory.getCommands(SynchronousCommands.class); assertThat(api.get(key.getBytes())).isEqualTo(value.getBytes()); } @Test void mgetAsValues() { connection.sync().set(key, value); RedisCommandFactory factory = new RedisCommandFactory(connection); SynchronousCommands api = factory.getCommands(SynchronousCommands.class); List<Value<String>> values = api.mgetAsValues(key); assertThat(values).hasSize(1); assertThat(values.get(0)).isEqualTo(Value.just(value)); }
RedisCommandsClusterIntegrationTests
java
apache__camel
components/camel-freemarker/src/main/java/org/apache/camel/component/freemarker/FreemarkerComponent.java
{ "start": 1352, "end": 7057 }
class ____ extends DefaultComponent { @Metadata(defaultValue = "true", description = "Sets whether to use resource content cache or not") private boolean contentCache = true; @Metadata private boolean allowTemplateFromHeader; @Metadata private boolean allowContextMapAll; @Metadata private boolean localizedLookup; @Metadata(label = "advanced") private Configuration configuration; private Configuration noCacheConfiguration; public FreemarkerComponent() { } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { // should we use regular configuration or no cache (content cache is default true) Configuration config; String encoding = getAndRemoveParameter(parameters, "encoding", String.class); boolean cache = getAndRemoveParameter(parameters, "contentCache", Boolean.class, contentCache); int templateUpdateDelay = getAndRemoveParameter(parameters, "templateUpdateDelay", Integer.class, 0); if (cache) { config = getConfiguration(); if (templateUpdateDelay > 0) { config.setTemplateUpdateDelay(templateUpdateDelay); } } else { config = getNoCacheConfiguration(); } FreemarkerEndpoint endpoint = new FreemarkerEndpoint(uri, this, remaining); if (ObjectHelper.isNotEmpty(encoding)) { endpoint.setEncoding(encoding); } endpoint.setAllowTemplateFromHeader(allowTemplateFromHeader); endpoint.setAllowContextMapAll(allowContextMapAll); endpoint.setContentCache(cache); endpoint.setConfiguration(config); endpoint.setTemplateUpdateDelay(templateUpdateDelay); setProperties(endpoint, parameters); // if its a http resource then append any remaining parameters and update the resource uri if (ResourceHelper.isHttpUri(remaining)) { remaining = ResourceHelper.appendParameters(remaining, parameters); endpoint.setResourceUri(remaining); } return endpoint; } public Configuration getConfiguration() { lock.lock(); try { if (configuration == null) { configuration = new Configuration(Configuration.VERSION_2_3_34); configuration.setLocalizedLookup(isLocalizedLookup()); configuration.setTemplateLoader(new URLTemplateLoader() { @Override protected URL getURL(String name) { try { return ResourceHelper.resolveMandatoryResourceAsUrl(getCamelContext(), name); } catch (Exception e) { // freemarker prefers to ask for locale first (eg xxx_en_GB, xxX_en), and then fallback without locale // so we should return null to signal the resource could not be found return null; } } }); } return (Configuration) configuration.clone(); } finally { lock.unlock(); } } /** * To use an existing {@link freemarker.template.Configuration} instance as the configuration. */ public void setConfiguration(Configuration configuration) { this.configuration = configuration; } public boolean isContentCache() { return contentCache; } /** * Sets whether to use resource content cache or not */ public void setContentCache(boolean contentCache) { this.contentCache = contentCache; } public boolean isAllowTemplateFromHeader() { return allowTemplateFromHeader; } /** * Whether to allow to use resource template from header or not (default false). * * Enabling this allows to specify dynamic templates via message header. However this can be seen as a potential * security vulnerability if the header is coming from a malicious user, so use this with care. */ public void setAllowTemplateFromHeader(boolean allowTemplateFromHeader) { this.allowTemplateFromHeader = allowTemplateFromHeader; } public boolean isAllowContextMapAll() { return allowContextMapAll; } /** * Sets whether the context map should allow access to all details. By default only the message body and headers can * be accessed. This option can be enabled for full access to the current Exchange and CamelContext. Doing so impose * a potential security risk as this opens access to the full power of CamelContext API. */ public void setAllowContextMapAll(boolean allowContextMapAll) { this.allowContextMapAll = allowContextMapAll; } public boolean isLocalizedLookup() { return localizedLookup; } /** * Enables/disables localized template lookup. Disabled by default. */ public void setLocalizedLookup(boolean localizedLookup) { this.localizedLookup = localizedLookup; } private Configuration getNoCacheConfiguration() { lock.lock(); try { if (noCacheConfiguration == null) { // create a clone of the regular configuration noCacheConfiguration = (Configuration) getConfiguration().clone(); // set this one to not use cache noCacheConfiguration.setCacheStorage(new NullCacheStorage()); } return noCacheConfiguration; } finally { lock.unlock(); } } }
FreemarkerComponent
java
spring-projects__spring-boot
integration-test/spring-boot-sni-integration-tests/spring-boot-sni-reactive-app/src/main/java/org/springframework/boot/sni/server/SniServerApplication.java
{ "start": 1073, "end": 1210 }
class ____ { public static void main(String[] args) { SpringApplication.run(SniServerApplication.class, args); } }
SniServerApplication
java
apache__kafka
storage/src/main/java/org/apache/kafka/server/log/remote/storage/ClassLoaderAwareRemoteStorageManager.java
{ "start": 1252, "end": 3878 }
class ____ implements RemoteStorageManager { private final RemoteStorageManager delegate; private final ClassLoader rsmClassLoader; public ClassLoaderAwareRemoteStorageManager(RemoteStorageManager rsm, ClassLoader rsmClassLoader) { this.delegate = rsm; this.rsmClassLoader = rsmClassLoader; } public RemoteStorageManager delegate() { return delegate; } @Override public void configure(Map<String, ?> configs) { withClassLoader(() -> { delegate.configure(configs); return null; }); } @Override public void close() throws IOException { withClassLoader(() -> { delegate.close(); return null; }); } private <T, E extends Exception> T withClassLoader(StorageAction<T, E> action) throws E { ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(rsmClassLoader); try { return action.execute(); } finally { Thread.currentThread().setContextClassLoader(originalClassLoader); } } public Optional<CustomMetadata> copyLogSegmentData(RemoteLogSegmentMetadata remoteLogSegmentMetadata, LogSegmentData logSegmentData) throws RemoteStorageException { return withClassLoader(() -> delegate.copyLogSegmentData(remoteLogSegmentMetadata, logSegmentData)); } @Override public InputStream fetchLogSegment(RemoteLogSegmentMetadata remoteLogSegmentMetadata, int startPosition) throws RemoteStorageException { return withClassLoader(() -> delegate.fetchLogSegment(remoteLogSegmentMetadata, startPosition)); } @Override public InputStream fetchLogSegment(RemoteLogSegmentMetadata remoteLogSegmentMetadata, int startPosition, int endPosition) throws RemoteStorageException { return withClassLoader(() -> delegate.fetchLogSegment(remoteLogSegmentMetadata, startPosition, endPosition)); } @Override public InputStream fetchIndex(RemoteLogSegmentMetadata remoteLogSegmentMetadata, IndexType indexType) throws RemoteStorageException { return withClassLoader(() -> delegate.fetchIndex(remoteLogSegmentMetadata, indexType)); } @Override public void deleteLogSegmentData(RemoteLogSegmentMetadata remoteLogSegmentMetadata) throws RemoteStorageException { withClassLoader(() -> { delegate.deleteLogSegmentData(remoteLogSegmentMetadata); return null; }); } }
ClassLoaderAwareRemoteStorageManager
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/query/NamedQueryDefinition.java
{ "start": 1137, "end": 1244 }
class ____ package name. Null for named queries declared * in XML. */ @Nullable String getLocation(); }
or
java
micronaut-projects__micronaut-core
http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java
{ "start": 47792, "end": 48171 }
class ____ { @NonNull private static SocketAddress makeDomainSocketAddress(String path) { try { return new DomainSocketAddress(path); } catch (NoClassDefFoundError e) { throw new UnsupportedOperationException("Netty domain socket support not on classpath", e); } } } }
DomainSocketHolder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ThreadLocalUsageTest.java
{ "start": 1590, "end": 1965 }
class ____ { static final ThreadLocal<Object> local = new ThreadLocal<>(); } """) .doTest(); } @Test public void negativeWellKnownTypes() { testHelper .addSourceLines( "Test.java", """ import java.text.DateFormat; import java.text.SimpleDateFormat;
Test
java
grpc__grpc-java
alts/src/main/java/io/grpc/alts/internal/AltsProtocolNegotiator.java
{ "start": 5824, "end": 6461 }
class ____ implements TsiHandshakerFactory { @Override public TsiHandshaker newHandshaker( @Nullable String authority, ChannelLogger negotiationLogger) { assert authority == null; return AltsTsiHandshaker.newServer( HandshakerServiceGrpc.newStub(lazyHandshakerChannel.get()), new AltsHandshakerOptions(RpcProtocolVersionsUtil.getRpcProtocolVersions()), negotiationLogger); } } return new ServerAltsProtocolNegotiator( new ServerTsiHandshakerFactory(), lazyHandshakerChannel); } @VisibleForTesting static final
ServerTsiHandshakerFactory
java
spring-projects__spring-boot
module/spring-boot-security/src/test/java/org/springframework/boot/security/autoconfigure/actuate/web/servlet/AbstractEndpointRequestIntegrationTests.java
{ "start": 6854, "end": 7218 }
class ____ implements Supplier<org.springframework.boot.actuate.endpoint.web.EndpointServlet> { @Override public org.springframework.boot.actuate.endpoint.web.EndpointServlet get() { return new org.springframework.boot.actuate.endpoint.web.EndpointServlet(ExampleServlet.class); } } @Configuration(proxyBeanMethods = false) static
TestServletEndpoint
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/DependentContext.java
{ "start": 412, "end": 1899 }
class ____ implements InjectableContext { @Override public Class<? extends Annotation> getScope() { return Dependent.class; } @Override public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) { Objects.requireNonNull(contextual, "Contextual must not be null"); if (creationalContext == null) { // there's never an "existing instance" of a dependent-scoped bean return null; } T instance = contextual.create(creationalContext); if (creationalContext instanceof CreationalContextImpl) { // we can remove this `if` and cast unconditionally after https://github.com/jakartaee/cdi-tck/pull/452 CreationalContextImpl<T> ccimpl = (CreationalContextImpl<T>) creationalContext; ccimpl.addDependentInstance((InjectableBean<T>) contextual, instance, creationalContext); } return instance; } @Override public <T> T get(Contextual<T> contextual) { return get(contextual, null); } @Override public boolean isActive() { return true; } @Override public void destroy(Contextual<?> contextual) { throw new UnsupportedOperationException(); } @Override public void destroy() { throw new UnsupportedOperationException(); } @Override public ContextState getState() { throw new UnsupportedOperationException(); } }
DependentContext
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/PositionsValidator.java
{ "start": 1500, "end": 2000 }
class ____ positions in the {@link SubscriptionState} based on current {@link ConsumerMetadata} * version. It maintains just enough shared state to determine when it can avoid costly inter-thread communication * in the {@link Consumer#poll(Duration)} method. * * <p/> * * Callers from the application thread should not mutate any of the state contained within this class. * It should be considered as <em>read-only</em>, and only the background thread should mutate the state. */ public
validates
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/RequestScopeExceptionMapperTest.java
{ "start": 1475, "end": 1789 }
class ____ implements ExceptionMapper<NotAllowedException> { @Inject UriInfo uriInfo; @Override public Response toResponse(NotAllowedException exception) { return Response.status(999).header("path", uriInfo.getPath()).build(); } } }
RequestScopeExceptionMapper
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-actuator/src/main/java/smoketest/actuator/ExampleInfoContributor.java
{ "start": 867, "end": 1074 }
class ____ implements InfoContributor { @Override public void contribute(Info.Builder builder) { builder.withDetail("example", Collections.singletonMap("someKey", "someValue")); } }
ExampleInfoContributor
java
quarkusio__quarkus
independent-projects/bootstrap/app-model/src/main/java/io/quarkus/bootstrap/model/PathsCollection.java
{ "start": 388, "end": 860 }
class ____ implements PathCollection, Serializable { private static final long serialVersionUID = -7214825505580070033L; public static PathsCollection from(Iterable<Path> paths) { final List<Path> list = new ArrayList<>(); paths.forEach(list::add); return new PathsCollection(list); } public static PathsCollection of(Path... paths) { return new PathsCollection(Arrays.asList(paths)); } public static
PathsCollection
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2439/ErroneousIssue2439Mapper.java
{ "start": 300, "end": 435 }
interface ____ { @Mapping(target = "modeName", source = "mode.desc") LiveDto map(LiveEntity entity);
ErroneousIssue2439Mapper
java
netty__netty
codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompSubframeDecoder.java
{ "start": 13190, "end": 16801 }
class ____ extends Utf8LineParser { private final boolean validateHeaders; private String name; private boolean valid; private boolean shouldUnescape; private boolean unescapeInProgress; HeaderParser(AppendableCharSequence charSeq, int maxLineLength, boolean validateHeaders) { super(charSeq, maxLineLength); this.validateHeaders = validateHeaders; } boolean parseHeader(StompHeadersSubframe headersSubframe, ByteBuf buf) { shouldUnescape = shouldUnescape(headersSubframe.command()); AppendableCharSequence value = super.parse(buf); if (value == null || (name == null && value.length() == 0)) { return false; } if (valid) { headersSubframe.headers().add(name, value.toString()); } else if (validateHeaders) { if (StringUtil.isNullOrEmpty(name)) { throw new IllegalArgumentException("received an invalid header line '" + value + '\''); } String line = name + ':' + value; throw new IllegalArgumentException("a header value or name contains a prohibited character ':'" + ", " + line); } return true; } @Override public boolean process(byte nextByte) throws Exception { if (nextByte == StompConstants.COLON) { if (name == null) { AppendableCharSequence charSeq = charSequence(); if (charSeq.length() != 0) { name = charSeq.substring(0, charSeq.length()); charSeq.reset(); valid = true; return true; } else { name = StringUtil.EMPTY_STRING; } } else { valid = false; } } return super.process(nextByte); } @Override protected void appendTo(AppendableCharSequence charSeq, char chr) { if (!shouldUnescape) { super.appendTo(charSeq, chr); return; } if (chr == '\\') { if (unescapeInProgress) { super.appendTo(charSeq, chr); unescapeInProgress = false; } else { unescapeInProgress = true; } return; } if (unescapeInProgress) { if (chr == 'c') { charSeq.append(':'); } else if (chr == 'r') { charSeq.append('\r'); } else if (chr == 'n') { charSeq.append('\n'); } else { charSeq.append('\\').append(chr); throw new IllegalArgumentException("received an invalid escape header sequence '" + charSeq + '\''); } unescapeInProgress = false; return; } super.appendTo(charSeq, chr); } @Override protected void reset() { name = null; valid = false; unescapeInProgress = false; super.reset(); } private static boolean shouldUnescape(StompCommand command) { return command != StompCommand.CONNECT && command != StompCommand.CONNECTED; } } }
HeaderParser
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/googlevertexai/response/GoogleVertexAiRerankResponseEntityTests.java
{ "start": 733, "end": 7509 }
class ____ extends ESTestCase { public void testFromResponse_CreatesResultsForASingleItem() throws IOException { String responseJson = """ { "records": [ { "id": "2", "title": "title 2", "content": "content 2", "score": 0.97 } ] } """; RankedDocsResults parsedResults = GoogleVertexAiRerankResponseEntity.fromResponse( new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)) ); assertThat(parsedResults.getRankedDocs(), is(List.of(new RankedDocsResults.RankedDoc(2, 0.97F, "content 2")))); } public void testFromResponse_CreatesResultsForASingleItem_NoContent() throws IOException { String responseJson = """ { "records": [ { "id": "2", "title": "title 2", "score": 0.97 } ] } """; RankedDocsResults parsedResults = GoogleVertexAiRerankResponseEntity.fromResponse( new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)) ); assertThat(parsedResults.getRankedDocs(), is(List.of(new RankedDocsResults.RankedDoc(2, 0.97F, null)))); } public void testFromResponse_CreatesResultsForMultipleItems() throws IOException { String responseJson = """ { "records": [ { "id": "2", "title": "title 2", "content": "content 2", "score": 0.97 }, { "id": "1", "title": "title 1", "content": "content 1", "score": 0.90 } ] } """; RankedDocsResults parsedResults = GoogleVertexAiRerankResponseEntity.fromResponse( new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)) ); assertThat( parsedResults.getRankedDocs(), is(List.of(new RankedDocsResults.RankedDoc(2, 0.97F, "content 2"), new RankedDocsResults.RankedDoc(1, 0.90F, "content 1"))) ); } public void testFromResponse_CreatesResultsForMultipleItems_NoContent() throws IOException { String responseJson = """ { "records": [ { "id": "2", "title": "title 2", "score": 0.97 }, { "id": "1", "title": "title 1", "score": 0.90 } ] } """; RankedDocsResults parsedResults = GoogleVertexAiRerankResponseEntity.fromResponse( new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)) ); assertThat( parsedResults.getRankedDocs(), is(List.of(new RankedDocsResults.RankedDoc(2, 0.97F, null), new RankedDocsResults.RankedDoc(1, 0.90F, null))) ); } public void testFromResponse_FailsWhenRecordsFieldIsNotPresent() { String responseJson = """ { "not_records": [ { "id": "2", "title": "title 2", "content": "content 2", "score": 0.97 }, { "id": "1", "title": "title 1", "content": "content 1", "score": 0.90 } ] } """; var thrownException = expectThrows( IllegalStateException.class, () -> GoogleVertexAiRerankResponseEntity.fromResponse( new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)) ) ); assertThat(thrownException.getMessage(), is("Failed to find required field [records] in Google Vertex AI rerank response")); } public void testFromResponse_FailsWhenScoreFieldIsNotPresent() { String responseJson = """ { "records": [ { "id": "2", "title": "title 2", "content": "content 2", "not_score": 0.97 }, { "id": "1", "title": "title 1", "content": "content 1", "score": 0.96 } ] } """; var thrownException = expectThrows( IllegalStateException.class, () -> GoogleVertexAiRerankResponseEntity.fromResponse( new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)) ) ); assertThat(thrownException.getMessage(), is("Failed to find required field [score] in Google Vertex AI rerank response")); } public void testFromResponse_FailsWhenIDFieldIsNotInteger() { String responseJson = """ { "records": [ { "id": "abcd", "title": "title 2", "content": "content 2", "score": 0.97 }, { "id": "1", "title": "title 1", "content": "content 1", "score": 0.96 } ] } """; var thrownException = expectThrows( IllegalStateException.class, () -> GoogleVertexAiRerankResponseEntity.fromResponse( new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)) ) ); assertThat( thrownException.getMessage(), is("Expected numeric value for record ID field in Google Vertex AI rerank response but received [abcd]") ); } }
GoogleVertexAiRerankResponseEntityTests
java
quarkusio__quarkus
extensions/kubernetes/spi/src/test/java/io/quarkus/kubernetes/spi/KubernetesEnvBuildItemTest.java
{ "start": 1202, "end": 3267 }
class ____ { private static final String TARGET = "target"; private static final String VALUE = "value"; private static final String NAME = "name"; private static final String PREFIX = "prefix"; @Test public void testCreateSimpleVarFromEnvConfig() { final KubernetesEnvBuildItem item = create(NAME, VALUE, null, null, null, TARGET, null); assertEquals(var, item.getType()); assertEquals(NAME, item.getName()); assertEquals(VALUE, item.getValue()); assertEquals(TARGET, item.getTarget()); assertNull(item.getConfigMap()); assertNull(item.getSecret()); assertNull(item.getField()); } @Test public void testCreateLoadFromConfigMapFromEnvConfig() { final KubernetesEnvBuildItem item = create(NAME, null, null, VALUE, null, TARGET, null); assertEquals(configmap, item.getType()); assertEquals(VALUE, item.getName()); assertNull(item.getValue()); assertEquals(VALUE, item.getConfigMap()); assertNull(item.getSecret()); assertNull(item.getField()); } @Test public void testCreateConfigMapWithPrefix() { final KubernetesEnvBuildItem item = create(NAME, null, null, VALUE, null, TARGET, PREFIX); assertEquals(configmap, item.getType()); assertEquals(VALUE, item.getName()); assertNull(item.getValue()); assertEquals(VALUE, item.getConfigMap()); assertNull(item.getSecret()); assertNull(item.getField()); assertEquals(PREFIX, item.getPrefix()); } @Test public void testCreateSecretWithPrefix() { final KubernetesEnvBuildItem item = create(NAME, null, VALUE, null, null, TARGET, PREFIX); assertEquals(secret, item.getType()); assertEquals(VALUE, item.getName()); assertNull(item.getValue()); assertEquals(VALUE, item.getSecret()); assertNull(item.getConfigMap()); assertNull(item.getField()); assertEquals(PREFIX, item.getPrefix()); } }
KubernetesEnvBuildItemTest
java
apache__camel
components/camel-netty/src/main/java/org/apache/camel/component/netty/codec/DatagramPacketStringDecoder.java
{ "start": 1295, "end": 2624 }
class ____ extends MessageToMessageDecoder<AddressedEnvelope<Object, InetSocketAddress>> { private static final Logger LOG = LoggerFactory.getLogger(DatagramPacketStringDecoder.class); private final Charset charset; /** * Creates a new instance with the current system character set. */ public DatagramPacketStringDecoder() { this(Charset.defaultCharset()); } /** * Creates a new instance with the specified character set. */ public DatagramPacketStringDecoder(Charset charset) { if (charset == null) { throw new NullPointerException("charset"); } this.charset = charset; } @Override protected void decode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg, List<Object> out) throws Exception { if (msg.content() instanceof ByteBuf) { ByteBuf payload = (ByteBuf) msg.content(); AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop = new DefaultAddressedEnvelope<>(payload.toString(charset), msg.recipient(), msg.sender()); out.add(addressedEnvelop); } else { LOG.debug("Ignoring message content as it is not an io.netty.buffer.ByteBuf instance."); } } }
DatagramPacketStringDecoder
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/configuration/tracker/ConfigTrackingConfig.java
{ "start": 659, "end": 3316 }
interface ____ { /** * Whether configuration dumping is enabled */ @WithDefault("false") boolean enabled(); /** * Directory in which the configuration dump should be stored. * If not configured the {@code .quarkus} directory under the project directory will be used. */ Optional<Path> directory(); /** * File in which the configuration dump should be stored. If not configured, the {@link #filePrefix} and * {@link #fileSuffix} will be used to generate the final file name. * If the configured file path is absolute, the {@link #directory} option will be ignored. Otherwise, * the path will be considered relative to the {@link #directory}. */ Optional<Path> file(); /** * File name prefix. This option will be ignored in case {@link #file} is configured. */ @WithDefault("quarkus") String filePrefix(); /** * File name suffix. This option will be ignored in case {@link #file} is configured. */ @WithDefault("-config-dump") String fileSuffix(); /** * A list of config properties that should be excluded from the report. * GLOB patterns could be used instead of property names. */ Optional<List<String>> exclude(); /** * Translates the value of {@link #exclude} to a list of {@link java.util.regex.Pattern}. * * @return list of patterns created from {@link #exclude} */ default List<Pattern> getExcludePatterns() { return toPatterns(exclude()); } /** * A list of config properties whose values should be hashed in the report. * The values will be hashed using SHA-512 algorithm. * GLOB patterns could be used instead of property names. */ Optional<List<String>> hashOptions(); /** * Translates the value of {@link #hashOptions()} to a list of {@link java.util.regex.Pattern}. * * @return list of patterns created from {@link #hashOptions()} */ default List<Pattern> getHashOptionsPatterns() { return toPatterns(hashOptions()); } static List<Pattern> toPatterns(Optional<List<String>> globs) { if (globs.isEmpty()) { return List.of(); } var list = globs.get(); final List<Pattern> patterns = new ArrayList<>(list.size()); for (var s : list) { patterns.add(Pattern.compile(GlobUtil.toRegexPattern(s))); } return patterns; } /** * Whether to use a {@code ~} as an alias for user home directory in path values */ @WithDefault("true") boolean useUserHomeAliasInPaths(); }
ConfigTrackingConfig
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/connector/source/DynamicTableSource.java
{ "start": 5884, "end": 6108 }
interface ____ extends RuntimeConverter { /** Converts the given object into an internal data structure. */ @Nullable Object toInternal(@Nullable Object externalStructure); } }
DataStructureConverter
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/io/parsing/SkipParser.java
{ "start": 1120, "end": 1174 }
interface ____ skip symbols and actions. */ public
to
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b2/CustomerInventory.java
{ "start": 1016, "end": 2965 }
class ____ implements Serializable, Comparator<CustomerInventory> { @Id @TableGenerator(name = "inventory", table = "U_SEQUENCES", pkColumnName = "S_ID", valueColumnName = "S_NEXTNUM", pkColumnValue = "inventory", allocationSize = 1000) @GeneratedValue(strategy = GenerationType.TABLE, generator = "inventory") @Column(name = "CI_ID") private Integer id; @Id @ManyToOne(cascade = CascadeType.MERGE) @JoinColumn(name = "CI_CUSTOMERID") private Customer customer; @ManyToOne(cascade = CascadeType.MERGE) @JoinColumn(name = "CI_ITEMID") private Item vehicle; @Column(name = "CI_VALUE") private BigDecimal totalCost; @Column(name = "CI_QUANTITY") private int quantity; @Version @Column(name = "CI_VERSION") private int version; protected CustomerInventory() { } CustomerInventory(Customer customer, Item vehicle, int quantity, BigDecimal totalValue) { this.customer = customer; this.vehicle = vehicle; this.quantity = quantity; this.totalCost = totalValue; } public Item getVehicle() { return vehicle; } public BigDecimal getTotalCost() { return totalCost; } public int getQuantity() { return quantity; } public Integer getId() { return id; } public Customer getCustomer() { return customer; } public int getVersion() { return version; } public int compare(CustomerInventory cdb1, CustomerInventory cdb2) { return cdb1.id.compareTo( cdb2.id ); } @Override public boolean equals(Object obj) { if ( obj == this ) { return true; } if ( obj == null || !( obj instanceof CustomerInventory ) ) { return false; } if ( this.id == ( ( CustomerInventory ) obj ).id ) { return true; } if ( this.id != null && ( ( CustomerInventory ) obj ).id == null ) { return false; } if ( this.id == null && ( ( CustomerInventory ) obj ).id != null ) { return false; } return this.id.equals( ( ( CustomerInventory ) obj ).id ); } }
CustomerInventory
java
reactor__reactor-core
reactor-test/src/main/java/reactor/test/DefaultStepVerifierBuilder.java
{ "start": 74568, "end": 76203 }
class ____<T> extends TaskEvent<T> { final Duration duration; NoEvent(Duration duration, String desc) { super(null, desc); this.duration = duration; } @Override void run(DefaultVerifySubscriber<T> parent) throws Exception { if(parent.virtualTimeScheduler != null) { parent.monitorSignal = true; virtualOrRealWait(duration.minus(Duration.ofNanos(1)), parent); parent.monitorSignal = false; Signal<T> parentTerminalError = parent.terminalError; if (parentTerminalError != null && !parent.isCancelled()) { Throwable terminalError = parentTerminalError.getThrowable(); throw parent.messageFormatter.assertionError("Unexpected error during a no-event expectation: " + terminalError, terminalError); } else if (parent.isTerminated() && !parent.isCancelled()) { throw parent.messageFormatter.assertionError("Unexpected completion during a no-event expectation"); } virtualOrRealWait(Duration.ofNanos(1), parent); } else{ parent.monitorSignal = true; virtualOrRealWait(duration, parent); parent.monitorSignal = false; Signal<T> parentTerminalError = parent.terminalError; if (parentTerminalError != null && !parent.isCancelled()) { Throwable terminalError = parentTerminalError.getThrowable(); throw parent.messageFormatter.assertionError("Unexpected error during a no-event expectation: " + terminalError, terminalError); } else if (parent.isTerminated() && !parent.isCancelled()) { throw parent.messageFormatter.assertionError("Unexpected completion during a no-event expectation"); } } } } static final
NoEvent
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng5572ReactorPluginExtensionsTest.java
{ "start": 1124, "end": 2416 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Test that Maven warns when one reactor project contains a plugin, and another tries to use it with extensions * * @throws Exception in case of failure */ @Test public void testit() throws Exception { File testDir = extractResources("/mng-5572-reactor-plugin-extensions"); // plugin must be available in local repo, otherwise the project couldn't be built Verifier setup = newVerifier(testDir.getAbsolutePath()); setup.setAutoclean(true); setup.addCliArgument("-f"); setup.addCliArgument("plugin/pom.xml"); setup.addCliArgument("install"); setup.execute(); setup.verifyErrorFreeLog(); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setLogFileName("log2.txt"); verifier.setAutoclean(false); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyTextInLog( "[WARNING] 'project' uses 'org.apache.maven.its.mng5572:plugin' as extension which is not possible within the same reactor build. This plugin was pulled from the local repository!"); } }
MavenITmng5572ReactorPluginExtensionsTest
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/PropertyMappingContextCustomizerFactoryTests.java
{ "start": 5175, "end": 5274 }
class ____ { } @Configuration(proxyBeanMethods = false) @TypeMappingAnnotation static
TypeMapping
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/mutationquery/MutationQueriesWhereAndFilterTest.java
{ "start": 6588, "end": 6866 }
class ____ { @Id private Long id; @Column( name = "where_deleted" ) private boolean whereDeleted; @Column( name = "filter_deleted" ) private boolean filterDeleted; } @Entity( name = "DiscriminatorUser" ) @DiscriminatorValue( "user" ) public static
DiscriminatorBase
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/entities/BreakDance.java
{ "start": 397, "end": 717 }
class ____ { @Id @GeneratedValue(generator = "memencoIdGen", strategy = GenerationType.TABLE) @TableGenerator( name = "memencoIdGen", table = "hi_id_key", pkColumnName = "id_key", valueColumnName = "next_hi", pkColumnValue = "issue", allocationSize = 1 ) public Integer id; public String name; }
BreakDance
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/aggs/categorization/TokenListSimilarityTester.java
{ "start": 610, "end": 4717 }
class ____ { /** * Calculate the weighted edit distance between two sequences. Each * element of each sequence has an associated weight, such that some * elements can be considered more expensive to add/remove/replace than * others. * * Unfortunately, in the case of arbitrary weightings, the * Berghel-Roach algorithm cannot be applied. Ukkonen gives a * counter-example on page 114 of Information and Control, Vol 64, * Nos. 1-3, January/February/March 1985. The problem is that the * matrix diagonals are not necessarily monotonically increasing. * See http://www.cs.helsinki.fi/u/ukkonen/InfCont85.PDF. * * TODO: It may be possible to apply some of the lesser optimisations * from section 2 of Ukkonen's paper to this algorithm. */ public static int weightedEditDistance(List<TokenAndWeight> first, List<TokenAndWeight> second) { // This is similar to the traditional Levenshtein distance, as // described in http://en.wikipedia.org/wiki/Levenshtein_distance, // but adding the concept of different costs for each element. If // you are trying to understand this method, you should first make // sure you fully understand traditional Levenshtein distance. int firstLen = first.size(); int secondLen = second.size(); // Rule out boundary cases. if (firstLen == 0) { return second.stream().mapToInt(TokenAndWeight::getWeight).sum(); } if (secondLen == 0) { return first.stream().mapToInt(TokenAndWeight::getWeight).sum(); } // We need to store just two columns of the matrix; the current and // previous columns. We allocate two arrays and then swap their // meanings. int[] currentCol = new int[secondLen + 1]; int[] prevCol = new int[secondLen + 1]; // Populate the left column. currentCol[0] = 0; for (int downMinusOne = 0; downMinusOne < secondLen; ++downMinusOne) { currentCol[downMinusOne + 1] = currentCol[downMinusOne] + second.get(downMinusOne).getWeight(); } // Calculate the other entries in the matrix. for (TokenAndWeight firstTokenAndWeight : first) { { int[] temp = prevCol; prevCol = currentCol; currentCol = temp; } int firstCost = firstTokenAndWeight.getWeight(); currentCol[0] = prevCol[0] + firstCost; for (int downMinusOne = 0; downMinusOne < secondLen; ++downMinusOne) { TokenAndWeight secondTokenAndWeight = second.get(downMinusOne); int secondCost = secondTokenAndWeight.getWeight(); // There are 3 options, and due to the possible differences // in the weightings, we must always evaluate all 3: // 1) Deletion => cell to the left's value plus cost of // deleting the element from the first sequence. int option1 = prevCol[downMinusOne + 1] + firstCost; // 2) Insertion => cell above's value plus cost of // inserting the element from the second sequence. int option2 = currentCol[downMinusOne] + secondCost; // 3) Substitution => cell above left's value plus the // higher of the two element weights. // OR // No extra cost in the case where the corresponding // elements are equal. int option3 = prevCol[downMinusOne] + ((firstTokenAndWeight.getTokenId() == secondTokenAndWeight.getTokenId()) ? 0 : Math.max(firstCost, secondCost)); // Take the cheapest option of the 3. currentCol[downMinusOne + 1] = Math.min(Math.min(option1, option2), option3); } } // Result is the value in the bottom right hand corner of the matrix. return currentCol[secondLen]; } }
TokenListSimilarityTester
java
apache__thrift
lib/javame/src/org/apache/thrift/TSerializer.java
{ "start": 1226, "end": 3315 }
class ____ { /** * This is the byte array that data is actually serialized into */ private final ByteArrayOutputStream baos_ = new ByteArrayOutputStream(); /** * This transport wraps that byte array */ private final TIOStreamTransport transport_ = new TIOStreamTransport(baos_); /** * Internal protocol used for serializing objects. */ private TProtocol protocol_; /** * Create a new TSerializer that uses the TBinaryProtocol by default. */ public TSerializer() { this(new TBinaryProtocol.Factory()); } /** * Create a new TSerializer. It will use the TProtocol specified by the * factory that is passed in. * * @param protocolFactory Factory to create a protocol */ public TSerializer(TProtocolFactory protocolFactory) { protocol_ = protocolFactory.getProtocol(transport_); } /** * Serialize the Thrift object into a byte array. The process is simple, * just clear the byte array output, write the object into it, and grab the * raw bytes. * * @param base The object to serialize * @return Serialized object in byte[] format */ public byte[] serialize(TBase base) throws TException { baos_.reset(); base.write(protocol_); return baos_.toByteArray(); } /** * Serialize the Thrift object into a Java string, using a specified * character set for encoding. * * @param base The object to serialize * @param charset Valid JVM charset * @return Serialized object as a String */ public String toString(TBase base, String charset) throws TException { try { return new String(serialize(base), charset); } catch (UnsupportedEncodingException uex) { throw new TException("JVM DOES NOT SUPPORT ENCODING: " + charset); } } /** * Serialize the Thrift object into a Java string, using the default JVM * charset encoding. * * @param base The object to serialize * @return Serialized object as a String */ public String toString(TBase base) throws TException { return new String(serialize(base)); } }
TSerializer
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/shell/find/TestAnd.java
{ "start": 1314, "end": 8182 }
class ____ { // test all expressions passing @Test public void testPass() throws IOException { And and = new And(); PathData pathData = mock(PathData.class); Expression first = mock(Expression.class); when(first.apply(pathData, -1)).thenReturn(Result.PASS); Expression second = mock(Expression.class); when(second.apply(pathData, -1)).thenReturn(Result.PASS); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); assertEquals(Result.PASS, and.apply(pathData, -1)); verify(first).apply(pathData, -1); verify(second).apply(pathData, -1); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); } // test the first expression failing @Test public void testFailFirst() throws IOException { And and = new And(); PathData pathData = mock(PathData.class); Expression first = mock(Expression.class); when(first.apply(pathData, -1)).thenReturn(Result.FAIL); Expression second = mock(Expression.class); when(second.apply(pathData, -1)).thenReturn(Result.PASS); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); assertEquals(Result.FAIL, and.apply(pathData, -1)); verify(first).apply(pathData, -1); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); } // test the second expression failing @Test public void testFailSecond() throws IOException { And and = new And(); PathData pathData = mock(PathData.class); Expression first = mock(Expression.class); when(first.apply(pathData, -1)).thenReturn(Result.PASS); Expression second = mock(Expression.class); when(second.apply(pathData, -1)).thenReturn(Result.FAIL); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); assertEquals(Result.FAIL, and.apply(pathData, -1)); verify(first).apply(pathData, -1); verify(second).apply(pathData, -1); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); } // test both expressions failing @Test public void testFailBoth() throws IOException { And and = new And(); PathData pathData = mock(PathData.class); Expression first = mock(Expression.class); when(first.apply(pathData, -1)).thenReturn(Result.FAIL); Expression second = mock(Expression.class); when(second.apply(pathData, -1)).thenReturn(Result.FAIL); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); assertEquals(Result.FAIL, and.apply(pathData, -1)); verify(first).apply(pathData, -1); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); } // test the first expression stopping @Test public void testStopFirst() throws IOException { And and = new And(); PathData pathData = mock(PathData.class); Expression first = mock(Expression.class); when(first.apply(pathData, -1)).thenReturn(Result.STOP); Expression second = mock(Expression.class); when(second.apply(pathData, -1)).thenReturn(Result.PASS); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); assertEquals(Result.STOP, and.apply(pathData, -1)); verify(first).apply(pathData, -1); verify(second).apply(pathData, -1); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); } // test the second expression stopping @Test public void testStopSecond() throws IOException { And and = new And(); PathData pathData = mock(PathData.class); Expression first = mock(Expression.class); when(first.apply(pathData, -1)).thenReturn(Result.PASS); Expression second = mock(Expression.class); when(second.apply(pathData, -1)).thenReturn(Result.STOP); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); assertEquals(Result.STOP, and.apply(pathData, -1)); verify(first).apply(pathData, -1); verify(second).apply(pathData, -1); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); } // test first expression stopping and second failing @Test public void testStopFail() throws IOException { And and = new And(); PathData pathData = mock(PathData.class); Expression first = mock(Expression.class); when(first.apply(pathData, -1)).thenReturn(Result.STOP); Expression second = mock(Expression.class); when(second.apply(pathData, -1)).thenReturn(Result.FAIL); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); assertEquals(Result.STOP.combine(Result.FAIL), and.apply(pathData, -1)); verify(first).apply(pathData, -1); verify(second).apply(pathData, -1); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); } // test setOptions is called on child @Test public void testSetOptions() throws IOException { And and = new And(); Expression first = mock(Expression.class); Expression second = mock(Expression.class); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); FindOptions options = mock(FindOptions.class); and.setOptions(options); verify(first).setOptions(options); verify(second).setOptions(options); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); } // test prepare is called on child @Test public void testPrepare() throws IOException { And and = new And(); Expression first = mock(Expression.class); Expression second = mock(Expression.class); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); and.prepare(); verify(first).prepare(); verify(second).prepare(); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); } // test finish is called on child @Test public void testFinish() throws IOException { And and = new And(); Expression first = mock(Expression.class); Expression second = mock(Expression.class); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); and.finish(); verify(first).finish(); verify(second).finish(); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); } }
TestAnd
java
elastic__elasticsearch
x-pack/plugin/spatial/src/test/java/org/elasticsearch/xpack/spatial/search/aggregations/metrics/InternalCartesianCentroidTests.java
{ "start": 1149, "end": 6722 }
class ____ extends InternalAggregationTestCase<InternalCartesianCentroid> { @Override protected SearchPlugin registerPlugin() { return new LocalStateSpatialPlugin(); } @Override protected InternalCartesianCentroid createTestInstance(String name, Map<String, Object> metadata) { Point point = ShapeTestUtils.randomPoint(false); CartesianPoint centroid = new CartesianPoint(point.getX(), point.getY()); // Unlike InternalGeoCentroid, we do not need to encode/decode to handle hashcode test failures, // but we do need to treat zero values with care. See the mutate function below for details on that long count = randomIntBetween(0, 1000); if (count == 0) { centroid = null; } return new InternalCartesianCentroid(name, centroid, count, Collections.emptyMap()); } @Override protected void assertReduced(InternalCartesianCentroid reduced, List<InternalCartesianCentroid> inputs) { double xSum = 0; double ySum = 0; long totalCount = 0; for (InternalCartesianCentroid input : inputs) { if (input.count() > 0) { xSum += (input.count() * input.centroid().getX()); ySum += (input.count() * input.centroid().getY()); } totalCount += input.count(); } if (totalCount > 0) { assertThat(ySum / totalCount, closeTo(reduced.centroid().getY(), Math.abs(reduced.centroid().getY() / 1e10))); assertThat(xSum / totalCount, closeTo(reduced.centroid().getX(), Math.abs(reduced.centroid().getX() / 1e10))); } assertEquals(totalCount, reduced.count()); } @Override protected boolean supportsSampling() { return true; } @Override protected void assertSampled(InternalCartesianCentroid sampled, InternalCartesianCentroid reduced, SamplingContext samplingContext) { assertThat(sampled.centroid().getY(), closeTo(reduced.centroid().getY(), Math.abs(reduced.centroid().getY() / 1e10))); assertThat(sampled.centroid().getX(), closeTo(reduced.centroid().getX(), Math.abs(reduced.centroid().getX() / 1e10))); assertEquals(sampled.count(), samplingContext.scaleUp(reduced.count()), 0); } public void testReduceMaxCount() { InternalCartesianCentroid maxValueCentroid = new InternalCartesianCentroid( "agg", new CartesianPoint(10, 0), Long.MAX_VALUE, Collections.emptyMap() ); InternalCentroid reducedCentroid = (InternalCentroid) InternalAggregationTestCase.reduce( Collections.singletonList(maxValueCentroid), null ); assertThat(reducedCentroid.count(), equalTo(Long.MAX_VALUE)); } @Override protected InternalCartesianCentroid mutateInstance(InternalCartesianCentroid instance) { double minValue = -1000000; double maxValue = 1000000; String name = instance.getName(); SpatialPoint centroid = instance.centroid(); long count = instance.count(); Map<String, Object> metadata = instance.getMetadata(); switch (between(0, 3)) { case 0 -> name += randomAlphaOfLength(5); case 1 -> { count += between(1, 100); if (centroid == null) { // if the new count is > 0 then we need to make sure there is a // centroid or the constructor will throw an exception centroid = new CartesianPoint( randomDoubleBetween(minValue, maxValue, false), randomDoubleBetween(minValue, maxValue, false) ); } } case 2 -> { if (centroid == null) { centroid = new CartesianPoint( randomDoubleBetween(minValue, maxValue, false), randomDoubleBetween(minValue, maxValue, false) ); count = between(1, 100); } else { CartesianPoint newCentroid = new CartesianPoint(centroid); if (randomBoolean()) { mutateCoordinate(centroid::getY, newCentroid::resetY); } else { mutateCoordinate(centroid::getX, newCentroid::resetX); } centroid = newCentroid; } } case 3 -> { if (metadata == null) { metadata = Maps.newMapWithExpectedSize(1); } else { metadata = new HashMap<>(instance.getMetadata()); } metadata.put(randomAlphaOfLength(15), randomInt()); } default -> throw new AssertionError("Illegal randomisation branch"); } return new InternalCartesianCentroid(name, centroid, count, metadata); } /** * The previous mutation of dividing by 2.0 left zero values unchanged, leading to lack of mutation. * Now we act differently on small values to ensure that mutation actually occurs. */ private void mutateCoordinate(Supplier<Double> getter, Consumer<Double> setter) { double coordinate = getter.get(); if (Math.abs(coordinate) < 1e-6) { setter.accept(coordinate + 1.0); } else { setter.accept(coordinate / 2.0); } } }
InternalCartesianCentroidTests
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/LineNumberAware.java
{ "start": 985, "end": 2048 }
interface ____ { /** * The line number of this entity. * * @return -1 if line number is not possible to know */ int getLineNumber(); /** * Sets the line number of this entity. parsing the source file and provide the line number representing this node. * * @param lineNumber the line number */ void setLineNumber(int lineNumber); /** * The location of the entity. */ String getLocation(); /** * Sets the location of the entity (source file name, i.e. foo.java, bar.xml, etc.) */ void setLocation(String location); /** * Set the {@link LineNumberAware} if the object is an instance of {@link LineNumberAware}. */ static <T> T trySetLineNumberAware(T object, LineNumberAware source) { if (source != null && object instanceof LineNumberAware lineNumberAware) { lineNumberAware.setLineNumber(source.getLineNumber()); lineNumberAware.setLocation(source.getLocation()); } return object; } }
LineNumberAware
java
elastic__elasticsearch
x-pack/plugin/logsdb/src/main/java/org/elasticsearch/xpack/logsdb/patterntext/DelimiterAnalyzer.java
{ "start": 1562, "end": 2222 }
class ____ extends CharTokenizer { DelimiterTokenizer() { super(TokenStream.DEFAULT_TOKEN_ATTRIBUTE_FACTORY); } @Override protected boolean isTokenChar(int c) { if (Character.isWhitespace(c) || c == '=' || c == '?' || c == ':' || c == '[' || c == ']' || c == '{' || c == '}' || c == '"' || c == '\\' || c == '\'') { return false; } else { return true; } } } }
DelimiterTokenizer
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeDelay.java
{ "start": 1050, "end": 1706 }
class ____<T> extends AbstractMaybeWithUpstream<T, T> { final long delay; final TimeUnit unit; final Scheduler scheduler; final boolean delayError; public MaybeDelay(MaybeSource<T> source, long delay, TimeUnit unit, Scheduler scheduler, boolean delayError) { super(source); this.delay = delay; this.unit = unit; this.scheduler = scheduler; this.delayError = delayError; } @Override protected void subscribeActual(MaybeObserver<? super T> observer) { source.subscribe(new DelayMaybeObserver<>(observer, delay, unit, scheduler, delayError)); } static final
MaybeDelay
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/DelegatingCreatorImplicitNamesTest.java
{ "start": 3295, "end": 5640 }
class ____ extends JacksonAnnotationIntrospector { private static final long serialVersionUID = 1L; @Override public String findImplicitPropertyName(MapperConfig<?> config, AnnotatedMember member) { if (member instanceof AnnotatedParameter ap) { AnnotatedWithParams owner = ap.getOwner(); if (owner instanceof AnnotatedMethod method) { if (Objects.requireNonNull(method.getAnnotation(JsonCreator.class)).mode() == JsonCreator.Mode.DELEGATING) return "fullData"; } } return super.findImplicitPropertyName(config, member); } } private final ObjectMapper MAPPER = newJsonMapper(); private final ObjectMapper MAPPER_2543 = JsonMapper.builder() .annotationIntrospector(new DelegatingCreatorNamedArgumentIntrospector2543()) .build(); // [databind#1001] @Test public void testWithoutNamedParameters1001() throws Exception { D d = D.make("abc:def"); String actualJson = MAPPER.writeValueAsString(d); D actualD = MAPPER.readValue(actualJson, D.class); assertEquals("\"abc:def\"", actualJson); assertEquals(d, actualD); } @Test public void testWithNamedParameters1001() throws Exception { ObjectMapper sut = jsonMapperBuilder() .annotationIntrospector(new CreatorNameIntrospector1001()) .build(); D d = D.make("abc:def"); String actualJson = sut.writeValueAsString(d); D actualD = sut.readValue(actualJson, D.class); assertEquals("\"abc:def\"", actualJson); assertEquals(d, actualD); } // [databind#2543] @Test public void testDeserialization2543() throws Exception { Data2543 data = MAPPER_2543.readValue(a2q("{'part1':'a','part2':'b'}"), Data2543.class); assertThat(data.part1).isEqualTo("a"); assertThat(data.part2).isEqualTo("b"); } @Test public void testDelegatingDeserialization2543() throws Exception { Data2543 data = MAPPER_2543.readValue(a2q("'a b'"), Data2543.class); assertThat(data.part1).isEqualTo("a"); assertThat(data.part2).isEqualTo("b"); } }
DelegatingCreatorNamedArgumentIntrospector2543
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/deduplicate/RowTimeMiniBatchLatestChangeDeduplicateFunction.java
{ "start": 1664, "end": 3678 }
class ____ extends MiniBatchDeduplicateFunctionBase<RowData, RowData, RowData, RowData, RowData> { private static final long serialVersionUID = 1L; private final TypeSerializer<RowData> serializer; private final boolean generateUpdateBefore; private final boolean generateInsert; private final int rowtimeIndex; private final boolean keepLastRow; public RowTimeMiniBatchLatestChangeDeduplicateFunction( InternalTypeInfo<RowData> typeInfo, TypeSerializer<RowData> serializer, long minRetentionTime, int rowtimeIndex, boolean generateUpdateBefore, boolean generateInsert, boolean keepLastRow) { super(typeInfo, minRetentionTime); this.serializer = serializer; this.generateUpdateBefore = generateUpdateBefore; this.generateInsert = generateInsert; this.rowtimeIndex = rowtimeIndex; this.keepLastRow = keepLastRow; } @Override public RowData addInput(@Nullable RowData value, RowData input) throws Exception { if (shouldKeepCurrentRow(value, input, rowtimeIndex, keepLastRow)) { return serializer.copy(input); } return value; } @Override public void finishBundle(Map<RowData, RowData> buffer, Collector<RowData> out) throws Exception { for (Map.Entry<RowData, RowData> entry : buffer.entrySet()) { RowData currentKey = entry.getKey(); RowData bufferedRow = entry.getValue(); ctx.setCurrentKey(currentKey); RowData preRow = state.value(); checkInsertOnly(bufferedRow); if (shouldKeepCurrentRow(preRow, bufferedRow, rowtimeIndex, keepLastRow)) { updateDeduplicateResult( generateUpdateBefore, generateInsert, preRow, bufferedRow, out); state.update(bufferedRow); } } } }
RowTimeMiniBatchLatestChangeDeduplicateFunction
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedAnonymousClassTest.java
{ "start": 5052, "end": 5654 }
class ____ { static ArrayList<Callable<Void>> callables = new ArrayList<>(); static Void register(Callable<Void> callable) { callables.add(callable); return null; } public static void main(String[] args) throws Exception { new Callable<Void>() { Void register = register(this); public Void call() throws Exception { return null; } }; } } """) .doTest(); } }
One
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInJsonTest.java
{ "start": 1014, "end": 1180 }
class ____ extends MarkerMixInTest { @Override protected ObjectMapper newObjectMapper() { return new Log4jJsonObjectMapper(); } }
MarkerMixInJsonTest
java
elastic__elasticsearch
x-pack/plugin/mapper-counted-keyword/src/main/java/org/elasticsearch/xpack/countedkeyword/CountedKeywordFieldMapper.java
{ "start": 8459, "end": 10819 }
class ____ extends AbstractSortedSetDocValues { private final SortedSetDocValues dvValues; private final BinaryDocValues dvCounts; private int sumCount; private Iterator<Long> ordsForThisDoc; private final ByteArrayStreamInput scratch = new ByteArrayStreamInput(); CountedKeywordSortedBinaryDocValues(SortedSetDocValues dvValues, BinaryDocValues dvCounts) { this.dvValues = dvValues; this.dvCounts = dvCounts; } @Override public boolean advanceExact(int doc) throws IOException { sumCount = 0; if (dvValues.advanceExact(doc)) { boolean exactMatch = dvCounts.advanceExact(doc); assert exactMatch; BytesRef encodedValue = dvCounts.binaryValue(); scratch.reset(encodedValue.bytes, encodedValue.offset, encodedValue.length); int[] counts = scratch.readVIntArray(); assert counts.length == dvValues.docValueCount(); List<Long> values = new ArrayList<>(); for (int count : counts) { this.sumCount += count; long ord = dvValues.nextOrd(); for (int j = 0; j < count; j++) { values.add(ord); } } this.ordsForThisDoc = values.iterator(); return true; } else { ordsForThisDoc = null; return false; } } @Override public int docValueCount() { return sumCount; } @Override public long nextOrd() { assert ordsForThisDoc.hasNext(); return ordsForThisDoc.next(); } @Override public BytesRef lookupOrd(long ord) throws IOException { return dvValues.lookupOrd(ord); } @Override public long getValueCount() { return dvValues.getValueCount(); } @Override public TermsEnum termsEnum() throws IOException { return dvValues.termsEnum(); } } private static CountedKeywordFieldMapper toType(FieldMapper in) { return (CountedKeywordFieldMapper) in; } public static
CountedKeywordSortedBinaryDocValues
java
apache__flink
flink-clients/src/main/java/org/apache/flink/client/cli/ApplicationDeployer.java
{ "start": 1031, "end": 1138 }
interface ____ be used by the {@link CliFrontend} to submit user programs for execution. */ @Internal public
to
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/async/utils/CatchFunction.java
{ "start": 4064, "end": 4632 }
class ____ * representing the type of exception to catch. The method uses the handle method of the * {@code CompletableFuture} to apply the catch function. * <p> * If the input future completes exceptionally with an instance of the specified exception * type, the catch function is applied to the exception. If the future completes with a * different type of exception or normally, the original result or exception is propagated. * * @param in the input {@code CompletableFuture} to which the catch function is applied * @param eClazz the
object
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/StateSerializerProvider.java
{ "start": 2929, "end": 14614 }
class ____<T> { /** * The registered serializer for the state. * * <p>In the case that this provider was created from a restored serializer snapshot via {@link * #fromPreviousSerializerSnapshot(TypeSerializerSnapshot)}, but a new serializer was never * registered for the state (i.e., this is the case if a restored state was never accessed), * this would be {@code null}. */ @Nullable TypeSerializer<T> registeredSerializer; /** * The state's previous serializer's snapshot. * * <p>In the case that this provider was created from a registered state serializer instance via * {@link #fromNewRegisteredSerializer(TypeSerializer)}, but a serializer snapshot was never * supplied to this provider (i.e. because the registered serializer was for a new state, not a * restored one), this would be {@code null}. */ @Nullable TypeSerializerSnapshot<T> previousSerializerSnapshot; /** * The restore serializer, lazily created only when the restore serializer is accessed. * * <p>NOTE: It is important to only create this lazily, so that off-heap state do not fail * eagerly when restoring state that has a {@link UnloadableDummyTypeSerializer} as the previous * serializer. This should be relevant only for restores from Flink versions prior to 1.7.x. */ @Nullable private TypeSerializer<T> cachedRestoredSerializer; private boolean isRegisteredWithIncompatibleSerializer = false; /** * Creates a {@link StateSerializerProvider} for restored state from the previous serializer's * snapshot. * * <p>Once a new serializer is registered for the state, it should be provided via the {@link * #registerNewSerializerForRestoredState(TypeSerializer)} method. * * @param stateSerializerSnapshot the previous serializer's snapshot. * @param <T> the type of the state. * @return a new {@link StateSerializerProvider}. */ public static <T> StateSerializerProvider<T> fromPreviousSerializerSnapshot( TypeSerializerSnapshot<T> stateSerializerSnapshot) { return new LazilyRegisteredStateSerializerProvider<>(stateSerializerSnapshot); } /** * Creates a {@link StateSerializerProvider} from the registered state serializer. * * <p>If the state is a restored one, and the previous serializer's snapshot is obtained later * on, is should be supplied via the {@link * #setPreviousSerializerSnapshotForRestoredState(TypeSerializerSnapshot)} method. * * @param registeredStateSerializer the new state's registered serializer. * @param <T> the type of the state. * @return a new {@link StateSerializerProvider}. */ public static <T> StateSerializerProvider<T> fromNewRegisteredSerializer( TypeSerializer<T> registeredStateSerializer) { return new EagerlyRegisteredStateSerializerProvider<>(registeredStateSerializer); } private StateSerializerProvider(@Nonnull TypeSerializer<T> stateSerializer) { this.registeredSerializer = stateSerializer; this.previousSerializerSnapshot = null; } private StateSerializerProvider(@Nonnull TypeSerializerSnapshot<T> previousSerializerSnapshot) { this.previousSerializerSnapshot = previousSerializerSnapshot; this.registeredSerializer = null; } /** * Gets the serializer that recognizes the current serialization schema of the state. This is * the serializer that should be used for regular state serialization and deserialization after * state has been restored. * * <p>If this provider was created from a restored state's serializer snapshot, while a new * serializer (with a new schema) was not registered for the state (i.e., because the state was * never accessed after it was restored), then the schema of state remains identical. Therefore, * in this case, it is guaranteed that the serializer returned by this method is the same as the * one returned by {@link #previousSchemaSerializer()}. * * <p>If this provider was created from a serializer instance, then this always returns the that * same serializer instance. If later on a snapshot of the previous serializer is supplied via * {@link #setPreviousSerializerSnapshotForRestoredState(TypeSerializerSnapshot)}, then the * initially supplied serializer instance will be checked for compatibility. * * @return a serializer that reads and writes in the current schema of the state. */ @Nonnull public final TypeSerializer<T> currentSchemaSerializer() { if (registeredSerializer != null) { checkState( !isRegisteredWithIncompatibleSerializer, "Unable to provide a serializer with the current schema, because the restored state was " + "registered with a new serializer that has incompatible schema."); return registeredSerializer; } // if we are not yet registered with a new serializer, // we can just use the restore serializer to read / write the state. return previousSchemaSerializer(); } /** * Gets the serializer that recognizes the previous serialization schema of the state. This is * the serializer that should be used for restoring the state, i.e. when the state is still in * the previous serialization schema. * * <p>This method only returns a serializer if this provider has the previous serializer's * snapshot. Otherwise, trying to access the previous schema serializer will fail with an * exception. * * @return a serializer that reads and writes in the previous schema of the state. */ @Nonnull public final TypeSerializer<T> previousSchemaSerializer() { if (cachedRestoredSerializer != null) { return cachedRestoredSerializer; } if (previousSerializerSnapshot == null) { throw new UnsupportedOperationException( "This provider does not contain the state's previous serializer's snapshot. Cannot provider a serializer for previous schema."); } this.cachedRestoredSerializer = previousSerializerSnapshot.restoreSerializer(); return cachedRestoredSerializer; } /** * Gets the previous serializer snapshot. * * @return The previous serializer snapshot, or null if registered serializer was for a new * state, not a restored one. */ @Nullable public final TypeSerializerSnapshot<T> getPreviousSerializerSnapshot() { return previousSerializerSnapshot; } /** * For restored state, register a new serializer that potentially has a new serialization * schema. * * <p>Users are allowed to register serializers for state only once. Therefore, this method is * irrelevant if this provider was created with a serializer instance, since a state serializer * had been registered already. * * <p>For the case where this provider was created from a serializer snapshot, then this method * should be called at most once. The new serializer will be checked for its schema * compatibility with the previous serializer's schema, and returned to the caller. The caller * is responsible for checking the result and react appropriately to it, as follows: * * <ul> * <li>{@link TypeSerializerSchemaCompatibility#isCompatibleAsIs()}: nothing needs to be done. * {@link #currentSchemaSerializer()} now returns the newly registered serializer. * <li>{@link TypeSerializerSchemaCompatibility#isCompatibleAfterMigration()}: state needs to * be migrated before the serializer returned by {@link #currentSchemaSerializer()} can be * used. The migration should be performed by reading the state with {@link * #previousSchemaSerializer()}, and then writing it again with {@link * #currentSchemaSerializer()}. * <li>{@link TypeSerializerSchemaCompatibility#isIncompatible()}: the registered serializer * is incompatible. {@link #currentSchemaSerializer()} can no longer return a serializer * for the state, and therefore this provider shouldn't be used anymore. * </ul> * * @return the schema compatibility of the new registered serializer, with respect to the * previous serializer. */ @Nonnull public abstract TypeSerializerSchemaCompatibility<T> registerNewSerializerForRestoredState( TypeSerializer<T> newSerializer); /** * For restored state, set the state's previous serializer's snapshot. * * <p>Users are allowed to set the previous serializer's snapshot once. Therefore, this method * is irrelevant if this provider was created with a serializer snapshot, since the serializer * snapshot had been set already. * * <p>For the case where this provider was created from a serializer instance, then this method * should be called at most once. The initially registered state serializer will be checked for * its schema compatibility with the previous serializer's schema, and returned to the caller. * The caller is responsible for checking the result and react appropriately to it, as follows: * * <ul> * <li>{@link TypeSerializerSchemaCompatibility#isCompatibleAsIs()}: nothing needs to be done. * {@link #currentSchemaSerializer()} remains to return the initially registered * serializer. * <li>{@link TypeSerializerSchemaCompatibility#isCompatibleAfterMigration()}: state needs to * be migrated before the serializer returned by {@link #currentSchemaSerializer()} can be * used. The migration should be performed by reading the state with {@link * #previousSchemaSerializer()}, and then writing it again with {@link * #currentSchemaSerializer()}. * <li>{@link TypeSerializerSchemaCompatibility#isIncompatible()}: the registered serializer * is incompatible. {@link #currentSchemaSerializer()} can no longer return a serializer * for the state, and therefore this provider shouldn't be used anymore. * </ul> * * @param previousSerializerSnapshot the state's previous serializer's snapshot * @return the schema compatibility of the initially registered serializer, with respect to the * previous serializer. */ @Nonnull public abstract TypeSerializerSchemaCompatibility<T> setPreviousSerializerSnapshotForRestoredState( TypeSerializerSnapshot<T> previousSerializerSnapshot); /** * Invalidates access to the current schema serializer. This lets {@link * #currentSchemaSerializer()} fail when invoked. * * <p>Access to the current schema serializer should be invalidated by the methods {@link * #registerNewSerializerForRestoredState(TypeSerializer)} or {@link * #setPreviousSerializerSnapshotForRestoredState(TypeSerializerSnapshot)} once the registered * serializer is determined to be incompatible. */ protected final void invalidateCurrentSchemaSerializerAccess() { this.isRegisteredWithIncompatibleSerializer = true; } /** * Implementation of the {@link StateSerializerProvider} for the case where a snapshot of the * previous serializer is obtained before a new state serializer is registered (hence, the * naming "lazily" registered). */ private static
StateSerializerProvider
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinator.java
{ "start": 16128, "end": 16444 }
interface ____ extends Serializable { /** Gets the ID of the operator to which the coordinator belongs. */ OperatorID getOperatorId(); /** Creates the {@code OperatorCoordinator}, using the given context. */ OperatorCoordinator create(Context context) throws Exception; } }
Provider
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/authentication/ProviderManagerBuilder.java
{ "start": 1167, "end": 1904 }
interface ____<B extends ProviderManagerBuilder<B>> extends SecurityBuilder<AuthenticationManager> { /** * Add authentication based upon the custom {@link AuthenticationProvider} that is * passed in. Since the {@link AuthenticationProvider} implementation is unknown, all * customizations must be done externally and the {@link ProviderManagerBuilder} is * returned immediately. * * Note that an Exception is thrown if an error occurs when adding the * {@link AuthenticationProvider}. * @return a {@link ProviderManagerBuilder} to allow further authentication to be * provided to the {@link ProviderManagerBuilder} */ B authenticationProvider(AuthenticationProvider authenticationProvider); }
ProviderManagerBuilder
java
elastic__elasticsearch
test/external-modules/multi-project/src/javaRestTest/java/org/elasticsearch/multiproject/action/ProjectCrudActionIT.java
{ "start": 1365, "end": 4398 }
class ____ extends MultiProjectRestTestCase { @ClassRule public static ElasticsearchCluster CLUSTER = ElasticsearchCluster.local() .distribution(DistributionType.INTEG_TEST) .setting("test.multi_project.enabled", "true") .setting("xpack.security.enabled", "false") .build(); @Override protected String getTestRestCluster() { return CLUSTER.getHttpAddresses(); } public void testCreateAndDeleteProject() throws IOException { final var projectId = randomUniqueProjectId(); var request = new Request("PUT", "/_project/" + projectId); final int numberOfRequests = between(1, 8); final var successCount = new AtomicInteger(); final var errorCount = new AtomicInteger(); runInParallel(numberOfRequests, ignore -> { try { var response = client().performRequest(request); assertAcknowledged(response); successCount.incrementAndGet(); } catch (IOException e) { if (e instanceof ResponseException responseException) { assertThat(responseException.getMessage(), containsString("project [" + projectId + "] already exists")); errorCount.incrementAndGet(); return; } fail(e, "unexpected exception"); } }); assertThat(successCount.get(), equalTo(1)); assertThat(errorCount.get(), equalTo(numberOfRequests - 1)); assertThat(getProjectIdsFromClusterState(), hasItem(projectId.id())); final Response response = client().performRequest(new Request("DELETE", "/_project/" + projectId)); assertAcknowledged(response); assertThat(getProjectIdsFromClusterState(), not(hasItem(projectId.id()))); } private Set<String> getProjectIdsFromClusterState() throws IOException { final Response response = client().performRequest(new Request("GET", "/_cluster/state?multi_project=true")); final ObjectPath clusterState = assertOKAndCreateObjectPath(response); final Set<String> projectIdsFromMetadata = extractProjectIds(clusterState, "metadata.projects"); final Set<String> projectIdsFromRoutingTable = extractProjectIds(clusterState, "routing_table.projects"); assertThat(projectIdsFromMetadata, equalTo(projectIdsFromRoutingTable)); return projectIdsFromMetadata; } @SuppressWarnings("unchecked") private Set<String> extractProjectIds(ObjectPath clusterState, String path) throws IOException { final int numberProjects = ((List<Object>) clusterState.evaluate(path)).size(); return IntStream.range(0, numberProjects).mapToObj(i -> { try { return (String) clusterState.evaluate(path + "." + i + ".id"); } catch (IOException e) { throw new UncheckedIOException(e); } }).collect(Collectors.toUnmodifiableSet()); } }
ProjectCrudActionIT
java
apache__camel
components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpEndpointUriAssemblerTest.java
{ "start": 1139, "end": 2988 }
class ____ extends CamelTestSupport { @Test public void testAsEndpointUriNettyHttpHostnameWithDash() throws Exception { EndpointUriFactory assembler = context.getCamelContextExtension().getEndpointUriFactory("netty-http"); Map<String, Object> map = new LinkedHashMap<>(); map.put("protocol", "http"); map.put("host", "a-b-c.hostname.tld"); map.put("port", "8080"); map.put("path", "anything"); String uri = assembler.buildUri("netty-http", map); assertEquals("netty-http:http://a-b-c.hostname.tld:8080/anything", uri); map = new LinkedHashMap<>(); map.put("protocol", "http"); map.put("host", "a-b-c.server.net"); map.put("port", "8888"); map.put("path", "service/v3"); uri = assembler.buildUri("netty-http", map); assertEquals("netty-http:http://a-b-c.server.net:8888/service/v3", uri); map = new HashMap<>(); // use http protocol map.put("protocol", "http"); map.put("host", "localhost"); map.put("port", "8080"); map.put("path", "foo/bar"); map.put("disconnect", "true"); uri = assembler.buildUri("netty-http", map); assertEquals("netty-http:http://localhost:8080/foo/bar?disconnect=true", uri); // lets switch protocol map.put("protocol", "https"); uri = assembler.buildUri("netty-http", map); assertEquals("netty-http:https://localhost:8080/foo/bar?disconnect=true", uri); // lets set a query parameter in the path map.put("path", "foo/bar?verbose=true"); map.put("disconnect", "true"); uri = assembler.buildUri("netty-http", map); assertEquals("netty-http:https://localhost:8080/foo/bar?verbose=true&disconnect=true", uri); } }
NettyHttpEndpointUriAssemblerTest
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerIntegrationTests.java
{ "start": 8302, "end": 8516 }
class ____ implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.setPatternParser(new PathPatternParser()); } } static
PathPatternParserConfig
java
micronaut-projects__micronaut-core
runtime-osx/src/main/java/io/micronaut/scheduling/io/watch/osx/MacOsWatchServiceFactory.java
{ "start": 1816, "end": 2869 }
class ____ { protected static final Logger LOG = LoggerFactory.getLogger(WatchServiceFactory.class); /** * The default {@link WatchService}. * * @return The watch service to use. * @throws IOException if an error occurs creating the watch service */ @Bean(preDestroy = "close") @Prototype @Requires(classes = {MacOSXListeningWatchService.class, Library.class}) @Requires(property = FileWatchConfiguration.ENABLED, value = StringUtils.TRUE, defaultValue = StringUtils.TRUE) @Requires(property = FileWatchConfiguration.PATHS) @Primary protected WatchService macWatchService() throws IOException { try { return new MacOSXListeningWatchService(); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn("Unable to create Mac OS X specific watch service. Falling back to default polling strategy: {}", e.getMessage(), e); } return new WatchServiceFactory().watchService(); } } }
MacOsWatchServiceFactory
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/parsetools/impl/JsonParserImpl.java
{ "start": 12226, "end": 14145 }
class ____ implements Handler<JsonEventImpl> { Handler<Void> handler; int depth; TokenParser buffer; @Override public void handle(JsonEventImpl event) { String fieldName = event.fieldName(); if (fieldName != null) { buffer.tokens.add(JsonToken.FIELD_NAME); buffer.tokens.add(fieldName); } try { switch (event.type()) { case START_OBJECT: case START_ARRAY: if (depth++ == 0) { JsonFactory factory = new JsonFactory(); buffer = new TokenParser(new IOContext(factory._getBufferRecycler(), this, true), com.fasterxml.jackson.core.JsonParser.Feature.collectDefaults()); } buffer.tokens.add(event.token()); break; case VALUE: JsonToken token = event.token(); buffer.tokens.add(token); if (token != JsonToken.VALUE_FALSE && token != JsonToken.VALUE_TRUE && token != JsonToken.VALUE_NULL) { buffer.tokens.add(event.value()); } break; case END_OBJECT: case END_ARRAY: buffer.tokens.add(event.token()); if (--depth == 0) { handler.handle(null); buffer.close(); buffer = null; } break; default: throw new UnsupportedOperationException("Not implemented " + event); } } catch (IOException e) { // Should not happen as we are buffering throw new VertxException(e); } } <T> T convert(Class<T> type) { return JacksonCodec.fromParser(buffer, type); } } @Override public JsonParser write(Buffer buffer) { handle(buffer); return this; } @Override public JsonParser exceptionHandler(Handler<Throwable> handler) { exceptionHandler = handler; return this; } }
BufferingHandler
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/issues/Issue5932.java
{ "start": 491, "end": 2924 }
class ____ { @Test public void test_parse_selectsum() { for (DbType dbType : new DbType[]{DbType.mysql}) { for (String sql : new String[]{ "SELECT a.aab001, COUNT(DISTINCT a.aac001) AS 住院人数, SUM(a.bka030) AS 住院天数\n" + "\t, SUM((\n" + "\t\tSELECT SUM(b.aae019)\n" + "\t\tFROM kc27 b\n" + "\t\tWHERE b.aaa157 IN ('350100','350300','350806')\n" + "\t\t\tAND a.AKB020 = b.AKB020\n" + "\t AND a.AAZ217 = b.AAZ217\n" + "\t AND b.AAE100 = '1'\n" + "\t)) AS '住院记账医疗费用'\n" + "FROM kc21 a\n" + "WHERE a.aae100 = '1'\n" + "\tAND a.aka130 = '62'\n" + "\tAND a.BAA027 = '440111'\n" + "\tAND a.AKC194 >= DATE_FORMAT('20240401', '%Y-%m-%d %T')\n" + "\tAND a.AKC194 < DATE_FORMAT('20240501', '%Y-%m-%d %T')\n" + "\tGROUP BY a.aab001;", }) { SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType); List<SQLStatement> statementList = parser.parseStatementList(); System.out.println(statementList); assertEquals(1, statementList.size()); assertEquals("SELECT a.aab001, COUNT(DISTINCT a.aac001) AS 住院人数, SUM(a.bka030) AS 住院天数\n" + "\t, SUM((\n" + "\t\tSELECT SUM(b.aae019)\n" + "\t\tFROM kc27 b\n" + "\t\tWHERE b.aaa157 IN ('350100', '350300', '350806')\n" + "\t\t\tAND a.AKB020 = b.AKB020\n" + "\t\t\tAND a.AAZ217 = b.AAZ217\n" + "\t\t\tAND b.AAE100 = '1'\n" + "\t)) AS \"住院记账医疗费用\"\n" + "FROM kc21 a\n" + "WHERE a.aae100 = '1'\n" + "\tAND a.aka130 = '62'\n" + "\tAND a.BAA027 = '440111'\n" + "\tAND a.AKC194 >= DATE_FORMAT('20240401', '%Y-%m-%d %T')\n" + "\tAND a.AKC194 < DATE_FORMAT('20240501', '%Y-%m-%d %T')\n" + "GROUP BY a.aab001;", statementList.get(0).toString()); SQLParseAssertUtil.assertParseSql(sql, dbType); } } } }
Issue5932
java
bumptech__glide
annotation/compiler/src/main/java/com/bumptech/glide/annotation/compiler/AppModuleGenerator.java
{ "start": 1182, "end": 1453 }
class ____ always call the AppGlideModule last to give it priority over choices * made or classes registered in LibraryGlideModules. * * <p>Android logging is included to allow developers to see exactly which modules are included at * runtime. * * <p>The generated
will
java
spring-projects__spring-framework
buildSrc/src/main/java/org/springframework/build/JavaConventions.java
{ "start": 1202, "end": 4880 }
class ____ { private static final List<String> COMPILER_ARGS; private static final List<String> TEST_COMPILER_ARGS; /** * The Java version we should use as the JVM baseline for building the project. * <p>NOTE: If you update this value, you should also update the value used in * the {@code javadoc} task in {@code framework-api.gradle}. */ private static final JavaLanguageVersion DEFAULT_LANGUAGE_VERSION = JavaLanguageVersion.of(25); /** * The Java version we should use as the baseline for the compiled bytecode * (the "-release" compiler argument). */ private static final JavaLanguageVersion DEFAULT_RELEASE_VERSION = JavaLanguageVersion.of(17); static { List<String> commonCompilerArgs = List.of( "-Xlint:serial", "-Xlint:cast", "-Xlint:classfile", "-Xlint:dep-ann", "-Xlint:divzero", "-Xlint:empty", "-Xlint:finally", "-Xlint:overrides", "-Xlint:path", "-Xlint:processing", "-Xlint:static", "-Xlint:try", "-Xlint:-options", "-parameters" ); COMPILER_ARGS = new ArrayList<>(); COMPILER_ARGS.addAll(commonCompilerArgs); COMPILER_ARGS.addAll(List.of( "-Xlint:varargs", "-Xlint:fallthrough", "-Xlint:rawtypes", "-Xlint:deprecation", "-Xlint:unchecked", "-Werror" )); TEST_COMPILER_ARGS = new ArrayList<>(); TEST_COMPILER_ARGS.addAll(commonCompilerArgs); TEST_COMPILER_ARGS.addAll(List.of("-Xlint:-varargs", "-Xlint:-fallthrough", "-Xlint:-rawtypes", "-Xlint:-deprecation", "-Xlint:-unchecked")); } public void apply(Project project) { project.getPlugins().withType(JavaBasePlugin.class, javaPlugin -> { applyToolchainConventions(project); applyJavaCompileConventions(project); }); } /** * Configure the Toolchain support for the project. * @param project the current project */ private static void applyToolchainConventions(Project project) { project.getExtensions().getByType(JavaPluginExtension.class).toolchain(toolchain -> { toolchain.getLanguageVersion().set(DEFAULT_LANGUAGE_VERSION); }); } /** * Apply the common Java compiler options for main sources, test fixture sources, and * test sources. * @param project the current project */ private void applyJavaCompileConventions(Project project) { project.afterEvaluate(p -> { p.getTasks().withType(JavaCompile.class) .matching(compileTask -> compileTask.getName().startsWith(JavaPlugin.COMPILE_JAVA_TASK_NAME)) .forEach(compileTask -> { compileTask.getOptions().setCompilerArgs(COMPILER_ARGS); compileTask.getOptions().setEncoding("UTF-8"); setJavaRelease(compileTask); }); p.getTasks().withType(JavaCompile.class) .matching(compileTask -> compileTask.getName().startsWith(JavaPlugin.COMPILE_TEST_JAVA_TASK_NAME) || compileTask.getName().equals("compileTestFixturesJava")) .forEach(compileTask -> { compileTask.getOptions().setCompilerArgs(TEST_COMPILER_ARGS); compileTask.getOptions().setEncoding("UTF-8"); setJavaRelease(compileTask); }); }); } /** * We should pick the {@link #DEFAULT_RELEASE_VERSION} for all compiled classes, * unless the current task is compiling multi-release JAR code with a higher version. */ private void setJavaRelease(JavaCompile task) { int defaultVersion = DEFAULT_RELEASE_VERSION.asInt(); int releaseVersion = defaultVersion; int compilerVersion = task.getJavaCompiler().get().getMetadata().getLanguageVersion().asInt(); for (int version = defaultVersion ; version <= compilerVersion ; version++) { if (task.getName().contains("Java" + version)) { releaseVersion = version; break; } } task.getOptions().getRelease().set(releaseVersion); } }
JavaConventions
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/component/instance/ComponentInstanceEvent.java
{ "start": 1086, "end": 1887 }
class ____ extends AbstractEvent<ComponentInstanceEventType> { private ContainerId id; private ContainerStatus status; private boolean shouldDestroy = false; public ComponentInstanceEvent(ContainerId containerId, ComponentInstanceEventType componentInstanceEventType) { super(componentInstanceEventType); Preconditions.checkNotNull(containerId); this.id = containerId; } public ContainerId getContainerId() { return id; } public ContainerStatus getStatus() { return this.status; } public ComponentInstanceEvent setStatus(ContainerStatus status) { this.status = status; return this; } public void setShouldDestroy() { shouldDestroy = true; } public boolean shouldDestroy() { return shouldDestroy; } }
ComponentInstanceEvent
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/dev/IsolatedRemoteDevModeMain.java
{ "start": 8682, "end": 9269 }
class ____ @Override public void accept(CuratedApplication o, Map<String, Object> o2) { LoggingSetupRecorder.handleFailedStart(); //we are not going to actually run an app Timing.staticInitStarted(o.getOrCreateBaseRuntimeClassLoader(), false); try { curatedApplication = o; Object potentialContext = o2.get(DevModeContext.class.getName()); if (potentialContext instanceof DevModeContext) { context = (DevModeContext) potentialContext; } else { //this was from the external
loader
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/cluster/coordination/CoordinationDiagnosticsAction.java
{ "start": 4119, "end": 5127 }
class ____ extends HandledTransportAction<Request, Response> { private final CoordinationDiagnosticsService coordinationDiagnosticsService; @Inject public TransportAction( TransportService transportService, ActionFilters actionFilters, CoordinationDiagnosticsService coordinationDiagnosticsService ) { super( CoordinationDiagnosticsAction.NAME, transportService, actionFilters, Request::new, transportService.getThreadPool().executor(ThreadPool.Names.CLUSTER_COORDINATION) ); this.coordinationDiagnosticsService = coordinationDiagnosticsService; } @Override protected void doExecute(Task task, Request request, ActionListener<Response> listener) { listener.onResponse(new Response(coordinationDiagnosticsService.diagnoseMasterStability(request.explain))); } } }
TransportAction
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/bom/BomExtension.java
{ "start": 10175, "end": 11373 }
class ____ { private String reason; private final List<String> startsWith = new ArrayList<>(); private final List<String> endsWith = new ArrayList<>(); private final List<String> contains = new ArrayList<>(); private VersionRange versionRange; public void versionRange(String versionRange) { try { this.versionRange = VersionRange.createFromVersionSpec(versionRange); } catch (InvalidVersionSpecificationException ex) { throw new InvalidUserCodeException("Invalid version range", ex); } } public void startsWith(String startsWith) { this.startsWith.add(startsWith); } public void startsWith(Collection<String> startsWith) { this.startsWith.addAll(startsWith); } public void endsWith(String endsWith) { this.endsWith.add(endsWith); } public void endsWith(Collection<String> endsWith) { this.endsWith.addAll(endsWith); } public void contains(String contains) { this.contains.add(contains); } public void contains(List<String> contains) { this.contains.addAll(contains); } public void because(String because) { this.reason = because; } } public static
ProhibitedHandler
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/io/compression/Bzip2InputStreamFactory.java
{ "start": 1161, "end": 1729 }
class ____ implements InflaterInputStreamFactory<BZip2CompressorInputStream> { private static final Bzip2InputStreamFactory INSTANCE = new Bzip2InputStreamFactory(); public static Bzip2InputStreamFactory getInstance() { return INSTANCE; } @Override public BZip2CompressorInputStream create(InputStream in) throws IOException { return new BZip2CompressorInputStream(in); } @Override public Collection<String> getCommonFileExtensions() { return Collections.singleton("bz2"); } }
Bzip2InputStreamFactory
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/spi/AbstractCommonQueryContract.java
{ "start": 10503, "end": 42363 }
enum ____ if ( hintValue != null ) { hints.put( hintName, hintValue ); // hints.put( hintName, hintValue.name() ); } } protected void putIfNotNull(Map<String, Object> hints, String hintName, Object hintValue) { if ( hintValue != null ) { hints.put( hintName, hintValue ); } } @Override public CommonQueryContract setHint(String hintName, Object value) { if ( !applyHint( hintName, value ) ) { QUERY_MESSAGE_LOGGER.ignoringUnrecognizedQueryHint( hintName ); } return this; } public final boolean applyHint(String hintName, Object value) { getSession().checkOpen( true ); try { switch ( hintName ) { case HINT_FLUSH_MODE: applyFlushModeHint( ConfigurationHelper.getFlushMode( value ) ); return true; case HINT_TIMEOUT: applyTimeoutHint( getInteger( value ) ); return true; case HINT_JAVAEE_QUERY_TIMEOUT: DEPRECATION_LOGGER.deprecatedSetting( HINT_JAVAEE_QUERY_TIMEOUT, HINT_SPEC_QUERY_TIMEOUT ); //fall through: case HINT_SPEC_QUERY_TIMEOUT: // convert milliseconds to seconds int timeout = (int) Math.round( getInteger( value ).doubleValue() / 1000.0 ); applyTimeoutHint( timeout ); return true; case HINT_COMMENT: applyCommentHint( (String) value ); return true; case HINT_NATIVE_SPACES: applySynchronizeSpacesHint( value ); return true; case HINT_QUERY_DATABASE: applyDatabaseHint( (String) value ); return true; default: return applySelectionHint( hintName, value ); } } catch ( ClassCastException e ) { throw new IllegalArgumentException( "Incorrect value for query hint: " + hintName, e ); } } protected void applySynchronizeSpacesHint(Object value) { throw new IllegalArgumentException( "Query spaces hint was specified for non-native query" ); } protected final boolean applySelectionHint(String hintName, Object value) { if ( applyLockingHint( hintName, value ) ) { return true; } else { final var queryOptions = getQueryOptions(); switch ( hintName ) { case HINT_READONLY: queryOptions.setReadOnly( getBoolean( value ) ); return true; case HINT_FETCH_SIZE: queryOptions.setFetchSize( getInteger( value ) ); return true; case HINT_QUERY_PLAN_CACHEABLE: queryOptions.setQueryPlanCachingEnabled( getBoolean( value ) ); return true; case HINT_CACHEABLE: queryOptions.setResultCachingEnabled( getBoolean( value ) ); return true; case HINT_CACHE_REGION: queryOptions.setResultCacheRegionName( (String) value ); return true; case HINT_CACHE_MODE: queryOptions.setCacheMode( getCacheMode( value ) ); return true; case HINT_JAVAEE_CACHE_RETRIEVE_MODE: DEPRECATION_LOGGER.deprecatedHint( HINT_JAVAEE_CACHE_RETRIEVE_MODE, HINT_SPEC_CACHE_RETRIEVE_MODE ); //fall through to: case HINT_SPEC_CACHE_RETRIEVE_MODE: final var retrieveMode = value == null ? null : CacheRetrieveMode.valueOf( value.toString() ); queryOptions.setCacheRetrieveMode( retrieveMode ); return true; case HINT_JAVAEE_CACHE_STORE_MODE: DEPRECATION_LOGGER.deprecatedHint( HINT_JAVAEE_CACHE_STORE_MODE, HINT_SPEC_CACHE_STORE_MODE ); //fall through to: case HINT_SPEC_CACHE_STORE_MODE: final var storeMode = value == null ? null : CacheStoreMode.valueOf( value.toString() ); queryOptions.setCacheStoreMode( storeMode ); return true; case HINT_JAVAEE_FETCH_GRAPH: DEPRECATION_LOGGER.deprecatedHint( HINT_JAVAEE_FETCH_GRAPH, HINT_SPEC_FETCH_GRAPH ); //fall through to: case HINT_SPEC_FETCH_GRAPH: applyEntityGraphHint( GraphSemantic.FETCH, value, hintName ); return true; case HINT_JAVAEE_LOAD_GRAPH: DEPRECATION_LOGGER.deprecatedHint( HINT_JAVAEE_LOAD_GRAPH, HINT_SPEC_LOAD_GRAPH ); //fall through to: case HINT_SPEC_LOAD_GRAPH: applyEntityGraphHint( GraphSemantic.LOAD, value, hintName ); return true; case HINT_FETCH_PROFILE: queryOptions.enableFetchProfile( (String) value ); default: // unrecognized hint return false; } } } protected void applyEntityGraphHint(GraphSemantic graphSemantic, Object value, String hintName) { if ( value instanceof RootGraphImplementor<?> rootGraphImplementor ) { applyGraph( rootGraphImplementor, graphSemantic ); } else if ( value instanceof String string ) { // try and interpret it as the name of a @NamedEntityGraph final var entityGraph = getEntityGraph( string ); if ( entityGraph == null ) { try { // try and parse it in the entity graph language applyGraph( string, graphSemantic ); } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException( "The string value of the hint '" + hintName + "' must be the name of a named EntityGraph, or a representation understood by GraphParser" ); } } else { applyGraph( entityGraph, graphSemantic ); } } else { throw new IllegalArgumentException( "The value of the hint '" + hintName + "' must be an instance of EntityGraph, the string name of a named EntityGraph, or a string representation understood by GraphParser" ); } } private RootGraphImplementor<?> getEntityGraph(String string) { try { return getSession().getEntityGraph( string ); } catch ( IllegalArgumentException e ) { return null; } } protected void applyGraph(String graphString, GraphSemantic graphSemantic) { final int separatorPosition = graphString.indexOf( '(' ); final int terminatorPosition = graphString.lastIndexOf( ')' ); if ( separatorPosition < 0 || terminatorPosition < 0 ) { throw new IllegalArgumentException( String.format( ROOT, "Invalid entity-graph definition '%s'; expected form '${EntityName}( ${property1} ... )'", graphString ) ); } final var factory = getSessionFactory(); final String entityName = factory.getMappingMetamodel() .getImportedName( graphString.substring( 0, separatorPosition ).trim() ); final String graphNodes = graphString.substring( separatorPosition + 1, terminatorPosition ); final var rootGraph = new RootGraphImpl<>( null, factory.getJpaMetamodel().entity( entityName ) ); GraphParser.parseInto( (EntityGraph<?>) rootGraph, graphNodes, getSessionFactory() ); applyGraph( rootGraph, graphSemantic ); } protected void applyGraph(RootGraphImplementor<?> entityGraph, GraphSemantic graphSemantic) { getQueryOptions().applyGraph( entityGraph, graphSemantic ); } private boolean applyLockingHint(String hintName, Object value) { switch ( hintName ) { case HINT_JAVAEE_LOCK_TIMEOUT: DEPRECATION_LOGGER.deprecatedHint( HINT_JAVAEE_LOCK_TIMEOUT, HINT_SPEC_LOCK_TIMEOUT ); //fall through to: case HINT_SPEC_LOCK_TIMEOUT: if ( value != null ) { applyLockTimeoutHint( getInteger( value ) ); return true; } else { return false; } case HINT_FOLLOW_ON_STRATEGY: if ( value == null ) { applyFollowOnStrategyHint( Locking.FollowOn.ALLOW ); } if ( value instanceof Locking.FollowOn strategyValue ) { applyFollowOnStrategyHint( strategyValue ); } else { applyFollowOnStrategyHint( Locking.FollowOn.valueOf( value.toString() ) ); } return true; case HINT_FOLLOW_ON_LOCKING: applyFollowOnLockingHint( getBoolean( value ) ); return true; case HINT_NATIVE_LOCKMODE: applyLockModeHint( value ); return true; default: if ( hintName.startsWith( HINT_NATIVE_LOCKMODE ) ) { applyLockModeHint( value ); return true; } return false; } } protected void applyLockTimeoutHint(Integer timeout) { if ( timeout != null ) { applyLockTimeoutHint( (int) timeout ); } } private LockOptions getLockOptions() { return getQueryOptions().getLockOptions(); } protected void applyLockTimeoutHint(int timeout) { getLockOptions().setTimeOut( timeout ); } protected void applyHibernateLockMode(LockMode value) { getLockOptions().setLockMode( value ); } protected void applyLockModeType(LockModeType value) { applyHibernateLockMode( LockMode.fromJpaLockMode( value ) ); } protected final void applyLockModeHint(Object value) { if ( value instanceof LockMode lockMode ) { applyHibernateLockMode( lockMode ); } else if ( value instanceof LockModeType lockModeType ) { applyLockModeType( lockModeType ); } else if ( value instanceof String string ) { applyHibernateLockMode( LockMode.fromExternalForm( string ) ); } else { throw new IllegalArgumentException( String.format( "Native lock-mode hint [%s] must specify %s or %s. Encountered type: %s", HINT_NATIVE_LOCKMODE, LockMode.class.getName(), LockModeType.class.getName(), value.getClass().getName() ) ); } } protected void applyFollowOnStrategyHint(Locking.FollowOn followOnStrategy) { getLockOptions().setFollowOnStrategy( followOnStrategy ); } protected void applyFollowOnLockingHint(Boolean followOnLocking) { DEPRECATION_LOGGER.deprecatedHint( HINT_FOLLOW_ON_LOCKING, HINT_FOLLOW_ON_STRATEGY ); applyFollowOnStrategyHint( Locking.FollowOn.fromLegacyValue( followOnLocking ) ); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Options public String getComment() { return getQueryOptions().getComment(); } public CommonQueryContract setComment(String comment) { getQueryOptions().setComment( comment ); return this; } @Override public FlushMode getHibernateFlushMode() { final FlushMode flushMode = getQueryOptions().getFlushMode(); return flushMode == null ? getSession().getHibernateFlushMode() : flushMode; } @Override public CommonQueryContract setHibernateFlushMode(FlushMode flushMode) { getQueryOptions().setFlushMode( flushMode ); return this; } @Override public QueryFlushMode getQueryFlushMode() { return FlushModeTypeHelper.getForcedFlushMode( getQueryOptions().getFlushMode() ); } @Override public CommonQueryContract setQueryFlushMode(QueryFlushMode queryFlushMode) { getQueryOptions().setFlushMode( FlushModeTypeHelper.getFlushMode(queryFlushMode) ); return this; } protected void applyTimeoutHint(int timeout) { setTimeout( timeout ); } protected void applyCommentHint(String comment) { setComment( comment ); } protected void applyFlushModeHint(FlushMode flushMode) { setHibernateFlushMode( flushMode ); } protected void applyDatabaseHint(String hint) { getQueryOptions().addDatabaseHint( hint ); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Options public MutableQueryOptions getQueryOptions() { return queryOptions; } @Override public Integer getTimeout() { return getQueryOptions().getTimeout(); } @Override public CommonQueryContract setTimeout(int timeout) { getQueryOptions().setTimeout( timeout ); return this; } private void getCheckOpen() { getSession().checkOpen(); } private void checkOpenNoRollback() { getSession().checkOpen( false ); } public int getMaxResults() { getCheckOpen(); return getQueryOptions().getLimit().getMaxRowsJpa(); } public int getFirstResult() { getCheckOpen(); return getQueryOptions().getLimit().getFirstRowJpa(); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Parameter handling @Override public abstract ParameterMetadataImplementor getParameterMetadata(); @SuppressWarnings({"unchecked", "rawtypes"}) public Set<Parameter<?>> getParameters() { checkOpenNoRollback(); return (Set) getParameterMetadata().getRegistrations(); } public QueryParameterImplementor<?> getParameter(String name) { checkOpenNoRollback(); try { return getParameterMetadata().getQueryParameter( name ); } catch ( HibernateException e ) { throw getExceptionConverter().convert( e ); } } @SuppressWarnings("unchecked") public <T> QueryParameterImplementor<T> getParameter(String name, Class<T> type) { checkOpenNoRollback(); try { //noinspection rawtypes final QueryParameterImplementor parameter = getParameterMetadata().getQueryParameter( name ); if ( !type.isAssignableFrom( parameter.getParameterType() ) ) { throw new IllegalArgumentException( "The type [" + parameter.getParameterType().getName() + "] associated with the parameter corresponding to name [" + name + "] is not assignable to requested Java type [" + type.getName() + "]" ); } return parameter; } catch ( HibernateException e ) { throw getExceptionConverter().convert( e ); } } public QueryParameterImplementor<?> getParameter(int position) { checkOpenNoRollback(); try { return getParameterMetadata().getQueryParameter( position ); } catch ( HibernateException e ) { throw getExceptionConverter().convert( e ); } } @SuppressWarnings( {"unchecked", "rawtypes"} ) public <T> QueryParameterImplementor<T> getParameter(int position, Class<T> type) { checkOpenNoRollback(); try { final QueryParameterImplementor parameter = getParameterMetadata().getQueryParameter( position ); if ( !type.isAssignableFrom( parameter.getParameterType() ) ) { throw new IllegalArgumentException( "The type [" + parameter.getParameterType().getName() + "] associated with the parameter corresponding to position [" + position + "] is not assignable to requested Java type [" + type.getName() + "]" ); } return parameter; } catch ( HibernateException e ) { throw getExceptionConverter().convert( e ); } } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Parameter binding handling @Internal // Made public to work around this bug: https://bugs.openjdk.org/browse/JDK-8340443 public abstract QueryParameterBindings getQueryParameterBindings(); protected abstract boolean resolveJdbcParameterTypeIfNecessary(); private <P> JavaType<P> getJavaType(Class<P> javaType) { return getTypeConfiguration().getJavaTypeRegistry() .resolveDescriptor( javaType ); } protected <P> QueryParameterBinding<P> locateBinding(Parameter<P> parameter) { if ( parameter instanceof QueryParameterImplementor<P> parameterImplementor ) { return locateBinding( parameterImplementor ); } else if ( parameter.getName() != null ) { return locateBinding( parameter.getName() ); } else if ( parameter.getPosition() != null ) { return locateBinding( parameter.getPosition() ); } throw getExceptionConverter().convert( new IllegalArgumentException( "Could not resolve binding for given parameter reference [" + parameter + "]" ) ); } protected <P> QueryParameterBinding<P> locateBinding(QueryParameterImplementor<P> parameter) { getCheckOpen(); return getQueryParameterBindings().getBinding( getQueryParameter( parameter ) ); } protected <P> QueryParameterBinding<P> locateBinding(String name) { getCheckOpen(); return getQueryParameterBindings().getBinding( name ); } protected <P> QueryParameterBinding<P> locateBinding(int position) { getCheckOpen(); return getQueryParameterBindings().getBinding( position ); } protected <P> QueryParameterImplementor<P> getQueryParameter(QueryParameterImplementor<P> parameter) { return parameter; } public boolean isBound(Parameter<?> param) { getCheckOpen(); final var parameter = getParameterMetadata().resolve( param ); return parameter != null && getQueryParameterBindings().isBound( getQueryParameter( parameter ) ); } public <T> T getParameterValue(Parameter<T> param) { checkOpenNoRollback(); final var parameter = getParameterMetadata().resolve( param ); if ( parameter == null ) { throw new IllegalArgumentException( "The parameter [" + param + "] is not part of this Query" ); } final var binding = getQueryParameterBindings().getBinding( getQueryParameter( parameter ) ); if ( binding == null || !binding.isBound() ) { throw new IllegalStateException( "Parameter value not yet bound : " + param.toString() ); } if ( binding.isMultiValued() ) { //noinspection unchecked return (T) binding.getBindValues(); } else { return binding.getBindValue(); } } public Object getParameterValue(String name) { checkOpenNoRollback(); final QueryParameterBinding<?> binding = getQueryParameterBindings().getBinding( name ); if ( !binding.isBound() ) { throw new IllegalStateException( "The parameter [" + name + "] has not yet been bound" ); } if ( binding.isMultiValued() ) { return binding.getBindValues(); } else { return binding.getBindValue(); } } public Object getParameterValue(int position) { checkOpenNoRollback(); final QueryParameterBinding<?> binding = getQueryParameterBindings().getBinding( position ); if ( !binding.isBound() ) { throw new IllegalStateException( "The parameter [" + position + "] has not yet been bound" ); } return binding.isMultiValued() ? binding.getBindValues() : binding.getBindValue(); } @Override public CommonQueryContract setParameter(String name, Object value) { checkOpenNoRollback(); if ( value instanceof TypedParameterValue<?> typedParameterValue ) { setTypedParameter( name, typedParameterValue ); } else { final QueryParameterBinding<Object> binding = getQueryParameterBindings().getBinding( name ); if ( multipleBinding( binding.getQueryParameter(), value ) && value instanceof Collection<?> collectionValue && !isRegisteredAsBasicType( value.getClass() ) ) { return setParameterList( name, collectionValue ); } binding.setBindValue( value, resolveJdbcParameterTypeIfNecessary() ); } return this; } private boolean multipleBinding(QueryParameter<Object> parameter, Object value){ if ( parameter.allowsMultiValuedBinding() ) { final var hibernateType = parameter.getHibernateType(); return hibernateType == null || value == null || isInstance( hibernateType, value ); } else { return false; } } private <T> void setTypedParameter(String name, TypedParameterValue<T> typedValue) { setParameter( name, typedValue.value(), typedValue.type() ); } private <T> void setTypedParameter(int position, TypedParameterValue<T> typedValue) { setParameter( position, typedValue.value(), typedValue.type() ); } private boolean isInstance(Type<?> parameterType, Object value) { final SqmExpressible<?> sqmExpressible = getNodeuilder().resolveExpressible( parameterType ); assert sqmExpressible != null; return sqmExpressible.getExpressibleJavaType().isInstance( value ); } private NodeBuilder getNodeuilder() { return getSessionFactory().getQueryEngine().getCriteriaBuilder(); } @Override public <P> CommonQueryContract setParameter(String name, P value, Class<P> javaType) { final var javaDescriptor = getJavaType( javaType ); if ( javaDescriptor == null ) { setParameter( name, value ); } else { setParameter( name, value, getParamType( javaType ) ); } return this; } @Override public <P> CommonQueryContract setParameter(String name, P value, Type<P> type) { this.<P>locateBinding( name ).setBindValue( value, (BindableType<P>) type ); return this; } @Override @Deprecated(since = "7") public CommonQueryContract setParameter(String name, Instant value, TemporalType temporalType) { this.locateBinding( name ).setBindValue( value, temporalType ); return this; } @Override public CommonQueryContract setParameter(int position, Object value) { checkOpenNoRollback(); if ( value instanceof TypedParameterValue<?> typedParameterValue ) { setTypedParameter( position, typedParameterValue ); } else { final QueryParameterBinding<Object> binding = getQueryParameterBindings().getBinding( position ); if ( multipleBinding( binding.getQueryParameter(), value ) && value instanceof Collection<?> collectionValue && !isRegisteredAsBasicType( value.getClass() ) ) { return setParameterList( position, collectionValue ); } binding.setBindValue( value, resolveJdbcParameterTypeIfNecessary() ); } return this; } private boolean isRegisteredAsBasicType(Class<?> valueClass) { return getTypeConfiguration().getBasicTypeForJavaType( valueClass ) != null; } @Override public <P> CommonQueryContract setParameter(int position, P value, Class<P> javaType) { final var javaDescriptor = getJavaType( javaType ); if ( javaDescriptor == null ) { setParameter( position, value ); } else { setParameter( position, value, getParamType( javaType ) ); } return this; } @Override public <P> CommonQueryContract setParameter(int position, P value, Type<P> type) { this.<P>locateBinding( position ).setBindValue( value, (BindableType<P>) type ); return this; } @Override @Deprecated(since = "7") public CommonQueryContract setParameter(int position, Instant value, TemporalType temporalType) { this.locateBinding( position ).setBindValue( value, temporalType ); return this; } @Override public <P> CommonQueryContract setParameter(QueryParameter<P> parameter, P value) { locateBinding( parameter ).setBindValue( value, resolveJdbcParameterTypeIfNecessary() ); return this; } @Override public <P> CommonQueryContract setParameter(QueryParameter<P> parameter, P value, Class<P> javaType) { final var javaDescriptor = getJavaType( javaType ); if ( javaDescriptor == null ) { setParameter( parameter, value ); } else { setParameter( parameter, value, getParamType( javaType ) ); } return this; } @Override public <P> CommonQueryContract setParameter(QueryParameter<P> parameter, P value, Type<P> type) { locateBinding( parameter ).setBindValue( value, (BindableType<P>) type ); return this; } @Override public <P> CommonQueryContract setParameter(Parameter<P> parameter, P value) { if ( value instanceof TypedParameterValue<?> typedParameterValue ) { final var parameterType = parameter.getParameterType(); final var type = typedParameterValue.type(); if ( type == null ) { throw new IllegalArgumentException( "TypedParameterValue has no type" ); } if ( !parameterType.isAssignableFrom( type.getJavaType() ) ) { throw new QueryArgumentException( "Given TypedParameterValue is not assignable to given Parameter type", parameterType, typedParameterValue.value() ); } @SuppressWarnings("unchecked") // safe, because we just checked final var typedValue = (TypedParameterValue<P>) value; setParameter( parameter, typedValue.value(), typedValue.type() ); } else { locateBinding( parameter ).setBindValue( value, resolveJdbcParameterTypeIfNecessary() ); } return this; } private <P> void setParameter(Parameter<P> parameter, P value, Type<P> type) { if ( parameter instanceof QueryParameter<P> queryParameter ) { setParameter( queryParameter, value, type ); } else if ( value == null ) { locateBinding( parameter ).setBindValue( null, (BindableType<P>) type ); } else if ( value instanceof Collection ) { //TODO: this looks wrong to me: how can value be both a P and a (Collection<P>)? locateBinding( parameter ).setBindValues( (Collection<P>) value ); } else { locateBinding( parameter ).setBindValue( value, (BindableType<P>) type ); } } @Override @Deprecated public CommonQueryContract setParameter(Parameter<Calendar> param, Calendar value, TemporalType temporalType) { locateBinding( param ).setBindValue( value, temporalType ); return this; } @Override @Deprecated public CommonQueryContract setParameter(Parameter<Date> param, Date value, TemporalType temporalType) { locateBinding( param ).setBindValue( value, temporalType ); return this; } @Override @Deprecated public CommonQueryContract setParameter(String name, Calendar value, TemporalType temporalType) { locateBinding( name ).setBindValue( value, temporalType ); return this; } @Override @Deprecated public CommonQueryContract setParameter(String name, Date value, TemporalType temporalType) { locateBinding( name ).setBindValue( value, temporalType ); return this; } @Override @Deprecated public CommonQueryContract setParameter(int position, Calendar value, TemporalType temporalType) { locateBinding( position ).setBindValue( value, temporalType ); return this; } @Override @Deprecated public CommonQueryContract setParameter(int position, Date value, TemporalType temporalType) { locateBinding( position ).setBindValue( value, temporalType ); return this; } @Override public CommonQueryContract setParameterList(String name, @SuppressWarnings("rawtypes") Collection values) { locateBinding( name ).setBindValues( values ); return this; } public <P> CommonQueryContract setParameterList(String name, Collection<? extends P> values, Class<P> javaType) { final JavaType<P> javaDescriptor = getJavaType( javaType ); if ( javaDescriptor == null ) { setParameterList( name, values ); } else { setParameterList( name, values, getParamType( javaType ) ); } return this; } @Override public <P> CommonQueryContract setParameterList(String name, Collection<? extends P> values, Type<P> type) { this.<P>locateBinding( name ).setBindValues( values, (BindableType<P>) type ); return this; } @Override public CommonQueryContract setParameterList(String name, Object[] values) { locateBinding( name ).setBindValues( asList( values ) ); return this; } @Override public <P> CommonQueryContract setParameterList(String name, P[] values, Class<P> javaType) { final var javaDescriptor = getJavaType( javaType ); if ( javaDescriptor == null ) { setParameterList( name, values ); } else { setParameterList( name, values, getParamType( javaType ) ); } return this; } public <P> CommonQueryContract setParameterList(String name, P[] values, Type<P> type) { this.<P>locateBinding( name ).setBindValues( asList( values ), (BindableType<P>) type ); return this; } @Override public CommonQueryContract setParameterList(int position, @SuppressWarnings("rawtypes") Collection values) { locateBinding( position ).setBindValues( values ); return this; } @Override public <P> CommonQueryContract setParameterList(int position, Collection<? extends P> values, Class<P> javaType) { final var javaDescriptor = getJavaType( javaType ); if ( javaDescriptor == null ) { setParameterList( position, values ); } else { setParameterList( position, values, getParamType( javaType ) ); } return this; } private <P> Type<P> getParamType(Class<P> javaType) { final var basicType = getTypeConfiguration() .standardBasicTypeForJavaType( javaType ); if ( basicType != null ) { return basicType; } else { final var managedDomainType = getSessionFactory().getJpaMetamodel() .managedType( javaType ); if ( managedDomainType != null ) { return managedDomainType; } else { throw new HibernateException( "Unable to determine Type: " + javaType.getName() ); } } } @Override public <P> CommonQueryContract setParameterList(int position, Collection<? extends P> values, Type<P> type) { this.<P>locateBinding( position ).setBindValues( values, (BindableType<P>) type ); return this; } @Override public CommonQueryContract setParameterList(int position, Object[] values) { locateBinding( position ).setBindValues( asList( values ) ); return this; } @Override public <P> CommonQueryContract setParameterList(int position, P[] values, Class<P> javaType) { final var javaDescriptor = getJavaType( javaType ); if ( javaDescriptor == null ) { setParameterList( position, values ); } else { setParameterList( position, values, getParamType( javaType ) ); } return this; } @SuppressWarnings({ "unchecked", "rawtypes" }) public <P> CommonQueryContract setParameterList(int position, P[] values, Type<P> type) { locateBinding( position ).setBindValues( asList( values ), (BindableType) type ); return this; } @Override public <P> CommonQueryContract setParameterList(QueryParameter<P> parameter, Collection<? extends P> values) { locateBinding( parameter ).setBindValues( values ); return this; } @Override public <P> CommonQueryContract setParameterList(QueryParameter<P> parameter, Collection<? extends P> values, Class<P> javaType) { final var javaDescriptor = getJavaType( javaType ); if ( javaDescriptor == null ) { setParameterList( parameter, values ); } else { setParameterList( parameter, values, getParamType( javaType ) ); } return this; } @Override public <P> CommonQueryContract setParameterList(QueryParameter<P> parameter, Collection<? extends P> values, Type<P> type) { locateBinding( parameter ).setBindValues( values, (BindableType<P>) type ); return this; } @Override public <P> CommonQueryContract setParameterList(QueryParameter<P> parameter, P[] values) { locateBinding( parameter ).setBindValues( values == null ? null : asList( values ) ); return this; } @Override public <P> CommonQueryContract setParameterList(QueryParameter<P> parameter, P[] values, Class<P> javaType) { final var javaDescriptor = getJavaType( javaType ); if ( javaDescriptor == null ) { setParameterList( parameter, values ); } else { setParameterList( parameter, values, getParamType( javaType ) ); } return this; } @Override public <P> CommonQueryContract setParameterList(QueryParameter<P> parameter, P[] values, Type<P> type) { locateBinding( parameter ).setBindValues( asList( values ), (BindableType<P>) type ); return this; } @Override public CommonQueryContract setProperties(@SuppressWarnings("rawtypes") Map map) { for ( String paramName : getParameterMetadata().getNamedParameterNames() ) { final Object object = map.get( paramName ); if ( object == null ) { if ( map.containsKey( paramName ) ) { setParameter( paramName, null, determineType( paramName, null ) ); } } else { if ( object instanceof Collection<?> collection ) { setParameterList( paramName, collection ); } else if ( object instanceof Object[] array ) { setParameterList( paramName, array ); } else { setParameter( paramName, object, determineType( paramName, object.getClass() ) ); } } } return this; } protected <T> Type<T> determineType(String namedParam, Class<? extends T> retType) { BindableType<?> type = locateBinding( namedParam ).getBindType(); if ( type == null ) { type = getParameterMetadata().getQueryParameter( namedParam ).getHibernateType(); } if ( type == null && retType != null ) { type = getSessionFactory().getMappingMetamodel().resolveParameterBindType( retType ); } if ( retType!= null && !retType.isAssignableFrom( type.getJavaType() ) ) { throw new IllegalStateException( "Parameter not of expected type: " + retType.getName() ); } //noinspection unchecked return (Type<T>) type; } @Override public CommonQueryContract setProperties(Object bean) { final var beanClass = bean.getClass(); for ( String paramName : getParameterMetadata().getNamedParameterNames() ) { try { final var getter = BuiltInPropertyAccessStrategies.BASIC.getStrategy() .buildPropertyAccess( beanClass, paramName, true ) .getGetter(); final var returnType = getter.getReturnTypeClass(); final Object object = getter.get( bean ); if ( Collection.class.isAssignableFrom( returnType ) ) { setParameterList( paramName, (Collection<?>) object ); } else if ( returnType.isArray() ) { setParameterList( paramName, (Object[]) object ); } else { setParameter( paramName, object, determineType( paramName, returnType ) ); } } catch (PropertyNotFoundException pnfe) { // ignore } } return this; } }
name
java
apache__camel
components/camel-ibm/camel-ibm-secrets-manager/src/main/java/org/apache/camel/component/ibm/secrets/manager/IBMSecretsManagerConstants.java
{ "start": 912, "end": 2591 }
class ____ { private static final String HEADER_PREFIX = "CamelIbmSecretsManager"; // headers set by the producer only @Metadata(label = "producer", description = "Overrides the desired operation to be used in the producer.", javaType = "String") public static final String OPERATION = HEADER_PREFIX + "ProducerOperation"; // headers set by the producer only @Metadata(label = "producer", description = "Set the desired secret path as header.", javaType = "String") public static final String SECRET_NAME = HEADER_PREFIX + "SecretName"; // headers set by the producer only @Metadata(label = "producer", description = "Set the desired secret version as header.", javaType = "String") public static final String SECRET_VERSION = HEADER_PREFIX + "SecretVersion"; // headers set by the producer only @Metadata(label = "producer", description = "Set the desired secret version as header.", javaType = "String") public static final String SECRET_ID = HEADER_PREFIX + "SecretId"; // headers set by the producer only @Metadata(label = "producer", description = "Set the secret payload for update operation.", javaType = "String") public static final String SECRET_PAYLOAD = HEADER_PREFIX + "SecretPayload"; // headers set by the producer only @Metadata(label = "producer", description = "Set the secret data (Map) for KV secret update operation.", javaType = "java.util.Map") public static final String SECRET_DATA = HEADER_PREFIX + "SecretData"; private IBMSecretsManagerConstants() { } }
IBMSecretsManagerConstants
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/multidb/MultiDbTest.java
{ "start": 1092, "end": 3401 }
class ____ { protected static SqlSessionFactory sqlSessionFactory; protected static SqlSessionFactory sqlSessionFactory2; @BeforeAll static void setUp() throws Exception { try (Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/multidb/MultiDbConfig.xml")) { sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), "org/apache/ibatis/submitted/multidb/CreateDB.sql"); } @Test void shouldExecuteHsqlQuery() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { MultiDbMapper mapper = sqlSession.getMapper(MultiDbMapper.class); String answer = mapper.select1(1); assertEquals("hsql", answer); } } @Test void shouldExecuteCommonQuery() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { MultiDbMapper mapper = sqlSession.getMapper(MultiDbMapper.class); String answer = mapper.select2(1); assertEquals("common", answer); } } @Test void shouldExecuteHsqlQueryWithDynamicIf() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { MultiDbMapper mapper = sqlSession.getMapper(MultiDbMapper.class); String answer = mapper.select3(1); assertEquals("hsql", answer); } } @Test void shouldExecuteHsqlQueryWithInclude() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { MultiDbMapper mapper = sqlSession.getMapper(MultiDbMapper.class); String answer = mapper.select4(1); assertEquals("hsql", answer); } } @Test void shouldInsertInCommonWithSelectKey() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { MultiDbMapper mapper = sqlSession.getMapper(MultiDbMapper.class); mapper.insert(new User(2, "test")); String answer = mapper.select2(1); assertEquals("common", answer); } } @Test void shouldInsertInCommonWithSelectKey2() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { MultiDbMapper mapper = sqlSession.getMapper(MultiDbMapper.class); mapper.insert2(new User(2, "test")); String answer = mapper.select2(1); assertEquals("common", answer); } } }
MultiDbTest
java
quarkusio__quarkus
independent-projects/tools/codestarts/src/main/java/io/quarkus/devtools/codestarts/core/reader/QuteCodestartFileReader.java
{ "start": 953, "end": 4500 }
class ____ implements CodestartFileReader { private static final String TPL_QUTE_FLAG = ".tpl.qute"; private static final String ENTRY_QUTE_FLAG = ".entry.qute"; public static final String INCLUDE_QUTE_FLAG = ".include.qute"; public static final String SKIP_TAG = "<SKIP>"; private static final Pattern VERSION_PATTERN = Pattern.compile("^(\\d+)(\\.(\\d+))?(\\.(\\d+))?"); @Override public boolean matches(String fileName) { return fileName.contains(TPL_QUTE_FLAG) || fileName.contains(ENTRY_QUTE_FLAG) || fileName.contains(INCLUDE_QUTE_FLAG); } @Override public String cleanFileName(String fileName) { return fileName .replaceAll(TPL_QUTE_FLAG, "") .replace(ENTRY_QUTE_FLAG, ""); } @Override public Optional<String> read(CodestartResource projectResource, Source source, String languageName, Map<String, Object> data) throws IOException { if (FilenameUtils.getName(source.path()).contains(INCLUDE_QUTE_FLAG)) { return Optional.empty(); } final String value = readQuteFile(projectResource, source, languageName, data); if (SKIP_TAG.equals(value)) { return Optional.empty(); } return Optional.of(value); } public static String readQuteFile(CodestartResource projectResource, Source source, String languageName, Map<String, Object> data) { final String content = source.read(); final String templateId = source.absolutePath(); final Engine engine = Engine.builder().addDefaults() .addValueResolver(new StringValueResolver()) .addResultMapper(new MissingValueMapper()) .removeStandaloneLines(true) // For now we need to disable strict rendering for codestarts // A param of an {#if} section is not considered falsy if the value represents a "not found" result // https://github.com/quarkusio/quarkus/pull/18227#discussion_r662301281 .strictRendering(false) .addLocator( id -> findIncludeTemplate(source.getCodestartResource(), languageName, id) .map(IncludeTemplateLocation::new)) .addLocator( id -> findIncludeTemplate(projectResource, languageName, id) .map(IncludeTemplateLocation::new)) .addLocator(id -> Optional.of(new FallbackTemplateLocation())) .build(); try { return engine.parse(content, null, templateId).render(data); } catch (Exception e) { throw new CodestartException("Error while rendering template: " + source.absolutePath(), e); } } private static Optional<Source> findIncludeTemplate(CodestartResource projectResource, String languageName, String name) { final String includeFileName = name + INCLUDE_QUTE_FLAG; final Optional<Source> languageIncludeSource = projectResource.getSource(languageName, includeFileName); if (languageIncludeSource.isPresent()) { return languageIncludeSource; } final Optional<Source> baseIncludeSource = projectResource.getSource("base", includeFileName); if (baseIncludeSource.isPresent()) { return baseIncludeSource; } return Optional.empty(); } private static
QuteCodestartFileReader
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/TaskMetadata.java
{ "start": 1043, "end": 2744 }
interface ____ { /** * Task ID of the task. * * @return task ID consisting of subtopology and partition ID */ TaskId taskId(); /** * Source topic partitions of the task. * * @return source topic partitions */ Set<TopicPartition> topicPartitions(); /** * Offsets of the source topic partitions committed so far by the task. * * @return map from source topic partitions to committed offsets */ Map<TopicPartition, Long> committedOffsets(); /** * End offsets of the source topic partitions of the task. * * @return map source topic partition to end offsets */ Map<TopicPartition, Long> endOffsets(); /** * Time task idling started. If the task is not currently idling it will return empty. * * @return time when task idling started, empty {@code Optional} if the task is currently not idling */ Optional<Long> timeCurrentIdlingStarted(); /** * Compares the specified object with this TaskMetadata. Returns {@code true} if and only if the specified object is * also a TaskMetadata and both {@code taskId()} and {@code topicPartitions()} are equal. * * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. */ boolean equals(final Object o); /** * Returns the hash code value for this TaskMetadata. The hash code of a list is defined to be the result of the following calculation: * <pre> * {@code * Objects.hash(taskId(), topicPartitions()); * } * </pre> * * @return a hash code value for this object. */ int hashCode(); }
TaskMetadata
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/annotation/AnnotatedTypeInfo.java
{ "start": 651, "end": 790 }
interface ____ provides an abstraction for checking for the existence of annotations. * * @author Graeme Rocher * @since 1.0 */ public
that
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_296.java
{ "start": 177, "end": 1051 }
class ____ extends TestCase { public void test_for_issue() throws Exception { String text = "{\"downloadSpeed\":631055,\"responseTime\":1.435,\"url\":\"http://m2.music.126.net/xUqntwOHwpJdXsO_H-kHsw==/5817516022676667.mp3?v=50710699\"}"; JSONObject obj = (JSONObject) JSON.parse(text); Assert.assertEquals(631055, obj.get("downloadSpeed")); } public void test_for_issue_space() throws Exception { String text = "{\"downloadSpeed\":631055} "; JSONObject obj = (JSONObject) JSON.parse(text); Assert.assertEquals(631055, obj.get("downloadSpeed")); } public void test_for_issue_127() throws Exception { String text = "{\"downloadSpeed\":631055}\u007f"; JSONObject obj = (JSONObject) JSON.parse(text); Assert.assertEquals(631055, obj.get("downloadSpeed")); } }
Bug_for_issue_296
java
google__dagger
javatests/dagger/hilt/android/testing/testinstallin/TestInstallInBarTest.java
{ "start": 2069, "end": 2509 }
interface ____ { @Provides static Bar provideBar() { return new Bar(LocalBarTestModule.class); } } @Inject Foo foo; @Inject Bar bar; @Test public void testFoo() { hiltRule.inject(); assertThat(foo.moduleClass).isEqualTo(SingletonFooTestModule.class); } @Test public void testBar() { hiltRule.inject(); assertThat(bar.moduleClass).isEqualTo(LocalBarTestModule.class); } }
LocalBarTestModule
java
apache__camel
components/camel-ldap/src/test/java/org/apache/directory/server/core/integ5/ServerAnnotationProcessor.java
{ "start": 2776, "end": 6988 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(ServerAnnotationProcessor.class); private ServerAnnotationProcessor() { } private static void createTransports(LdapServer ldapServer, CreateTransport[] transportBuilders) { if (transportBuilders.length != 0) { for (CreateTransport transportBuilder : transportBuilders) { List<Transport> transports = createTransports(transportBuilder); for (Transport t : transports) { ldapServer.addTransports(t); } } } else { // Create default LDAP and LDAPS transports try { int port = getFreePort(); Transport ldap = new TcpTransport(port); ldapServer.addTransports(ldap); } catch (IOException ioe) { // Don't know what to do here... } try { int port = getFreePort(); Transport ldaps = new TcpTransport(port); ldaps.setEnableSSL(true); ldapServer.addTransports(ldaps); } catch (IOException ioe) { // Don't know what to do here... } } } /** * Just gives an instance of {@link LdapServer} without starting it. For getting a running LdapServer instance see * {@link #createLdapServer(CreateLdapServer, DirectoryService)} * * @param createLdapServer The LdapServer to create * @param directoryService the directory service * @return The created LdapServer * @see #createLdapServer(CreateLdapServer, DirectoryService) */ public static LdapServer instantiateLdapServer(CreateLdapServer createLdapServer, DirectoryService directoryService) { if (createLdapServer != null) { LdapServer ldapServer = new LdapServer(); ldapServer.setServiceName(createLdapServer.name()); // Read the transports createTransports(ldapServer, createLdapServer.transports()); // Associate the DS to this LdapServer ldapServer.setDirectoryService(directoryService); // Propagate the anonymous flag to the DS directoryService.setAllowAnonymousAccess(createLdapServer.allowAnonymousAccess()); ldapServer.setSaslHost(createLdapServer.saslHost()); ldapServer.setSaslPrincipal(createLdapServer.saslPrincipal()); if (!Strings.isEmpty(createLdapServer.keyStore())) { ldapServer.setKeystoreFile(createLdapServer.keyStore()); ldapServer.setCertificatePassword(createLdapServer.certificatePassword()); } for (Class<?> extOpClass : createLdapServer.extendedOpHandlers()) { try { ExtendedOperationHandler extOpHandler = (ExtendedOperationHandler) extOpClass .getDeclaredConstructor().newInstance(); ldapServer.addExtendedOperationHandler(extOpHandler); } catch (Exception e) { throw new RuntimeCamelException(I18n.err(I18n.ERR_690, extOpClass.getName()), e); } } for (SaslMechanism saslMech : createLdapServer.saslMechanisms()) { try { MechanismHandler handler = (MechanismHandler) saslMech.implClass() .getDeclaredConstructor().newInstance(); ldapServer.addSaslMechanismHandler(saslMech.name(), handler); } catch (Exception e) { throw new RuntimeCamelException( I18n.err(I18n.ERR_691, saslMech.name(), saslMech.implClass().getName()), e); } } NtlmMechanismHandler ntlmHandler = (NtlmMechanismHandler) ldapServer.getSaslMechanismHandlers().get( SupportedSaslMechanisms.NTLM); if (ntlmHandler != null) { Class<?> ntlmProviderClass = createLdapServer.ntlmProvider(); // default value is a invalid Object.
ServerAnnotationProcessor
java
alibaba__nacos
core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcServerTest.java
{ "start": 1982, "end": 4818 }
class ____ { static MockedStatic<ApplicationUtils> applicationUtilsMockedStatic = null; private BaseGrpcServer grpcSdkServer; @BeforeAll static void setUpBeforeClass() { EnvUtil.setEnvironment(new MockEnvironment()); applicationUtilsMockedStatic = Mockito.mockStatic(ApplicationUtils.class); } @AfterAll static void after() { applicationUtilsMockedStatic.close(); } @AfterEach void tearDown() throws Exception { if (null != grpcSdkServer) { grpcSdkServer.stopServer(); } } @Test void testGrpcSdkServer() throws Exception { grpcSdkServer = new GrpcSdkServer(); grpcSdkServer.start(); assertEquals(ConnectionType.GRPC, grpcSdkServer.getConnectionType()); assertEquals(1000, grpcSdkServer.rpcPortOffset()); } @Test void testGrpcClusterServer() throws Exception { grpcSdkServer = new GrpcClusterServer(); grpcSdkServer.start(); assertEquals(ConnectionType.GRPC, grpcSdkServer.getConnectionType()); assertEquals(1001, grpcSdkServer.rpcPortOffset()); grpcSdkServer.stopServer(); } @Test public void testGrpcSdkServerSourceCheck() throws Exception { grpcSdkServer = new GrpcSdkServer(); RequestHandlerRegistry mock = Mockito.mock(RequestHandlerRegistry.class); Field field = ReflectionUtils.findField(GrpcSdkServer.class, "requestHandlerRegistry"); field.setAccessible(true); ReflectionUtils.setField(field, grpcSdkServer, mock); GrpcRequestAcceptor mockAcceptor = Mockito.mock(GrpcRequestAcceptor.class); Field fieldGrpcAcceptor = ReflectionUtils.findField(GrpcSdkServer.class, "grpcCommonRequestAcceptor"); fieldGrpcAcceptor.setAccessible(true); ReflectionUtils.setField(fieldGrpcAcceptor, grpcSdkServer, mockAcceptor); StreamObserver streamObserverMock = Mockito.mock(StreamObserver.class); Payload convert = GrpcUtils.convert(new ConfigChangeClusterSyncRequest()); //verify not allowed Mockito.when(mock.checkSourceInvokeAllowed(ConfigChangeClusterSyncRequest.class.getSimpleName(), grpcSdkServer.getSource())).thenReturn(false); grpcSdkServer.handleCommonRequest(convert, streamObserverMock); Mockito.verify(streamObserverMock, Mockito.times(1)).onCompleted(); //verify allowed Mockito.when(mock.checkSourceInvokeAllowed(ConfigChangeClusterSyncRequest.class.getSimpleName(), grpcSdkServer.getSource())).thenReturn(true); grpcSdkServer.handleCommonRequest(convert, streamObserverMock); Mockito.verify(mockAcceptor, Mockito.times(1)).request(eq(convert), eq(streamObserverMock)); } }
GrpcServerTest
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/sql_load_script/FileNotFoundSqlLoadScriptTestCase.java
{ "start": 399, "end": 1277 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(MyEntity.class)) .withConfigurationResource("application.properties") .overrideConfigKey("quarkus.hibernate-orm.sql-load-script", "file-that-does-not-exist.sql") .assertException(t -> assertThat(t) .isInstanceOf(ConfigurationException.class) .hasMessageContainingAll("Unable to find file referenced in '" + "quarkus.hibernate-orm.sql-load-script=file-that-does-not-exist.sql'. Remove property or add file to your path.")); @Test public void testSqlLoadScriptFileAbsentTest() { // deployment exception should happen first Assertions.fail(); } }
FileNotFoundSqlLoadScriptTestCase
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_hasHour_Test.java
{ "start": 1062, "end": 1953 }
class ____ { @Test void should_pass_if_actual_is_in_given_hour() { // GIVEN LocalDateTime actual = LocalDateTime.of(2021, 12, 31, 23, 59, 59); // WHEN/THEN then(actual).hasHour(23); } @Test void should_fail_if_actual_is_not_in_given_hour() { // GIVEN LocalDateTime actual = LocalDateTime.of(2021, 12, 31, 23, 59, 59); int expectedHour = 22; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).hasHour(expectedHour)); // THEN then(assertionError).hasMessage(shouldHaveDateField(actual, "hour", expectedHour).create()); } @Test void should_fail_if_actual_is_null() { // GIVEN LocalDateTime actual = null; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).hasHour(1)); // THEN then(assertionError).hasMessage(actualIsNull()); } }
LocalDateTimeAssert_hasHour_Test
java
apache__camel
components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/events/KubernetesEventsConsumer.java
{ "start": 3153, "end": 6242 }
class ____ implements Runnable { private Watch watch; @Override public void run() { FilterWatchListDeletable<Event, EventList, Resource<Event>> w; /* Valid options are (according to how the client can be constructed): - inAnyNamespace - inAnyNamespace + withLabel - inNamespace - inNamespace + withLabel - inNamespace + withName */ String namespace = getEndpoint().getKubernetesConfiguration().getNamespace(); String labelKey = getEndpoint().getKubernetesConfiguration().getLabelKey(); String labelValue = getEndpoint().getKubernetesConfiguration().getLabelValue(); String resourceName = getEndpoint().getKubernetesConfiguration().getResourceName(); if (ObjectHelper.isEmpty(namespace)) { w = getEndpoint().getKubernetesClient().events().v1().events().inAnyNamespace(); if (ObjectHelper.isNotEmpty(labelKey) && ObjectHelper.isNotEmpty(labelValue)) { w = w.withLabel(labelKey, labelValue); } } else { final NonNamespaceOperation<Event, EventList, Resource<Event>> client = getEndpoint().getKubernetesClient().events().v1().events().inNamespace(namespace); w = client; if (ObjectHelper.isNotEmpty(labelKey) && ObjectHelper.isNotEmpty(labelValue)) { w = client.withLabel(labelKey, labelValue); } else if (ObjectHelper.isNotEmpty(resourceName)) { w = (FilterWatchListDeletable<Event, EventList, Resource<Event>>) client.withName(resourceName); } } watch = w.watch(new Watcher<>() { @Override public void eventReceived(Action action, Event resource) { Exchange exchange = createExchange(false); exchange.getIn().setBody(resource); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION, action); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENT_TIMESTAMP, System.currentTimeMillis()); try { processor.process(exchange); } catch (Exception e) { getExceptionHandler().handleException("Error during processing", exchange, e); } finally { releaseExchange(exchange, false); } } @Override public void onClose(WatcherException cause) { if (cause != null) { LOG.error(cause.getMessage(), cause); } } }); } public Watch getWatch() { return watch; } public void setWatch(Watch watch) { this.watch = watch; } } }
EventsConsumerTask
java
netty__netty
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2PingFrame.java
{ "start": 713, "end": 948 }
interface ____ extends Http2Frame { /** * When {@code true}, indicates that this ping is a ping response. */ boolean ack(); /** * Returns the eight byte opaque data. */ long content(); }
Http2PingFrame
java
grpc__grpc-java
examples/src/main/java/io/grpc/examples/cancellation/CancellationServer.java
{ "start": 2122, "end": 3026 }
class ____ { public static void main(String[] args) throws IOException, InterruptedException { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); int port = 50051; Server server = Grpc.newServerBuilderForPort(port, InsecureServerCredentials.create()) .addService(new SlowEcho(scheduler)) .build() .start(); System.out.println("Server started, listening on " + port); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { server.shutdown().awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(System.err); } } }); server.awaitTermination(); scheduler.shutdown(); if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) { scheduler.shutdownNow(); } } static
CancellationServer
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/internal/TypeHolder.java
{ "start": 3458, "end": 3624 }
class ____ {@code clazz}, * We check if there is a registered entity for a superclass of {@code otherClazz} * 5. We check if there is a registered entity for an
for
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/blink/parser/BlinkCreateTableParser.java
{ "start": 1232, "end": 4944 }
class ____ extends SQLCreateTableParser { public BlinkCreateTableParser(String sql) { super(new BlinkExprParser(sql)); } public BlinkCreateTableParser(SQLExprParser exprParser) { super(exprParser); } public SQLCreateTableStatement parseCreateTable() { BlinkCreateTableStatement stmt = new BlinkCreateTableStatement(); accept(Token.CREATE); if (lexer.nextIfIdentifier(FnvHash.Constants.EXTERNAL)) { stmt.setExternal(true); } accept(Token.TABLE); if (lexer.token() == Token.IF || lexer.identifierEquals("IF")) { lexer.nextToken(); accept(Token.NOT); accept(Token.EXISTS); stmt.setIfNotExists(true); } stmt.setName(this.exprParser.name()); accept(Token.LPAREN); if (lexer.isKeepComments() && lexer.hasComment()) { stmt.addBodyBeforeComment(lexer.readAndResetComments()); } for_: for (; ; ) { SQLColumnDefinition column = null; switch (lexer.token()) { case IDENTIFIER: case KEY: column = this.exprParser.parseColumn(); column.setParent(stmt); stmt.getTableElementList().add(column); break; case PRIMARY: SQLTableConstraint constraint = this.parseConstraint(); constraint.setParent(stmt); stmt.getTableElementList().add(constraint); break; case PERIOD: lexer.nextToken(); accept(Token.FOR); SQLExpr periodFor = this.exprParser.primary(); stmt.setPeriodFor(periodFor); break for_; default: throw new ParserException("expect identifier. " + lexer.info()); } // } else if (lexer.token() == Token.CONSTRAINT // // || lexer.token() == Token.PRIMARY // // || lexer.token() == Token.UNIQUE) { // SQLTableConstraint constraint = this.parseConstraint(); // constraint.setParent(stmt); // stmt.getTableElementList().add(constraint); // } if (lexer.isKeepComments() && lexer.hasComment() && column != null) { column.addAfterComment(lexer.readAndResetComments()); } if (!(lexer.token() == (Token.COMMA))) { break; } else { lexer.nextToken(); if (lexer.isKeepComments() && lexer.hasComment() && column != null) { column.addAfterComment(lexer.readAndResetComments()); } } } accept(Token.RPAREN); if (lexer.token() == Token.COMMENT) { lexer.nextToken(); stmt.setComment(this.exprParser.primary()); } if (stmt.getClusteredBy().size() > 0 || stmt.getSortedBy().size() > 0) { accept(Token.INTO); if (lexer.token() == Token.LITERAL_INT) { stmt.setBuckets(lexer.integerValue().intValue()); lexer.nextToken(); } else { throw new ParserException("into buckets must be integer. " + lexer.info()); } acceptIdentifier("BUCKETS"); } if (lexer.token() == Token.WITH) { lexer.nextToken(); accept(Token.LPAREN); parseAssignItems(stmt.getTableOptions(), stmt, true); accept(Token.RPAREN); } return stmt; } }
BlinkCreateTableParser
java
micronaut-projects__micronaut-core
http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/filter/ResponseFilterTest.java
{ "start": 1930, "end": 10802 }
class ____ { public static final String SPEC_NAME = "ResponseFilterTest"; @Test public void responseFilterImmediateRequestParameter() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/immediate-request-parameter")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("foo") .build()); Assertions.assertEquals( List.of("responseFilterImmediateRequestParameter /response-filter/immediate-request-parameter"), server.getApplicationContext().getBean(MyServerFilter.class).events ); }) .run(); } @Test public void responseFilterImmediateMutableRequestParameter() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/immediate-mutable-request-parameter")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("foo") .build()); Assertions.assertEquals( List.of("responseFilterImmediateMutableRequestParameter /response-filter/immediate-mutable-request-parameter"), server.getApplicationContext().getBean(MyServerFilter.class).events ); }) .run(); } @Test public void responseFilterResponseParameter() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/response-parameter")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("foo") .build()); Assertions.assertEquals( List.of("responseFilterResponseParameter foo"), server.getApplicationContext().getBean(MyServerFilter.class).events ); }) .run(); } @Test public void responseFilterMutableResponseParameter() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/mutable-response-parameter")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("responseFilterMutableResponseParameter foo") .build()); }) .run(); } @Test public void responseFilterThrowableParameterNotCalledForControllerError() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/throwable-parameter")) .assertion((server, request) -> { AssertionUtils.assertThrows(server, request, HttpResponseAssertion.builder() .status(HttpStatus.INTERNAL_SERVER_ERROR) .build()); // filter not called, the error is mapped to a response before filters are invoked Assertions.assertEquals( List.of(), server.getApplicationContext().getBean(MyServerFilter.class).events ); }) .run(); } @Test public void responseFilterReplaceResponse() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/replace-response")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("responseFilterReplaceResponse foo") .build()); }) .run(); } @Test public void responseFilterReplaceMutableResponse() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/replace-mutable-response")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("responseFilterReplaceMutableResponse foo") .build()); }) .run(); } @Test public void responseFilterReplaceResponseNull() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/replace-response-null")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("foo") .build()); }) .run(); } @Test public void responseFilterReplaceResponseEmpty() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/replace-response-empty")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("foo") .build()); }) .run(); } @Test public void responseFilterReplacePublisherResponse() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/replace-publisher-response")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("responseFilterReplacePublisherResponse foo") .build()); }) .run(); } @Test public void responseFilterReplaceMonoResponse() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/replace-mono-response")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("responseFilterReplaceMonoResponse foo") .build()); }) .run(); } @Test public void responseFilterReplaceCompletableResponse() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/replace-completable-response")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("responseFilterReplaceCompletableResponse foo") .build()); }) .run(); } @Test public void responseFilterReplaceCompletionResponse() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.GET("/response-filter/replace-completion-response")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("responseFilterReplaceCompletionResponse foo") .build()); }) .run(); } @Test public void responseFilterHeadBody() throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(HttpRequest.HEAD("/response-filter/head-body")) .assertion((server, request) -> { AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .header("X-HEAD-BODY", "foo") .build()); }) .run(); } @ServerFilter @Singleton @Requires(property = "spec.name", value = SPEC_NAME) public static
ResponseFilterTest
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/expressions/ResolvedFieldReference.java
{ "start": 1340, "end": 2134 }
class ____ { private final String name; private final TypeInformation<?> resultType; private final int fieldIndex; public ResolvedFieldReference(String name, TypeInformation<?> resultType, int fieldIndex) { Preconditions.checkArgument(fieldIndex >= 0, "Index of field should be a positive number"); this.name = Preconditions.checkNotNull(name, "Field name must not be null."); this.resultType = Preconditions.checkNotNull(resultType, "Field result type must not be null."); this.fieldIndex = fieldIndex; } public TypeInformation<?> resultType() { return resultType; } public String name() { return name; } public int fieldIndex() { return fieldIndex; } }
ResolvedFieldReference
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/type/DateArrayTest.java
{ "start": 10172, "end": 10689 }
class ____ { @Id private Long id; @Column( name = "the_array" ) private LocalDate[] theArray; public TableWithDateArrays() { } public TableWithDateArrays(Long id, LocalDate[] theArray) { this.id = id; this.theArray = theArray; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public LocalDate[] getTheArray() { return theArray; } public void setTheArray(LocalDate[] theArray) { this.theArray = theArray; } } }
TableWithDateArrays
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/bean/SimpleLanguageBeanFunctionMethodValueWithCommaTest.java
{ "start": 1027, "end": 3464 }
class ____ extends ContextTestSupport { @Test public void testSingle() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:other").expectedMessageCount(0); template.sendBody("direct:single", "Camel"); assertMockEndpointsSatisfied(); } @Test public void testDouble() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:other").expectedMessageCount(0); template.sendBody("direct:double", "Camel"); assertMockEndpointsSatisfied(); } @Test public void testHeader() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:other").expectedMessageCount(0); template.sendBodyAndHeader("direct:header", "Camel", "myHeader", "e,f"); assertMockEndpointsSatisfied(); } @Test public void testCron() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:other").expectedMessageCount(0); template.sendBody("direct:cron", new MyCronBody("SomeID", "0 0 10,11,12 * * ?")); assertMockEndpointsSatisfied(); } @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("foo", new MyBean()); return jndi; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:single").choice().when().simple("${bean:foo?method=bar(${body}, 'a,b')}").to("mock:result") .otherwise().to("mock:other"); from("direct:double").choice().when().simple("${bean:foo?method=bar(${body}, \"a,b\")}").to("mock:result") .otherwise().to("mock:other"); from("direct:header").choice().when().simple("${bean:foo?method=bar(${body}, ${header.myHeader})}") .to("mock:result").otherwise().to("mock:other"); from("direct:cron").choice().when().simple("${bean:foo?method=bar(${body.id}, ${body.cron})}").to("mock:result") .otherwise().to("mock:other"); } }; } public static
SimpleLanguageBeanFunctionMethodValueWithCommaTest