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
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ImplementAssertionWithChainingTest.java
{ "start": 4375, "end": 5369 }
class ____ extends Subject { private final Foo actual; private FooSubject(FailureMetadata metadata, Foo actual) { super(metadata, actual); this.actual = actual; } void doesNotHaveString(String other) { if (actual.string().equals(other)) { failWithActual("expected not to have string", other); } } void doesNotHaveInteger(int other) { if (actual.integer() == other) { failWithActual("expected not to have integer", other); } } void hasBoxedIntegerSameInstance(Integer expected) { if (actual.boxedInteger() != expected) { failWithActual("expected to have boxed integer", expected); } } } private static final
FooSubject
java
eclipse-vertx__vert.x
vertx-core/src/main/java/examples/CompletionStageInteropExamples.java
{ "start": 707, "end": 1706 }
class ____ { public void toCS(Vertx vertx) { Future<String> future = vertx.createDnsClient().lookup("vertx.io"); future.toCompletionStage().whenComplete((ip, err) -> { if (err != null) { System.err.println("Could not resolve vertx.io"); err.printStackTrace(); } else { System.out.println("vertx.io => " + ip); } }); } private Future<String> storeInDb(String key, String value) { return Future.succeededFuture("Yo"); } public void fromCS(Vertx vertx, CompletionStage<String> completionStage) { Future.fromCompletionStage(completionStage, vertx.getOrCreateContext()) .flatMap(str -> { String key = UUID.randomUUID().toString(); return storeInDb(key, str); }) .onSuccess(str -> { System.out.println("We have a result: " + str); }) .onFailure(err -> { System.err.println("We have a problem"); err.printStackTrace(); }); } }
CompletionStageInteropExamples
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlDecoderTests.java
{ "start": 1609, "end": 9116 }
class ____ extends AbstractLeakCheckingTests { private static final String POJO_ROOT = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<pojo>" + "<foo>foofoo</foo>" + "<bar>barbar</bar>" + "</pojo>"; private static final String POJO_CHILD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<root>" + "<pojo>" + "<foo>foo</foo>" + "<bar>bar</bar>" + "</pojo>" + "<pojo>" + "<foo>foofoo</foo>" + "<bar>barbar</bar>" + "</pojo>" + "<root/>"; private static final Map<String, Object> HINTS = Collections.emptyMap(); private final Jaxb2XmlDecoder decoder = new Jaxb2XmlDecoder(); private final XmlEventDecoder xmlEventDecoder = new XmlEventDecoder(); @Test void canDecode() { assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class), MediaType.APPLICATION_XML)).isTrue(); assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class), MediaType.TEXT_XML)).isTrue(); assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class), MediaType.APPLICATION_JSON)).isFalse(); assertThat(this.decoder.canDecode(ResolvableType.forClass(TypePojo.class), MediaType.APPLICATION_XML)).isTrue(); assertThat(this.decoder.canDecode(ResolvableType.forClass(getClass()), MediaType.APPLICATION_XML)).isFalse(); } @Test void splitOneBranches() { Flux<XMLEvent> xmlEvents = this.xmlEventDecoder.decode(toDataBufferMono(POJO_ROOT), null, null, HINTS); Flux<List<XMLEvent>> result = Jaxb2Helper.split(xmlEvents, Set.of(new QName("pojo"))); StepVerifier.create(result) .consumeNextWith(events -> { assertThat(events).hasSize(8); assertStartElement(events.get(0), "pojo"); assertStartElement(events.get(1), "foo"); assertCharacters(events.get(2), "foofoo"); assertEndElement(events.get(3), "foo"); assertStartElement(events.get(4), "bar"); assertCharacters(events.get(5), "barbar"); assertEndElement(events.get(6), "bar"); assertEndElement(events.get(7), "pojo"); }) .expectComplete() .verify(); } @Test void splitMultipleBranches() { Flux<XMLEvent> xmlEvents = this.xmlEventDecoder.decode(toDataBufferMono(POJO_CHILD), null, null, HINTS); Flux<List<XMLEvent>> result = Jaxb2Helper.split(xmlEvents, Set.of(new QName("pojo"))); StepVerifier.create(result) .consumeNextWith(events -> { assertThat(events).hasSize(8); assertStartElement(events.get(0), "pojo"); assertStartElement(events.get(1), "foo"); assertCharacters(events.get(2), "foo"); assertEndElement(events.get(3), "foo"); assertStartElement(events.get(4), "bar"); assertCharacters(events.get(5), "bar"); assertEndElement(events.get(6), "bar"); assertEndElement(events.get(7), "pojo"); }) .consumeNextWith(events -> { assertThat(events).hasSize(8); assertStartElement(events.get(0), "pojo"); assertStartElement(events.get(1), "foo"); assertCharacters(events.get(2), "foofoo"); assertEndElement(events.get(3), "foo"); assertStartElement(events.get(4), "bar"); assertCharacters(events.get(5), "barbar"); assertEndElement(events.get(6), "bar"); assertEndElement(events.get(7), "pojo"); }) .expectComplete() .verify(); } private static void assertStartElement(XMLEvent event, String expectedLocalName) { assertThat(event.isStartElement()).isTrue(); assertThat(event.asStartElement().getName().getLocalPart()).isEqualTo(expectedLocalName); } private static void assertEndElement(XMLEvent event, String expectedLocalName) { assertThat(event.isEndElement()).isTrue(); assertThat(event.asEndElement().getName().getLocalPart()).isEqualTo(expectedLocalName); } private static void assertCharacters(XMLEvent event, String expectedData) { assertThat(event.isCharacters()).isTrue(); assertThat(event.asCharacters().getData()).isEqualTo(expectedData); } @Test void decodeSingleXmlRootElement() { Mono<DataBuffer> source = toDataBufferMono(POJO_ROOT); Mono<Object> output = this.decoder.decodeToMono(source, ResolvableType.forClass(Pojo.class), null, HINTS); StepVerifier.create(output) .expectNext(new Pojo("foofoo", "barbar")) .expectComplete() .verify(); } @Test void decodeSingleXmlTypeElement() { Mono<DataBuffer> source = toDataBufferMono(POJO_ROOT); Mono<Object> output = this.decoder.decodeToMono(source, ResolvableType.forClass(TypePojo.class), null, HINTS); StepVerifier.create(output) .expectNext(new TypePojo("foofoo", "barbar")) .expectComplete() .verify(); } @Test void decodeMultipleXmlRootElement() { Mono<DataBuffer> source = toDataBufferMono(POJO_CHILD); Flux<Object> output = this.decoder.decode(source, ResolvableType.forClass(Pojo.class), null, HINTS); StepVerifier.create(output) .expectNext(new Pojo("foo", "bar")) .expectNext(new Pojo("foofoo", "barbar")) .expectComplete() .verify(); } @Test void decodeMultipleXmlTypeElement() { Mono<DataBuffer> source = toDataBufferMono(POJO_CHILD); Flux<Object> output = this.decoder.decode(source, ResolvableType.forClass(TypePojo.class), null, HINTS); StepVerifier.create(output) .expectNext(new TypePojo("foo", "bar")) .expectNext(new TypePojo("foofoo", "barbar")) .expectComplete() .verify(); } @Test void decodeXmlSeeAlso() { Mono<DataBuffer> source = toDataBufferMono(POJO_CHILD); Flux<Object> output = this.decoder.decode(source, ResolvableType.forClass(Parent.class), null, HINTS); StepVerifier.create(output) .expectNext(new Child("foo", "bar")) .expectNext(new Child("foofoo", "barbar")) .expectComplete() .verify(); } @Test void decodeError() { Flux<DataBuffer> source = Flux.concat( toDataBufferMono("<pojo>"), Flux.error(new RuntimeException())); Mono<Object> output = this.decoder.decodeToMono(source, ResolvableType.forClass(Pojo.class), null, HINTS); StepVerifier.create(output) .expectError(RuntimeException.class) .verify(); } @Test // gh-24622 public void decodeErrorWithXmlNotWellFormed() { Mono<DataBuffer> source = toDataBufferMono("<Response><tag>something</tag</Response>"); Mono<Object> result = this.decoder.decodeToMono(source, ResolvableType.forClass(Pojo.class), null, HINTS); StepVerifier.create(result).verifyErrorSatisfies(ex -> assertThat(Exceptions.unwrap(ex)).isInstanceOf(DecodingException.class)); } @Test void decodeNonUtf8() { String xml = "<pojo>" + "<foo>føø</foo>" + "<bar>bär</bar>" + "</pojo>"; Mono<DataBuffer> source = Mono.fromCallable(() -> { byte[] bytes = xml.getBytes(StandardCharsets.ISO_8859_1); DataBuffer buffer = this.bufferFactory.allocateBuffer(bytes.length); buffer.write(bytes); return buffer; }); MimeType mimeType = new MimeType(MediaType.APPLICATION_XML, StandardCharsets.ISO_8859_1); Mono<Object> output = this.decoder.decodeToMono(source, ResolvableType.forClass(TypePojo.class), mimeType, HINTS); StepVerifier.create(output) .expectNext(new TypePojo("føø", "bär")) .expectComplete() .verify(); } private Mono<DataBuffer> toDataBufferMono(String value) { return Mono.defer(() -> { byte[] bytes = value.getBytes(StandardCharsets.UTF_8); DataBuffer buffer = this.bufferFactory.allocateBuffer(bytes.length); buffer.write(bytes); return Mono.just(buffer); }); } @jakarta.xml.bind.annotation.XmlType @XmlSeeAlso(Child.class) public abstract static
Jaxb2XmlDecoderTests
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/internal/tls/SslContextManager.java
{ "start": 1182, "end": 10201 }
class ____ { private static final Config NULL_CONFIG = new Config(null, null, null, null, null); static final EnumMap<ClientAuth, io.netty.handler.ssl.ClientAuth> CLIENT_AUTH_MAPPING = new EnumMap<>(ClientAuth.class); static { CLIENT_AUTH_MAPPING.put(ClientAuth.REQUIRED, io.netty.handler.ssl.ClientAuth.REQUIRE); CLIENT_AUTH_MAPPING.put(ClientAuth.REQUEST, io.netty.handler.ssl.ClientAuth.OPTIONAL); CLIENT_AUTH_MAPPING.put(ClientAuth.NONE, io.netty.handler.ssl.ClientAuth.NONE); } private final Supplier<SslContextFactory> supplier; private final boolean useWorkerPool; private final Map<ConfigKey, Future<Config>> configMap; private final Map<ConfigKey, Future<SslContextProvider>> sslContextProviderMap; public SslContextManager(SSLEngineOptions sslEngineOptions, int cacheMaxSize) { this.configMap = new LruCache<>(cacheMaxSize); this.sslContextProviderMap = new LruCache<>(cacheMaxSize); this.supplier = sslEngineOptions::sslContextFactory; this.useWorkerPool = sslEngineOptions.getUseWorkerThread(); } /** * Resolve the ssl engine options to use for properly running the configured options. */ public static SSLEngineOptions resolveEngineOptions(SSLEngineOptions engineOptions, boolean useAlpn) { if (engineOptions == null) { if (useAlpn) { if (JdkSSLEngineOptions.isAlpnAvailable()) { engineOptions = new JdkSSLEngineOptions(); } else if (OpenSSLEngineOptions.isAlpnAvailable()) { engineOptions = new OpenSSLEngineOptions(); } } } if (engineOptions == null) { engineOptions = new JdkSSLEngineOptions(); } else if (engineOptions instanceof OpenSSLEngineOptions) { if (!OpenSsl.isAvailable()) { VertxException ex = new VertxException("OpenSSL is not available"); Throwable cause = OpenSsl.unavailabilityCause(); if (cause != null) { ex.initCause(cause); } throw ex; } } if (useAlpn) { if (engineOptions instanceof JdkSSLEngineOptions) { if (!JdkSSLEngineOptions.isAlpnAvailable()) { throw new VertxException("ALPN not available for JDK SSL/TLS engine"); } } if (engineOptions instanceof OpenSSLEngineOptions) { if (!OpenSSLEngineOptions.isAlpnAvailable()) { throw new VertxException("ALPN is not available for OpenSSL SSL/TLS engine"); } } } return engineOptions; } public synchronized int sniEntrySize() { int size = 0; for (Future<SslContextProvider> fut : sslContextProviderMap.values()) { SslContextProvider result = fut.result(); if (result != null) { size += result.sniEntrySize(); } } return size; } public SslContextManager(SSLEngineOptions sslEngineOptions) { this(sslEngineOptions, 256); } public Future<SslContextProvider> resolveSslContextProvider(SSLOptions options, ContextInternal ctx) { if (options instanceof ClientSSLOptions) { return resolveSslContextProvider((ClientSSLOptions) options, ctx); } else { return resolveSslContextProvider((ServerSSLOptions) options, ctx); } } public Future<SslContextProvider> resolveSslContextProvider(ServerSSLOptions options, ContextInternal ctx) { ClientAuth clientAuth = options.getClientAuth(); if (clientAuth == null) { clientAuth = ClientAuth.NONE; } return resolveSslContextProvider(options, null, clientAuth, false, ctx); } public Future<SslContextProvider> resolveSslContextProvider(ClientSSLOptions options, ContextInternal ctx) { String hostnameVerificationAlgorithm = options.getHostnameVerificationAlgorithm(); if (hostnameVerificationAlgorithm == null) { hostnameVerificationAlgorithm = ""; } return resolveSslContextProvider(options, hostnameVerificationAlgorithm, null, false, ctx); } public Future<SslContextProvider> resolveSslContextProvider(SSLOptions options, String endpointIdentificationAlgorithm, ClientAuth clientAuth, ContextInternal ctx) { return resolveSslContextProvider(options, endpointIdentificationAlgorithm, clientAuth, false, ctx); } public Future<SslContextProvider> resolveSslContextProvider(SSLOptions options, String hostnameVerificationAlgorithm, ClientAuth clientAuth, boolean force, ContextInternal ctx) { Promise<SslContextProvider> promise; ConfigKey k = new ConfigKey(options); synchronized (this) { if (force) { sslContextProviderMap.remove(k); } else { Future<SslContextProvider> v = sslContextProviderMap.get(k); if (v != null) { return v; } } promise = Promise.promise(); sslContextProviderMap.put(k, promise.future()); } buildSslContextProvider(options, hostnameVerificationAlgorithm, clientAuth, force, ctx) .onComplete(promise); return promise.future(); } /** * Initialize the helper, this loads and validates the configuration. * * @param ctx the context * @return a future resolved when the helper is initialized */ public Future<SslContextProvider> buildSslContextProvider(SSLOptions sslOptions, String hostnameVerificationAlgorithm, ClientAuth clientAuth, boolean force, ContextInternal ctx) { return buildConfig(sslOptions, force, ctx) .map(config -> buildSslContextProvider(sslOptions, hostnameVerificationAlgorithm, supplier, clientAuth, config)); } private SslContextProvider buildSslContextProvider(SSLOptions sslOptions, String hostnameVerificationAlgorithm, Supplier<SslContextFactory> supplier, ClientAuth clientAuth, Config config) { return new SslContextProvider( useWorkerPool, clientAuth, hostnameVerificationAlgorithm, sslOptions.getApplicationLayerProtocols(), sslOptions.getEnabledCipherSuites(), sslOptions.getEnabledSecureTransportProtocols(), config.keyManagerFactory, config.keyManagerFactoryMapper, config.trustManagerFactory, config.trustManagerMapper, config.crls, supplier); } private static TrustOptions trustOptionsOf(SSLOptions sslOptions) { if (sslOptions instanceof ClientSSLOptions) { ClientSSLOptions clientSSLOptions = (ClientSSLOptions) sslOptions; if (clientSSLOptions.isTrustAll()) { return TrustAllOptions.INSTANCE; } } return sslOptions.getTrustOptions(); } private Future<Config> buildConfig(SSLOptions sslOptions, boolean force, ContextInternal ctx) { if (trustOptionsOf(sslOptions) == null && sslOptions.getKeyCertOptions() == null) { return ctx.succeededFuture(NULL_CONFIG); } Promise<Config> promise; ConfigKey k = new ConfigKey(sslOptions); synchronized (this) { if (force) { configMap.remove(k); } else { Future<Config> fut = configMap.get(k); if (fut != null) { return fut; } } promise = Promise.promise(); configMap.put(k, promise.future()); } ctx.executeBlockingInternal(() -> { KeyManagerFactory keyManagerFactory = null; Function<String, KeyManagerFactory> keyManagerFactoryMapper = null; TrustManagerFactory trustManagerFactory = null; Function<String, TrustManager[]> trustManagerMapper = null; List<CRL> crls = new ArrayList<>(); if (sslOptions.getKeyCertOptions() != null) { keyManagerFactory = sslOptions.getKeyCertOptions().getKeyManagerFactory(ctx.owner()); keyManagerFactoryMapper = sslOptions.getKeyCertOptions().keyManagerFactoryMapper(ctx.owner()); } TrustOptions trustOptions = trustOptionsOf(sslOptions); if (trustOptions != null) { trustManagerFactory = trustOptions.getTrustManagerFactory(ctx.owner()); trustManagerMapper = trustOptions.trustManagerMapper(ctx.owner()); } List<Buffer> tmp = new ArrayList<>(); if (sslOptions.getCrlPaths() != null) { tmp.addAll(sslOptions.getCrlPaths() .stream() .map(path -> ctx.owner().fileResolver().resolve(path).getAbsolutePath()) .map(ctx.owner().fileSystem()::readFileBlocking) .collect(Collectors.toList())); } if (sslOptions.getCrlValues() != null) { tmp.addAll(sslOptions.getCrlValues()); } CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509"); for (Buffer crlValue : tmp) { crls.addAll(certificatefactory.generateCRLs(new ByteArrayInputStream(crlValue.getBytes()))); } return new Config(keyManagerFactory, trustManagerFactory, keyManagerFactoryMapper, trustManagerMapper, crls); }).onComplete(promise); return promise.future(); } private static
SslContextManager
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/SupportingField.java
{ "start": 404, "end": 2384 }
class ____ extends Field { private final String templateName; private final Map<String, Object> templateParameter; private final SupportingMappingMethod definingMethod; public SupportingField(SupportingMappingMethod definingMethod, FieldReference fieldReference, String name) { super( fieldReference.getType(), name, true ); this.templateName = getTemplateNameForClass( fieldReference.getClass() ); this.templateParameter = fieldReference.getTemplateParameter(); this.definingMethod = definingMethod; } @Override public String getTemplateName() { return templateName; } public Map<String, Object> getTemplateParameter() { return templateParameter; } public SupportingMappingMethod getDefiningMethod() { return definingMethod; } public static void addAllFieldsIn(Set<SupportingMappingMethod> supportingMappingMethods, Set<Field> targets) { for ( SupportingMappingMethod supportingMappingMethod : supportingMappingMethods ) { Field field = supportingMappingMethod.getSupportingField(); if ( field != null ) { targets.add( supportingMappingMethod.getSupportingField() ); } } } public static Field getSafeField(SupportingMappingMethod method, FieldReference ref, Set<Field> existingFields) { if ( ref == null ) { return null; } String name = ref.getVariableName(); for ( Field existingField : existingFields ) { if ( existingField.getVariableName().equals( ref.getVariableName() ) && existingField.getType().equals( ref.getType() ) ) { // field already exists, use that one return existingField; } } name = Strings.getSafeVariableName( name, Field.getFieldNames( existingFields ) ); return new SupportingField( method, ref, name ); } }
SupportingField
java
micronaut-projects__micronaut-core
http-server-netty/src/main/java/io/micronaut/http/server/netty/handler/Compressor.java
{ "start": 8787, "end": 11239 }
class ____ { private final EmbeddedChannel compressionChannel; private boolean finished = false; private Session(ChannelHandlerContext ctx, ChannelHandler handler) { compressionChannel = new EmbeddedChannel( ctx.channel().id(), ctx.channel().metadata().hasDisconnect(), ctx.channel().config(), handler ); } void push(ByteBuf data) { if (finished) { throw new IllegalStateException("Compression already finished"); } if (data.isReadable()) { compressionChannel.writeOutbound(data); } else { data.release(); } } void finish() { if (!finished) { compressionChannel.finish(); finished = true; } } void discard() { if (!finished) { try { compressionChannel.finishAndReleaseAll(); } catch (DecompressionException ignored) { } finished = true; } } void fixContentLength(HttpResponse hr) { if (!finished) { throw new IllegalStateException("Compression not finished yet"); } // fix content-length if necessary if (hr.headers().contains(HttpHeaderNames.CONTENT_LENGTH)) { long newContentLength = 0; for (Object outboundMessage : compressionChannel.outboundMessages()) { newContentLength += ((ByteBuf) outboundMessage).readableBytes(); } hr.headers().set(HttpHeaderNames.CONTENT_LENGTH, newContentLength); } } @Nullable ByteBuf poll() { int n = compressionChannel.outboundMessages().size(); if (n == 0) { return null; } else if (n == 1) { return compressionChannel.readOutbound(); } CompositeByteBuf buf = compressionChannel.alloc().compositeBuffer(n); while (true) { ByteBuf item = compressionChannel.readOutbound(); if (item == null) { break; } buf.addComponent(true, item); } return buf; } } }
Session
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/metrics/TimerGaugeTest.java
{ "start": 8411, "end": 8913 }
class ____ implements TimerGauge.StartStopListener { long startCount; long endCount; @Override public void markStart() { startCount++; } @Override public void markEnd() { endCount++; } public void assertCounts(long expectedStart, long expectedEnd) { assertThat(startCount).isEqualTo(expectedStart); assertThat(endCount).isEqualTo(expectedEnd); } } }
TestStartStopListener
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/LineNumberProcessorTest.java
{ "start": 1121, "end": 2011 }
class ____ extends ContextTestSupport { @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); context.setSourceLocationEnabled(true); return context; } @Test public void testLineNumber() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("LineNumberProcessorTest.java:51"); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .process(new MyProcessor()) .to("mock:result"); } }; } private static
LineNumberProcessorTest
java
elastic__elasticsearch
libs/entitlement/src/main/java/org/elasticsearch/entitlement/runtime/policy/FileUtils.java
{ "start": 576, "end": 2582 }
class ____ { private FileUtils() {} /** * Tests if a path is absolute or relative, taking into consideration both Unix and Windows conventions. * Note that this leads to a conflict, resolved in favor of Unix rules: `/foo` can be either a Unix absolute path, or a Windows * relative path with "wrong" directory separator (using non-canonical / in Windows). * This method is intended to be used as validation for different file entitlements format: therefore it is preferable to reject a * relative path that is definitely absolute on Unix, rather than accept it as a possible relative path on Windows (if that is the case, * the developer can easily fix the path by using the correct platform separators). */ public static boolean isAbsolutePath(String path) { if (path.isEmpty()) { return false; } if (path.charAt(0) == '/') { // Unix/BSD absolute return true; } return isWindowsAbsolutePath(path); } /** * When testing for path separators in a platform-agnostic way, we may encounter both kinds of slashes, especially when * processing windows paths. The JDK parses paths the same way under Windows. */ static boolean isSlash(char c) { return (c == '\\') || (c == '/'); } private static boolean isWindowsAbsolutePath(String input) { // if a prefix is present, we expected (long) UNC or (long) absolute if (input.startsWith("\\\\?\\")) { return true; } if (input.length() > 1) { char c0 = input.charAt(0); char c1 = input.charAt(1); if (isSlash(c0) && isSlash(c1)) { // Two slashes or more: UNC return true; } if (isLetter(c0) && c1 == ':') { // A drive: absolute return true; } } // Otherwise relative return false; } }
FileUtils
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/DistributedSchedulingAllocateResponsePBImpl.java
{ "start": 1507, "end": 6148 }
class ____ extends DistributedSchedulingAllocateResponse { YarnServerCommonServiceProtos.DistributedSchedulingAllocateResponseProto proto = YarnServerCommonServiceProtos. DistributedSchedulingAllocateResponseProto.getDefaultInstance(); YarnServerCommonServiceProtos.DistributedSchedulingAllocateResponseProto. Builder builder = null; boolean viaProto = false; private AllocateResponse allocateResponse; private List<RemoteNode> nodesForScheduling; public DistributedSchedulingAllocateResponsePBImpl() { builder = YarnServerCommonServiceProtos. DistributedSchedulingAllocateResponseProto.newBuilder(); } public DistributedSchedulingAllocateResponsePBImpl( YarnServerCommonServiceProtos. DistributedSchedulingAllocateResponseProto proto) { this.proto = proto; viaProto = true; } public YarnServerCommonServiceProtos. DistributedSchedulingAllocateResponseProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = YarnServerCommonServiceProtos. DistributedSchedulingAllocateResponseProto.newBuilder(proto); } viaProto = false; } private synchronized void mergeLocalToProto() { if (viaProto) maybeInitBuilder(); mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private synchronized void mergeLocalToBuilder() { if (this.nodesForScheduling != null) { builder.clearNodesForScheduling(); Iterable<YarnServerCommonServiceProtos.RemoteNodeProto> iterable = getNodeIdProtoIterable(this.nodesForScheduling); builder.addAllNodesForScheduling(iterable); } if (this.allocateResponse != null) { builder.setAllocateResponse( ((AllocateResponsePBImpl) this.allocateResponse).getProto()); } } @Override public void setAllocateResponse(AllocateResponse response) { maybeInitBuilder(); if (allocateResponse == null) { builder.clearAllocateResponse(); } this.allocateResponse = response; } @Override public AllocateResponse getAllocateResponse() { if (this.allocateResponse != null) { return this.allocateResponse; } YarnServerCommonServiceProtos. DistributedSchedulingAllocateResponseProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasAllocateResponse()) { return null; } this.allocateResponse = new AllocateResponsePBImpl(p.getAllocateResponse()); return this.allocateResponse; } @Override public void setNodesForScheduling(List<RemoteNode> nodesForScheduling) { maybeInitBuilder(); if (nodesForScheduling == null || nodesForScheduling.isEmpty()) { if (this.nodesForScheduling != null) { this.nodesForScheduling.clear(); } builder.clearNodesForScheduling(); return; } this.nodesForScheduling = new ArrayList<>(); this.nodesForScheduling.addAll(nodesForScheduling); } @Override public List<RemoteNode> getNodesForScheduling() { if (nodesForScheduling != null) { return nodesForScheduling; } initLocalNodesForSchedulingList(); return nodesForScheduling; } private synchronized void initLocalNodesForSchedulingList() { YarnServerCommonServiceProtos. DistributedSchedulingAllocateResponseProtoOrBuilder p = viaProto ? proto : builder; List<YarnServerCommonServiceProtos.RemoteNodeProto> list = p.getNodesForSchedulingList(); nodesForScheduling = new ArrayList<>(); if (list != null) { for (YarnServerCommonServiceProtos.RemoteNodeProto t : list) { nodesForScheduling.add(new RemoteNodePBImpl(t)); } } } private synchronized Iterable<RemoteNodeProto> getNodeIdProtoIterable( final List<RemoteNode> nodeList) { maybeInitBuilder(); return new Iterable<RemoteNodeProto>() { @Override public synchronized Iterator<RemoteNodeProto> iterator() { return new Iterator<RemoteNodeProto>() { Iterator<RemoteNode> iter = nodeList.iterator(); @Override public boolean hasNext() { return iter.hasNext(); } @Override public RemoteNodeProto next() { return ((RemoteNodePBImpl)iter.next()).getProto(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } }
DistributedSchedulingAllocateResponsePBImpl
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableRange.java
{ "start": 4778, "end": 6549 }
class ____ extends BaseRangeSubscription { private static final long serialVersionUID = 2587302975077663557L; final ConditionalSubscriber<? super Integer> downstream; RangeConditionalSubscription(ConditionalSubscriber<? super Integer> actual, int index, int end) { super(index, end); this.downstream = actual; } @Override void fastPath() { int f = end; ConditionalSubscriber<? super Integer> a = downstream; for (int i = index; i != f; i++) { if (cancelled) { return; } a.tryOnNext(i); } if (cancelled) { return; } a.onComplete(); } @Override void slowPath(long r) { long e = 0; int f = end; int i = index; ConditionalSubscriber<? super Integer> a = downstream; for (;;) { while (e != r && i != f) { if (cancelled) { return; } if (a.tryOnNext(i)) { e++; } i++; } if (i == f) { if (!cancelled) { a.onComplete(); } return; } r = get(); if (e == r) { index = i; r = addAndGet(-e); if (r == 0) { return; } e = 0; } } } } }
RangeConditionalSubscription
java
google__dagger
javatests/dagger/internal/codegen/UnresolvableDependencyTest.java
{ "start": 5894, "end": 6346 }
class ____ {", " @Inject", " Bar(String dep) {}", "}"); CompilerTests.daggerCompiler(fooComponent, foo, bar) .compile( subject -> { switch (CompilerTests.backend(subject)) { case JAVAC: subject.hasErrorCount(3); subject.hasErrorContaining( "cannot find symbol" + "\n symbol:
Bar
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiPropertySource.java
{ "start": 3437, "end": 3737 }
class ____ { private final String prefix; Mapping(String prefix) { this.prefix = prefix; } String getPrefix() { return this.prefix; } abstract @Nullable AnsiElement getElement(String postfix); } /** * {@link Mapping} for {@link AnsiElement} enums. */ private static
Mapping
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/CamelEvent.java
{ "start": 7486, "end": 7669 }
interface ____ extends ExchangeEvent { Processor getFailureHandler(); boolean isDeadLetterChannel(); String getDeadLetterUri(); }
ExchangeFailureEvent
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/transformer/AsyncReturnValueTransformerTest.java
{ "start": 1570, "end": 1694 }
class ____ { public Uni<String> hello() { return Uni.createFrom().item("hello"); } } }
MyService
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/ValidatorTest.java
{ "start": 2666, "end": 3272 }
class ____ { @InlineMe( replacement = "new Duration[size]", imports = {"java.time.Duration"}) @Deprecated public Duration[] someDurations(int size) { return new Duration[size]; } } """) .doTest(); } @Test public void arrayConstructor_fromStaticMethod() { helper .addSourceLines( "Foo.java", """ import com.google.errorprone.annotations.InlineMe; import java.time.Duration; public final
Foo
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/AsyncCallableReturnsNull.java
{ "start": 1062, "end": 1208 }
class ____ extends AbstractAsyncTypeReturnsNull { public AsyncCallableReturnsNull() { super(AsyncCallable.class); } }
AsyncCallableReturnsNull
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/connector/ConnectorCustomScheduleTests.java
{ "start": 1175, "end": 4029 }
class ____ extends ESTestCase { private NamedWriteableRegistry namedWriteableRegistry; @Before public void registerNamedObjects() { SearchModule searchModule = new SearchModule(Settings.EMPTY, emptyList()); List<NamedWriteableRegistry.Entry> namedWriteables = searchModule.getNamedWriteables(); namedWriteableRegistry = new NamedWriteableRegistry(namedWriteables); } public final void testRandomSerialization() throws IOException { for (int runs = 0; runs < 10; runs++) { ConnectorCustomSchedule testInstance = ConnectorTestUtils.getRandomConnectorCustomSchedule(); assertTransportSerialization(testInstance); } } public void testToXContent() throws IOException { String content = XContentHelper.stripWhitespace(""" { "configuration_overrides": { "domain_allowlist": [ "https://example.com" ], "max_crawl_depth": 1, "seed_urls": [ "https://example.com/blog", "https://example.com/info" ], "sitemap_discovery_disabled": true, "sitemap_urls": [ "https://example.com/sitemap.xml" ] }, "enabled": true, "interval": "0 0 12 * * ?", "last_synced": null, "name": "My Schedule" } """); ConnectorCustomSchedule customSchedule = ConnectorCustomSchedule.fromXContentBytes(new BytesArray(content), XContentType.JSON); boolean humanReadable = true; BytesReference originalBytes = toShuffledXContent(customSchedule, XContentType.JSON, ToXContent.EMPTY_PARAMS, humanReadable); ConnectorCustomSchedule parsed; try (XContentParser parser = createParser(XContentType.JSON.xContent(), originalBytes)) { parsed = ConnectorCustomSchedule.fromXContent(parser); } assertToXContentEquivalent(originalBytes, toXContent(parsed, XContentType.JSON, humanReadable), XContentType.JSON); } private void assertTransportSerialization(ConnectorCustomSchedule testInstance) throws IOException { ConnectorCustomSchedule deserializedInstance = copyInstance(testInstance); assertNotSame(testInstance, deserializedInstance); assertThat(testInstance, equalTo(deserializedInstance)); } private ConnectorCustomSchedule copyInstance(ConnectorCustomSchedule instance) throws IOException { return copyWriteable(instance, namedWriteableRegistry, ConnectorCustomSchedule::new); } }
ConnectorCustomScheduleTests
java
elastic__elasticsearch
modules/aggregations/src/test/java/org/elasticsearch/aggregations/pipeline/PipelineAggregationHelperTests.java
{ "start": 4038, "end": 5995 }
class ____ { public int count; public double[] docValues; public long key; } /** * Computes a simple agg metric (min, sum, etc) from the provided values * * @param values Array of values to compute metric for * @param metric A metric builder which defines what kind of metric should be returned for the values */ public static double calculateMetric(double[] values, ValuesSourceAggregationBuilder<?> metric) { if (metric instanceof MinAggregationBuilder) { double accumulator = Double.POSITIVE_INFINITY; for (double value : values) { accumulator = Math.min(accumulator, value); } return accumulator; } else if (metric instanceof MaxAggregationBuilder) { double accumulator = Double.NEGATIVE_INFINITY; for (double value : values) { accumulator = Math.max(accumulator, value); } return accumulator; } else if (metric instanceof SumAggregationBuilder) { double accumulator = 0; for (double value : values) { accumulator += value; } return accumulator; } else if (metric instanceof AvgAggregationBuilder) { double accumulator = 0; for (double value : values) { accumulator += value; } return values.length == 0 ? Double.NaN : accumulator / values.length; } return 0.0; } public static AggregationBuilder getRandomSequentiallyOrderedParentAgg() throws IOException { @SuppressWarnings("unchecked") Function<String, AggregationBuilder> builder = randomFrom( HistogramAggregationBuilder::new, DateHistogramAggregationBuilder::new, AutoDateHistogramAggregationBuilder::new ); return builder.apply("name"); } }
MockBucket
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schematools/TestExtraPhysicalTableTypes.java
{ "start": 1968, "end": 6919 }
class ____ { @Test @ServiceRegistry(settings = @Setting(name = EXTRA_PHYSICAL_TABLE_TYPES, value = "BASE TABLE")) public void testAddOneExtraPhysicalTableType(ServiceRegistryScope registryScope) throws Exception{ var model = buildMetadata( registryScope ); try (var ddlTransactionIsolator = buildDdlTransactionIsolator( registryScope )) { var informationExtractor = buildInformationExtractor( ddlTransactionIsolator, registryScope, model ); assertThat( informationExtractor.isPhysicalTableType( "BASE TABLE" ), is( true ) ); assertThat( informationExtractor.isPhysicalTableType( "TABLE" ), is( true ) ); } } @Test @ServiceRegistry(settings = @Setting(name = EXTRA_PHYSICAL_TABLE_TYPES, value = "BASE, BASE TABLE")) public void testAddingMultipleExtraPhysicalTableTypes(ServiceRegistryScope registryScope) throws Exception { var model = buildMetadata( registryScope ); try (var ddlTransactionIsolator = buildDdlTransactionIsolator( registryScope )) { var informationExtractor = buildInformationExtractor( ddlTransactionIsolator, registryScope, model ); assertThat( informationExtractor.isPhysicalTableType( "BASE TABLE" ), is( true ) ); assertThat( informationExtractor.isPhysicalTableType( "BASE" ), is( true ) ); assertThat( informationExtractor.isPhysicalTableType( "TABLE" ), is( true ) ); assertThat( informationExtractor.isPhysicalTableType( "TABLE 1" ), is( false ) ); } } @Test @ServiceRegistry(settings = @Setting(name = EXTRA_PHYSICAL_TABLE_TYPES, value = " ")) public void testExtraPhysicalTableTypesPropertyEmptyStringValue(ServiceRegistryScope registryScope) throws Exception { var model = buildMetadata( registryScope ); var dialect = model.getDatabase().getDialect(); // As of 2.0.202 H2 reports tables as BASE TABLE so we add the type through the dialect assumeFalse( dialect instanceof H2Dialect && dialect.getVersion().isSameOrAfter( 2 ) ); try (var ddlTransactionIsolator = buildDdlTransactionIsolator( registryScope )) { var informationExtractor = buildInformationExtractor( ddlTransactionIsolator, registryScope, model ); assertThat( informationExtractor.isPhysicalTableType( "BASE TABLE" ), is( false ) ); assertThat( informationExtractor.isPhysicalTableType( "TABLE" ), is( true ) ); } } @Test @ServiceRegistry public void testNoExtraPhysicalTableTypesProperty(ServiceRegistryScope registryScope) throws Exception { var model = buildMetadata( registryScope ); var dialect = model.getDatabase().getDialect(); // As of 2.0.202 H2 reports tables as BASE TABLE so we add the type through the dialect assumeFalse( dialect instanceof H2Dialect && dialect.getVersion().isSameOrAfter( 2 ) ); try (var ddlTransactionIsolator = buildDdlTransactionIsolator( registryScope )) { var informationExtractor = buildInformationExtractor( ddlTransactionIsolator, registryScope, model ); assertThat( informationExtractor.isPhysicalTableType( "BASE TABLE" ), is( false ) ); assertThat( informationExtractor.isPhysicalTableType( "TABLE" ), is( true ) ); } } private InformationExtractorJdbcDatabaseMetaDataImplTest buildInformationExtractor( DdlTransactionIsolator ddlTransactionIsolator, ServiceRegistryScope registryScope, MetadataImplementor metadata) throws SQLException { Database database = metadata.getDatabase(); SqlStringGenerationContext sqlStringGenerationContext = SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ); DatabaseInformation dbInfo = new DatabaseInformationImpl( registryScope.getRegistry(), database.getJdbcEnvironment(), sqlStringGenerationContext, ddlTransactionIsolator, registryScope.getRegistry().requireService( SchemaManagementTool.class ) ); ExtractionContextImpl extractionContext = new ExtractionContextImpl( registryScope.getRegistry(), database.getJdbcEnvironment(), sqlStringGenerationContext, registryScope.getRegistry().requireService( JdbcServices.class ).getBootstrapJdbcConnectionAccess(), (ExtractionContext.DatabaseObjectAccess) dbInfo ); return new InformationExtractorJdbcDatabaseMetaDataImplTest( extractionContext ); } private DdlTransactionIsolator buildDdlTransactionIsolator(ServiceRegistryScope registryScope) { final ConnectionProvider connectionProvider = registryScope.getRegistry().requireService( ConnectionProvider.class ); return new DdlTransactionIsolatorTestingImpl( registryScope.getRegistry(), new JdbcEnvironmentInitiator.ConnectionProviderJdbcConnectionAccess( connectionProvider ) ); } private MetadataImplementor buildMetadata(ServiceRegistryScope registryScope) { var metadata = (MetadataImplementor) new MetadataSources( registryScope.getRegistry() ) .buildMetadata(); metadata.orderColumns( false ); metadata.validate(); return metadata; } public static
TestExtraPhysicalTableTypes
java
google__guava
android/guava/src/com/google/common/collect/Streams.java
{ "start": 24687, "end": 27563 }
class ____ extends MapWithIndexSpliterator<Spliterator.OfLong, R, Splitr> implements LongConsumer { long holder; Splitr(Spliterator.OfLong splitr, long index) { super(splitr, index); } @Override public void accept(long t) { this.holder = t; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromSpliterator.tryAdvance(this)) { action.accept(function.apply(holder, index++)); return true; } return false; } @Override Splitr createSplit(Spliterator.OfLong from, long i) { return new Splitr(from, i); } } return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close); } /** * Returns a stream consisting of the results of applying the given function to the elements of * {@code stream} and their indexes in the stream. For example, * * {@snippet : * mapWithIndex( * DoubleStream.of(0.0, 1.0, 2.0) * (e, index) -> index + ":" + e) * } * * <p>...would return {@code Stream.of("0:0.0", "1:1.0", "2:2.0")}. * * <p>The resulting stream is <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * if and only if {@code stream} was efficiently splittable and its underlying spliterator * reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream * comes from a data structure supporting efficient indexed random access, typically an array or * list. * * <p>The order of the resulting stream is defined if and only if the order of the original stream * was defined. */ public static <R extends @Nullable Object> Stream<R> mapWithIndex( DoubleStream stream, DoubleFunctionWithIndex<R> function) { checkNotNull(stream); checkNotNull(function); boolean isParallel = stream.isParallel(); Spliterator.OfDouble fromSpliterator = stream.spliterator(); if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) { PrimitiveIterator.OfDouble fromIterator = Spliterators.iterator(fromSpliterator); return StreamSupport.stream( new AbstractSpliterator<R>( fromSpliterator.estimateSize(), fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) { long index = 0; @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromIterator.hasNext()) { action.accept(function.apply(fromIterator.nextDouble(), index++)); return true; } return false; } }, isParallel) .onClose(stream::close); } final
Splitr
java
alibaba__druid
core/src/main/java/com/alibaba/druid/mock/MockDriver.java
{ "start": 1204, "end": 9564 }
class ____ implements Driver, MockDriverMBean { private static Log LOG; public static final MockExecuteHandler DEFAULT_HANDLER = new MySqlMockExecuteHandlerImpl(); private String prefix = "jdbc:fake:"; private String mockPrefix = "jdbc:mock:"; private MockExecuteHandler executeHandler = DEFAULT_HANDLER; public static final MockDriver instance = new MockDriver(); private final AtomicLong connectCount = new AtomicLong(); private final AtomicLong connectionCloseCount = new AtomicLong(); private final AtomicLong connectionIdSeed = new AtomicLong(1000L); private final List<MockConnection> connections = new CopyOnWriteArrayList<MockConnection>(); private long idleTimeCount = 1000 * 60 * 3; private boolean logExecuteQueryEnable = true; private static final String MBEAN_NAME = "com.alibaba.druid:type=MockDriver"; static { registerDriver(instance); } public boolean isLogExecuteQueryEnable() { return logExecuteQueryEnable; } private static Log getLog() { if (LOG == null) { LOG = LogFactory.getLog(MockDriver.class); } return LOG; } public void setLogExecuteQueryEnable(boolean logExecuteQueryEnable) { this.logExecuteQueryEnable = logExecuteQueryEnable; } public long getIdleTimeCount() { return idleTimeCount; } public void setIdleTimeCount(long idleTimeCount) { this.idleTimeCount = idleTimeCount; } public long generateConnectionId() { return connectionIdSeed.incrementAndGet(); } public void closeAllConnections() throws SQLException { for (int i = 0, size = this.connections.size(); i < size; ++i) { Connection conn = this.connections.get(size - i - 1); conn.close(); } } public int getConnectionsSize() { return this.connections.size(); } public List<MockConnection> getConnections() { return connections; } protected void incrementConnectionCloseCount() { connectionCloseCount.incrementAndGet(); } public long getConnectionCloseCount() { return connectionCloseCount.get(); } protected void afterConnectionClose(MockConnection conn) { connectionCloseCount.incrementAndGet(); connections.remove(conn); if (getLog().isDebugEnabled()) { getLog().debug("conn-" + conn.getId() + " close"); } } public static boolean registerDriver(Driver driver) { try { DriverManager.registerDriver(driver); try { MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName = new ObjectName(MBEAN_NAME); if (!mbeanServer.isRegistered(objectName)) { mbeanServer.registerMBean(instance, objectName); } } catch (Exception ex) { getLog().warn("register druid-driver mbean error", ex); } return true; } catch (Exception e) { getLog().error("registerDriver error", e); } return false; } public MockExecuteHandler getExecuteHandler() { return executeHandler; } public void setExecuteHandler(MockExecuteHandler executeHandler) { this.executeHandler = executeHandler; } @Override public Connection connect(String url, Properties info) throws SQLException { if (!acceptsURL(url)) { return null; } if (info != null) { Object val = info.get("connectSleep"); if (val != null) { long millis = Long.parseLong(val.toString()); try { Thread.sleep(millis); } catch (InterruptedException e) { // skip } } } MockConnection conn = createMockConnection(this, url, info); if (getLog().isDebugEnabled()) { getLog().debug("connect, url " + url + ", id " + conn.getId()); } if (url == null) { connectCount.incrementAndGet(); connections.add(conn); return conn; } if (url.startsWith(prefix)) { String catalog = url.substring(prefix.length()); conn.setCatalog(catalog); connectCount.incrementAndGet(); connections.add(conn); return conn; } if (url.startsWith(mockPrefix)) { String catalog = url.substring(mockPrefix.length()); conn.setCatalog(catalog); connectCount.incrementAndGet(); connections.add(conn); return conn; } return null; } @Override public boolean acceptsURL(String url) throws SQLException { if (url == null) { return false; } return url.startsWith(prefix) || url.startsWith(mockPrefix); } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return null; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public boolean jdbcCompliant() { return true; } public MockResultSet createMockResultSet(MockStatementBase stmt) { return new MockResultSet(stmt); } public ResultSet executeQuery(MockStatementBase stmt, String sql) throws SQLException { if (logExecuteQueryEnable && getLog().isDebugEnabled()) { getLog().debug("executeQuery " + sql); } MockConnection conn = stmt.getConnection(); long idleTimeMillis = System.currentTimeMillis() - conn.getLastActiveTimeMillis(); if (idleTimeMillis >= this.idleTimeCount) { throw new SQLException("connection is idle time count"); } conn.setLastActiveTimeMillis(System.currentTimeMillis()); handleSleep(conn); if ("SELECT value FROM _int_1000_".equalsIgnoreCase(sql)) { MockResultSet rs = createMockResultSet(stmt); for (int i = 0; i < 1000; ++i) { rs.getRows().add(new Object[]{i}); } return rs; } return this.executeHandler.executeQuery(stmt, sql); } public void handleSleep(MockConnection conn) { if (conn != null) { conn.handleSleep(); } } public ResultSet createResultSet(MockPreparedStatement stmt) { MockResultSet rs = new MockResultSet(stmt); String sql = stmt.getSql(); if ("SELECT 1".equalsIgnoreCase(sql)) { rs.getRows().add(new Object[]{1}); } else if ("SELECT NOW()".equalsIgnoreCase(sql)) { rs.getRows().add(new Object[]{new java.sql.Timestamp(System.currentTimeMillis())}); } else if ("SELECT ?".equalsIgnoreCase(sql)) { rs.getRows().add(new Object[]{stmt.getParameters().get(0)}); } return rs; } protected Clob createClob(MockConnection conn) throws SQLException { return new MockClob(); } protected Blob createBlob(MockConnection conn) throws SQLException { return new MockBlob(); } protected NClob createNClob(MockConnection conn) throws SQLException { return new MockNClob(); } protected SQLXML createSQLXML(MockConnection conn) throws SQLException { return new MockSQLXML(); } public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } public MockConnection createMockConnection(MockDriver driver, String url, Properties connectProperties) { return new MockConnection(this, url, connectProperties); } public MockPreparedStatement createMockPreparedStatement(MockConnection conn, String sql) { return new MockPreparedStatement(conn, sql); } public MockStatement createMockStatement(MockConnection conn) { return new MockStatement(conn); } public MockCallableStatement createMockCallableStatement(MockConnection conn, String sql) { return new MockCallableStatement(conn, sql); } }
MockDriver
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/DeleteJobAction.java
{ "start": 1194, "end": 4260 }
class ____ extends AcknowledgedRequest<Request> { private String jobId; private boolean force; /** * Should this task store its result? */ private boolean shouldStoreResult; /** * Should user added annotations be removed when the job is deleted? */ private boolean deleteUserAnnotations; public Request(String jobId) { super(TRAPPY_IMPLICIT_DEFAULT_MASTER_NODE_TIMEOUT, DEFAULT_ACK_TIMEOUT); this.jobId = ExceptionsHelper.requireNonNull(jobId, Job.ID.getPreferredName()); } public Request(StreamInput in) throws IOException { super(in); jobId = in.readString(); force = in.readBoolean(); if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_7_0)) { deleteUserAnnotations = in.readBoolean(); } else { deleteUserAnnotations = false; } } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public boolean isForce() { return force; } public void setForce(boolean force) { this.force = force; } /** * Should this task store its result after it has finished? */ public void setShouldStoreResult(boolean shouldStoreResult) { this.shouldStoreResult = shouldStoreResult; } @Override public boolean getShouldStoreResult() { return shouldStoreResult; } public void setDeleteUserAnnotations(boolean deleteUserAnnotations) { this.deleteUserAnnotations = deleteUserAnnotations; } public boolean getDeleteUserAnnotations() { return deleteUserAnnotations; } @Override public String getDescription() { return DELETION_TASK_DESCRIPTION_PREFIX + jobId; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(jobId); out.writeBoolean(force); if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_7_0)) { out.writeBoolean(deleteUserAnnotations); } } @Override public int hashCode() { return Objects.hash(jobId, force, deleteUserAnnotations); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || obj.getClass() != getClass()) { return false; } DeleteJobAction.Request other = (DeleteJobAction.Request) obj; return Objects.equals(jobId, other.jobId) && Objects.equals(force, other.force) && Objects.equals(deleteUserAnnotations, other.deleteUserAnnotations); } } }
Request
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/geogrid/GeoTileBoundedPredicate.java
{ "start": 942, "end": 4609 }
class ____ { private final boolean crossesDateline; private final long maxTiles; private final int precision, leftX, rightX, minY, maxY; public GeoTileBoundedPredicate(int precision, GeoBoundingBox bbox) { this.crossesDateline = bbox.right() < bbox.left(); this.precision = precision; if (bbox.bottom() > GeoTileUtils.NORMALIZED_LATITUDE_MASK || bbox.top() < GeoTileUtils.NORMALIZED_NEGATIVE_LATITUDE_MASK) { // this makes validTile() always return false leftX = rightX = minY = maxY = -1; maxTiles = 0; } else { final int tiles = 1 << precision; // compute minX, minY final int minX = GeoTileUtils.getXTile(bbox.left(), tiles); final int minY = GeoTileUtils.getYTile(bbox.top(), tiles); final Rectangle minTile = GeoTileUtils.toBoundingBox(minX, minY, precision); // touching tiles are excluded, they need to share at least one interior point this.leftX = encodeLongitude(minTile.getMaxX()) == encodeLongitude(bbox.left()) ? minX + 1 : minX; this.minY = encodeLatitude(minTile.getMinY()) == encodeLatitude(bbox.top()) ? minY + 1 : minY; // compute maxX, maxY final int maxX = GeoTileUtils.getXTile(bbox.right(), tiles); final int maxY = GeoTileUtils.getYTile(bbox.bottom(), tiles); final Rectangle maxTile = GeoTileUtils.toBoundingBox(maxX, maxY, precision); // touching tiles are excluded, they need to share at least one interior point this.rightX = encodeLongitude(maxTile.getMinX()) == encodeLongitude(bbox.right()) ? maxX : maxX + 1; this.maxY = encodeLatitude(maxTile.getMaxY()) == encodeLatitude(bbox.bottom()) ? maxY : maxY + 1; if (crossesDateline) { this.maxTiles = ((long) tiles + this.rightX - this.leftX) * (this.maxY - this.minY); } else { this.maxTiles = (long) (this.rightX - this.leftX) * (this.maxY - this.minY); } } } /** Does the provided bounds crosses the dateline */ public boolean crossesDateline() { return crossesDateline; } /** The left bound on geotile coordinates */ public int leftX() { return leftX; } /** The right bound on geotile coordinates */ public int rightX() { return rightX; } /** The bottom bound on geotile coordinates */ public int minY() { return minY; } /** The top bound on geotile coordinates */ public int maxY() { return maxY; } /** Check if the provided tile at the provided level intersects with the provided bounds. The provided precision must be * lower or equal to the precision provided in the constructor. */ public boolean validTile(int x, int y, int precision) { assert this.precision >= precision : "input precision bigger than this predicate precision"; // compute number of splits at precision final int splits = 1 << this.precision - precision; final int yMin = y * splits; if (maxY > yMin && minY < yMin + splits) { final int xMin = x * splits; if (crossesDateline) { return rightX > xMin || leftX < xMin + splits; } else { return rightX > xMin && leftX < xMin + splits; } } return false; } /** * Total number of tiles intersecting this bounds at the precision provided in the constructor. */ public long getMaxTiles() { return maxTiles; } }
GeoTileBoundedPredicate
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/BasicTypeSerializerUpgradeTestSpecifications.java
{ "start": 26634, "end": 27079 }
class ____ implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<NullValue> { @Override public TypeSerializer<NullValue> createPriorSerializer() { return NullValueSerializer.INSTANCE; } @Override public NullValue createTestData() { return NullValue.getInstance(); } } /** NullValueSerializerVerifier. */ public static final
NullValueSerializerSetup
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java
{ "start": 12653, "end": 13156 }
class ____ { private long deadline = 5000; @Deprecated @InlineMe(replacement = "this.millis(millis)") public void setDeadline(long millis) { millis(millis); } public void millis(long millis) { this.deadline = millis; } } """) .expectUnchanged() .addInputLines( "Caller.java", """ public final
Client
java
apache__flink
flink-table/flink-sql-client/src/test/java/org/apache/flink/table/client/cli/parser/SqlClientHighlighterTest.java
{ "start": 1572, "end": 18626 }
class ____ { @ParameterizedTest @ValueSource( strings = { "select", "join", "match_recognize", "Select", "wHeRe", "FroM", "view", "temporary" }) void keywordsTest(String keyword) { applyTestFor(AttributedStringTestSpecBuilder::appendKeyword, keyword, null); applyTestFor(AttributedStringTestSpecBuilder::appendKeyword, keyword, SqlDialect.HIVE); applyTestFor(AttributedStringTestSpecBuilder::appendKeyword, keyword, SqlDialect.DEFAULT); } @ParameterizedTest @ValueSource( strings = { "-- one line comment", "--select", "/* \"''\"", "/*", "/*/*/", "/*/ this is a comment", "--", "--\n/*", "/* hello\n'wor'ld*/", "/*\"-- \"values*/", "/*\"--;\n FROM*/", "/*SELECT'''a\n'AS\n`````b``c`\nFROM t*/" }) void commentsTest(String comment) { applyTestFor(AttributedStringTestSpecBuilder::appendComment, comment, null); applyTestFor(AttributedStringTestSpecBuilder::appendComment, comment, SqlDialect.HIVE); applyTestFor(AttributedStringTestSpecBuilder::appendComment, comment, SqlDialect.DEFAULT); } @ParameterizedTest @ValueSource( strings = { "/*+ this is a hint*/", "/*+ select*/", "/*+ \"''\"*/", "/*+", "/*+/ this is a part of a hint", "/*+ hello\n'wor'ld*/", "/*+\"-- \"values*/", "/*+\"--;\n FROM*/" }) void hintsTest(String hint) { applyTestFor(AttributedStringTestSpecBuilder::appendHint, hint, null); applyTestFor(AttributedStringTestSpecBuilder::appendHint, hint, SqlDialect.HIVE); applyTestFor(AttributedStringTestSpecBuilder::appendHint, hint, SqlDialect.DEFAULT); } @ParameterizedTest @ValueSource( strings = { "'", "''", "'''", "''''", "'\\'", "'\\\\'", "'from'", "'''from'", "'''''where'", "'''''where'''", "'test ` \" \n''select'", "'/* '", "'''-- '", "'\n \n'" }) void quotedTest(String quotedText) { applyTestFor(AttributedStringTestSpecBuilder::appendQuoted, quotedText, null); applyTestFor(AttributedStringTestSpecBuilder::appendQuoted, quotedText, SqlDialect.HIVE); applyTestFor(AttributedStringTestSpecBuilder::appendQuoted, quotedText, SqlDialect.DEFAULT); } @ParameterizedTest @ValueSource(strings = {"select1", "test", "_from", "12", "hello world!", "", " ", "\t", "\n"}) void sqlNonKeywordTest(String nonKeyword) { applyTestFor(AttributedStringTestSpecBuilder::append, nonKeyword, SqlDialect.HIVE); applyTestFor(AttributedStringTestSpecBuilder::append, nonKeyword, SqlDialect.DEFAULT); applyTestFor(AttributedStringTestSpecBuilder::append, nonKeyword, null); } @ParameterizedTest @ValueSource( strings = { "\"", "\"\"", "\"\"\"test\"", "\"\"\"\"", "\"\"\"\"\"\"", "\"\\\"", "\"\\\\\"", "\"from\"", "\"''\"", "\"test '' \n\"\"select\"", "\"/* \"", "\"-- \"", "\"\n \n\"" }) void hiveSqlIdentifierTest(String sqlIdentifier) { // For non Hive dialect this is not sql identifier style applyTestFor( AttributedStringTestSpecBuilder::appendSqlIdentifier, sqlIdentifier, SqlDialect.HIVE); } @ParameterizedTest @ValueSource( strings = { "`", "``", "```", "````", "`\\`", "`\\\\`", "`select * from`", "`''`", "`hello '' ''select`", "`/* `", "`-- `", "`\n \n`" }) void sqlIdentifierTest(String sqlIdentifier) { // For Hive dialect this is not sql identifier style applyTestFor( AttributedStringTestSpecBuilder::appendSqlIdentifier, sqlIdentifier, SqlDialect.DEFAULT); applyTestFor(AttributedStringTestSpecBuilder::appendSqlIdentifier, sqlIdentifier, null); } private void applyTestFor( BiFunction<AttributedStringTestSpecBuilder, String, AttributedStringTestSpecBuilder> biFunction, String sql, SqlDialect dialect) { for (SyntaxHighlightStyle.BuiltInStyle style : SyntaxHighlightStyle.BuiltInStyle.values()) { SqlClientHighlighterTestSpec spec = forSql( sql, style1 -> biFunction.apply(withStyle(style1.getHighlightStyle()), sql)); assertThat( SqlClientSyntaxHighlighter.getHighlightedOutput( spec.sql, style.getHighlightStyle(), dialect) .toAnsi()) .as("sql: " + spec.sql + ", style: " + style + ", dialect: " + dialect) .isEqualTo(spec.getExpected(style)); } } @ParameterizedTest @MethodSource("allDialectsSpecFunctionProvider") void complexTestForAllDialects(SqlClientHighlighterTestSpec spec) { for (SyntaxHighlightStyle.BuiltInStyle style : SyntaxHighlightStyle.BuiltInStyle.values()) { for (SqlDialect dialect : SqlDialect.values()) { verifyHighlighting(spec.sql, style, dialect, spec.getExpected(style)); } } } @ParameterizedTest @MethodSource("hiveDialectsSpecFunctionProvider") void complexTestForHiveDialect(SqlClientHighlighterTestSpec spec) { for (SyntaxHighlightStyle.BuiltInStyle style : SyntaxHighlightStyle.BuiltInStyle.values()) { verifyHighlighting(spec.sql, style, SqlDialect.HIVE, spec.getExpected(style)); } } @ParameterizedTest @MethodSource("defaultDialectsSpecFunctionProvider") void complexTestForDefaultDialect(SqlClientHighlighterTestSpec spec) { for (SyntaxHighlightStyle.BuiltInStyle style : SyntaxHighlightStyle.BuiltInStyle.values()) { verifyHighlighting(spec.sql, style, SqlDialect.DEFAULT, spec.getExpected(style)); } } private static void verifyHighlighting( String sql, SyntaxHighlightStyle.BuiltInStyle style, SqlDialect dialect, String expected) { assertThat( SqlClientSyntaxHighlighter.getHighlightedOutput( sql, style.getHighlightStyle(), dialect) .toAnsi()) .as("SQL: " + sql + "\nDialect: " + dialect + "\nStyle: " + style) .isEqualTo(expected); } static Stream<SqlClientHighlighterTestSpec> allDialectsSpecFunctionProvider() { return Stream.of( forSql( "SELECT '\\';", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .append(" ") .appendQuoted("'\\'") .append(";")), forSql( "SELECT.FROM%JOIN;", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .append(".") .appendKeyword("FROM") .append("%") .appendKeyword("JOIN") .append(";")), forSql( "SELECT '''';", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .append(" ") .appendQuoted("''''") .append(";"))); } static Stream<SqlClientHighlighterTestSpec> defaultDialectsSpecFunctionProvider() { return Stream.of( forSql( "SELECT 123 AS `\\`;", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .append(" 123 ") .appendKeyword("AS") .append(" ") .appendSqlIdentifier("`\\`") .append(";")), forSql( "SELECT 1 AS ````;", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .append(" 1 ") .appendKeyword("AS") .append(" ") .appendSqlIdentifier("````") .append(";")), forSql( "SELECT'''''1''from'''AS```1``where``group`;", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .appendQuoted("'''''1''from'''") .appendKeyword("AS") .appendSqlIdentifier("```1``where``group`") .append(";")), forSql( // query without spaces "SELECT/*+hint*/'abc'--one-line-comment\nAS`field`/*\ncomment\n*/;", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .appendHint("/*+hint*/") .appendQuoted("'abc'") .appendComment("--one-line-comment\n") .appendKeyword("AS") .appendSqlIdentifier("`field`") .appendComment("/*\ncomment\n*/") .append(";")), forSql( // query without spaces with double quotes "SELECT/*+hint*/'abc'--one-line-comment\nAS\"field\"/*\ncomment\n*/;", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .appendHint("/*+hint*/") .appendQuoted("'abc'") .appendComment("--one-line-comment\n") .appendKeyword("AS") .append("\"field\"") .appendComment("/*\ncomment\n*/") .append(";")), forSql( // invalid query however highlighting should keep working "SELECT/*\n * / \n \"q\" \nfrom dual\n where\n 1 = 1", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .appendComment( "/*\n * / \n \"q\" \nfrom dual\n where\n 1 = 1")), forSql( // invalid query (wrong symbols at the end) // however highlighting should keep working "SELECT 1 AS`one`FROM mytable.tfrom//", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .append(" 1 ") .appendKeyword("AS") .appendSqlIdentifier("`one`") .appendKeyword("FROM") .append(" mytable.tfrom//"))); } static Stream<SqlClientHighlighterTestSpec> hiveDialectsSpecFunctionProvider() { return Stream.of( forSql( "SELECT 1 AS \"\"\"\";", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .append(" 1 ") .appendKeyword("AS") .append(" ") .appendSqlIdentifier("\"\"\"\"") .append(";")), forSql( // query without spaces "SELECT/*+hint*/'abc'--one-line-comment\nAS\"field\"/*\ncomment\n*/;", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .appendHint("/*+hint*/") .appendQuoted("'abc'") .appendComment("--one-line-comment\n") .appendKeyword("AS") .appendSqlIdentifier("\"field\"") .appendComment("/*\ncomment\n*/") .append(";")), forSql( // query without spaces and ticks "SELECT/*+hint*/'abc'--one-line-comment\nAS`joinq`.afrom/*\ncomment\n*/;", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .appendHint("/*+hint*/") .appendQuoted("'abc'") .appendComment("--one-line-comment\n") .appendKeyword("AS") .append("`joinq`") .append(".afrom") .appendComment("/*\ncomment\n*/") .append(";")), forSql( // invalid query however highlighting should keep working "SELECT/*\n * / \n \"q\" \nfrom dual\n where\n 1 = 1", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .appendComment( "/*\n * / \n \"q\" \nfrom dual\n where\n 1 = 1")), forSql( // invalid query (wrong symbols at the end) // however highlighting should keep working "SELECT 1 AS\"one\"FROM mytable.tfrom//", style -> withStyle(style.getHighlightStyle()) .appendKeyword("SELECT") .append(" 1 ") .appendKeyword("AS") .appendSqlIdentifier("\"one\"") .appendKeyword("FROM") .append(" mytable.tfrom//"))); } static
SqlClientHighlighterTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/domain/SqmAnyValuedSimplePath.java
{ "start": 657, "end": 3420 }
class ____<T> extends AbstractSqmSimplePath<T> { public SqmAnyValuedSimplePath( NavigablePath navigablePath, SqmPathSource<T> referencedPathSource, SqmPath<?> lhs, NodeBuilder nodeBuilder) { super( navigablePath, referencedPathSource, lhs, nodeBuilder ); assert referencedPathSource.getPathType() instanceof AnyMappingDomainType; } @SuppressWarnings("unused") public SqmAnyValuedSimplePath( NavigablePath navigablePath, SqmPathSource<T> referencedPathSource, SqmPath<?> lhs, @Nullable String explicitAlias, NodeBuilder nodeBuilder) { super( navigablePath, referencedPathSource, lhs, explicitAlias, nodeBuilder ); assert referencedPathSource.getPathType() instanceof AnyMappingDomainType; } @Override public SqmAnyValuedSimplePath<T> copy(SqmCopyContext context) { final SqmAnyValuedSimplePath<T> existing = context.getCopy( this ); if ( existing != null ) { return existing; } final SqmPath<?> lhsCopy = getLhs().copy( context ); final SqmAnyValuedSimplePath<T> path = context.registerCopy( this, new SqmAnyValuedSimplePath<>( getNavigablePathCopy( lhsCopy ), getModel(), lhsCopy, getExplicitAlias(), nodeBuilder() ) ); copyTo( path, context ); return path; } @Override public <S extends T> SqmTreatedPath<T, S> treatAs(Class<S> treatJavaType) { throw new UnsupportedOperationException(); } @Override public <S extends T> SqmTreatedPath<T, S> treatAs(EntityDomainType<S> treatTarget) { throw new UnsupportedOperationException(); } @Override public <S extends T> SqmTreatedPath<T, S> treatAs(Class<S> treatJavaType, @Nullable String alias) { throw new UnsupportedOperationException(); } @Override public <S extends T> SqmTreatedPath<T, S> treatAs(EntityDomainType<S> treatTarget, @Nullable String alias) { throw new UnsupportedOperationException(); } @Override public <S extends T> SqmTreatedPath<T, S> treatAs(Class<S> treatJavaType, @Nullable String alias, boolean fetch) { throw new UnsupportedOperationException(); } @Override public <S extends T> SqmTreatedPath<T, S> treatAs(EntityDomainType<S> treatTarget, @Nullable String alias, boolean fetch) { throw new UnsupportedOperationException(); } @Override public SqmPath<?> resolvePathPart( String name, boolean isTerminal, SqmCreationState creationState) { final SqmPath<?> sqmPath = get( name, true ); creationState.getProcessingStateStack().getCurrent().getPathRegistry().register( sqmPath ); return sqmPath; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Visitation @Override public <X> X accept(SemanticQueryWalker<X> walker) { return walker.visitAnyValuedValuedPath( this ); } }
SqmAnyValuedSimplePath
java
spring-projects__spring-security
docs/src/test/java/org/springframework/security/docs/features/authentication/authenticationpasswordstoragebcrypt/BCryptPasswordEncoderUsage.java
{ "start": 229, "end": 586 }
class ____ { public void testBCryptPasswordEncoder() { // tag::bcryptPasswordEncoder[] // Create an encoder with strength 16 BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16); String result = encoder.encode("myPassword"); assertTrue(encoder.matches("myPassword", result)); // end::bcryptPasswordEncoder[] } }
BCryptPasswordEncoderUsage
java
quarkusio__quarkus
integration-tests/main/src/test/java/io/quarkus/it/main/RemovedResourceTestCase.java
{ "start": 163, "end": 314 }
class ____ { @Test public void testRemovedResource() { RestAssured.get("/removed").then().statusCode(404); } }
RemovedResourceTestCase
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/support/springfox/JsonValueTest.java
{ "start": 204, "end": 449 }
class ____ extends TestCase { public void test_0() throws Exception { Json json = new Json("\"{\"id\":1001\"}"); String text = JSON.toJSONString(json); Assert.assertEquals("\"{\"id\":1001\"}", text); } }
JsonValueTest
java
apache__camel
components/camel-ai/camel-langchain4j-tools/src/main/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsConsumer.java
{ "start": 984, "end": 1164 }
class ____ extends DefaultConsumer { public LangChain4jToolsConsumer(Endpoint endpoint, Processor processor) { super(endpoint, processor); } }
LangChain4jToolsConsumer
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/web/context/reactive/GenericReactiveWebApplicationContextTests.java
{ "start": 916, "end": 1330 }
class ____ { @Test void getResourceByPath() throws Exception { GenericReactiveWebApplicationContext context = new GenericReactiveWebApplicationContext(); Resource rootResource = context.getResourceByPath("/"); assertThat(rootResource.exists()).isFalse(); assertThat(rootResource.createRelative("application.properties").exists()).isFalse(); context.close(); } }
GenericReactiveWebApplicationContextTests
java
spring-projects__spring-framework
spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletRequest.java
{ "start": 3289, "end": 10095 }
class ____ implements HttpServletRequest { private static final String HTTP = "http"; private static final String HTTPS = "https"; private static final String CHARSET_PREFIX = "charset="; private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); /** * Date formats as specified in the HTTP RFC. * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.1">Section 7.1.1.1 of RFC 7231</a> */ private static final String[] DATE_FORMATS = new String[] { "EEE, dd MMM yyyy HH:mm:ss zzz", "EEE, dd-MMM-yy HH:mm:ss zzz", "EEE MMM dd HH:mm:ss yyyy" }; // --------------------------------------------------------------------- // Public constants // --------------------------------------------------------------------- /** * The default protocol: 'HTTP/1.1'. * @since 4.3.7 */ public static final String DEFAULT_PROTOCOL = "HTTP/1.1"; /** * The default scheme: 'http'. * @since 4.3.7 */ public static final String DEFAULT_SCHEME = HTTP; /** * The default server address: '127.0.0.1'. */ public static final String DEFAULT_SERVER_ADDR = "127.0.0.1"; /** * The default server name: 'localhost'. */ public static final String DEFAULT_SERVER_NAME = "localhost"; /** * The default server port: '80'. */ public static final int DEFAULT_SERVER_PORT = 80; /** * The default remote address: '127.0.0.1'. */ public static final String DEFAULT_REMOTE_ADDR = "127.0.0.1"; /** * The default remote host: 'localhost'. */ public static final String DEFAULT_REMOTE_HOST = "localhost"; // --------------------------------------------------------------------- // Lifecycle properties // --------------------------------------------------------------------- private final ServletContext servletContext; private boolean active = true; // --------------------------------------------------------------------- // ServletRequest properties // --------------------------------------------------------------------- private final Map<String, Object> attributes = new LinkedHashMap<>(); private @Nullable String characterEncoding; private byte @Nullable [] content; private @Nullable String contentType; private @Nullable ServletInputStream inputStream; private @Nullable BufferedReader reader; private final Map<String, String[]> parameters = new LinkedHashMap<>(16); private String protocol = DEFAULT_PROTOCOL; private String scheme = DEFAULT_SCHEME; private String serverName = DEFAULT_SERVER_NAME; private int serverPort = DEFAULT_SERVER_PORT; private String remoteAddr = DEFAULT_REMOTE_ADDR; private String remoteHost = DEFAULT_REMOTE_HOST; /** List of locales in descending order. */ private final LinkedList<Locale> locales = new LinkedList<>(); private boolean secure = false; private int remotePort = DEFAULT_SERVER_PORT; private String localName = DEFAULT_SERVER_NAME; private String localAddr = DEFAULT_SERVER_ADDR; private int localPort = DEFAULT_SERVER_PORT; private boolean asyncStarted = false; private boolean asyncSupported = false; private @Nullable MockAsyncContext asyncContext; private DispatcherType dispatcherType = DispatcherType.REQUEST; // --------------------------------------------------------------------- // HttpServletRequest properties // --------------------------------------------------------------------- private @Nullable String authType; private @Nullable Cookie[] cookies; private final Map<String, HeaderValueHolder> headers = new LinkedCaseInsensitiveMap<>(); private @Nullable String method; private @Nullable String pathInfo; private String contextPath = ""; private @Nullable String queryString; private @Nullable String remoteUser; private final Set<String> userRoles = new HashSet<>(); private @Nullable Principal userPrincipal; private @Nullable String requestedSessionId; private @Nullable String uriTemplate; private @Nullable String requestURI; private String servletPath = ""; private @Nullable HttpSession session; private boolean requestedSessionIdValid = true; private boolean requestedSessionIdFromCookie = true; private boolean requestedSessionIdFromURL = false; private final MultiValueMap<String, Part> parts = new LinkedMultiValueMap<>(); private @Nullable HttpServletMapping httpServletMapping; // --------------------------------------------------------------------- // Constructors // --------------------------------------------------------------------- /** * Create a new {@code MockHttpServletRequest} with a default * {@link MockServletContext}. * @see #MockHttpServletRequest(ServletContext, String, String) */ public MockHttpServletRequest() { this(null, "", ""); } /** * Create a new {@code MockHttpServletRequest} with a default * {@link MockServletContext}. * @param method the request method (may be {@code null}) * @param requestURI the request URI (may be {@code null}) * @see #setMethod * @see #setRequestURI * @see #MockHttpServletRequest(ServletContext, String, String) */ public MockHttpServletRequest(@Nullable String method, @Nullable String requestURI) { this(null, method, requestURI); } /** * Create a new {@code MockHttpServletRequest} with the supplied {@link ServletContext}. * @param servletContext the ServletContext that the request runs in * (may be {@code null} to use a default {@link MockServletContext}) * @see #MockHttpServletRequest(ServletContext, String, String) */ public MockHttpServletRequest(@Nullable ServletContext servletContext) { this(servletContext, "", ""); } /** * Create a new {@code MockHttpServletRequest} with the supplied {@link ServletContext}, * {@code method}, and {@code requestURI}. * <p>The preferred locale will be set to {@link Locale#ENGLISH}. * @param servletContext the ServletContext that the request runs in (may be * {@code null} to use a default {@link MockServletContext}) * @param method the request method (may be {@code null}) * @param requestURI the request URI (may be {@code null}) * @see #setMethod * @see #setRequestURI * @see #setPreferredLocales * @see MockServletContext */ public MockHttpServletRequest(@Nullable ServletContext servletContext, @Nullable String method, @Nullable String requestURI) { this.servletContext = (servletContext != null ? servletContext : new MockServletContext()); this.method = method; this.requestURI = requestURI; this.locales.add(Locale.ENGLISH); } // --------------------------------------------------------------------- // Lifecycle methods // --------------------------------------------------------------------- /** * Return the ServletContext that this request is associated with. (Not * available in the standard HttpServletRequest
MockHttpServletRequest
java
apache__camel
components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/map/HazelcastMapProducer.java
{ "start": 1452, "end": 8814 }
class ____ extends HazelcastDefaultProducer { private final IMap<Object, Object> cache; public HazelcastMapProducer(HazelcastInstance hazelcastInstance, HazelcastMapEndpoint endpoint, String cacheName) { super(endpoint); this.cache = hazelcastInstance.getMap(cacheName); } @Override public void process(Exchange exchange) throws Exception { Map<String, Object> headers = exchange.getIn().getHeaders(); // GET header parameters Object oid = null; Object ovalue = null; Object ttl = null; Object ttlUnit = null; String query = null; if (headers.containsKey(HazelcastConstants.OBJECT_ID)) { oid = headers.get(HazelcastConstants.OBJECT_ID); } if (headers.containsKey(HazelcastConstants.OBJECT_VALUE)) { ovalue = headers.get(HazelcastConstants.OBJECT_VALUE); } if (headers.containsKey(HazelcastConstants.TTL_VALUE)) { ttl = headers.get(HazelcastConstants.TTL_VALUE); } if (headers.containsKey(HazelcastConstants.TTL_UNIT)) { ttlUnit = headers.get(HazelcastConstants.TTL_UNIT); } if (headers.containsKey(HazelcastConstants.QUERY)) { query = (String) headers.get(HazelcastConstants.QUERY); } final HazelcastOperation operation = lookupOperation(exchange); switch (operation) { case PUT: if (ObjectHelper.isEmpty(ttl) && ObjectHelper.isEmpty(ttlUnit)) { this.put(oid, exchange); } else { this.put(oid, ttl, ttlUnit, exchange); } break; case PUT_IF_ABSENT: if (ObjectHelper.isEmpty(ttl) && ObjectHelper.isEmpty(ttlUnit)) { this.putIfAbsent(oid, exchange); } else { this.putIfAbsent(oid, ttl, ttlUnit, exchange); } break; case GET: this.get(oid, exchange); break; case GET_ALL: this.getAll(oid, exchange); break; case GET_KEYS: this.getKeys(exchange); break; case CONTAINS_KEY: this.containsKey(oid, exchange); break; case CONTAINS_VALUE: this.containsValue(exchange); break; case DELETE: this.delete(oid); break; case UPDATE: if (ObjectHelper.isEmpty(ovalue)) { this.update(oid, exchange); } else { this.update(oid, ovalue, exchange); } break; case QUERY: this.query(query, exchange); break; case CLEAR: this.clear(); break; case EVICT: this.evict(oid); break; case EVICT_ALL: this.evictAll(); break; default: throw new IllegalArgumentException( String.format("The value '%s' is not allowed for parameter '%s' on the MAP cache.", operation, HazelcastConstants.OPERATION)); } // finally copy headers HazelcastComponentHelper.copyHeaders(exchange); } /** * QUERY map with a sql like syntax (see http://www.hazelcast.com/) */ private void query(String query, Exchange exchange) { Collection<Object> result; if (ObjectHelper.isNotEmpty(query)) { result = this.cache.values(new SqlPredicate(query)); } else { result = this.cache.values(); } exchange.getMessage().setBody(result); } /** * UPDATE an object in your cache (the whole object will be replaced) */ private void update(Object oid, Exchange exchange) { Object body = exchange.getIn().getBody(); this.cache.lock(oid); this.cache.replace(oid, body); this.cache.unlock(oid); } /** * Replaces the entry for given id with a specific value in the body, only if currently mapped to a given value */ private void update(Object oid, Object ovalue, Exchange exchange) { Object body = exchange.getIn().getBody(); this.cache.lock(oid); this.cache.replace(oid, ovalue, body); this.cache.unlock(oid); } /** * remove an object from the cache */ private void delete(Object oid) { this.cache.remove(oid); } /** * find an object by the given id and give it back */ private void get(Object oid, Exchange exchange) { exchange.getMessage().setBody(this.cache.get(oid)); } /** * GET All objects and give it back */ private void getAll(Object oid, Exchange exchange) { exchange.getMessage().setBody(this.cache.getAll((Set<Object>) oid)); } /** * PUT a new object into the cache */ private void put(Object oid, Exchange exchange) { Object body = exchange.getIn().getBody(); this.cache.put(oid, body); } /** * PUT a new object into the cache with a specific time to live */ private void put(Object oid, Object ttl, Object ttlUnit, Exchange exchange) { Object body = exchange.getIn().getBody(); this.cache.put(oid, body, (long) ttl, (TimeUnit) ttlUnit); } /** * if the specified key is not already associated with a value, associate it with the given value. */ private void putIfAbsent(Object oid, Exchange exchange) { Object body = exchange.getIn().getBody(); this.cache.putIfAbsent(oid, body); } /** * Puts an entry into this map with a given ttl (time to live) value if the specified key is not already associated * with a value. */ private void putIfAbsent(Object oid, Object ttl, Object ttlUnit, Exchange exchange) { Object body = exchange.getIn().getBody(); this.cache.putIfAbsent(oid, body, (long) ttl, (TimeUnit) ttlUnit); } /** * Clear all the entries */ private void clear() { this.cache.clear(); } /** * Eviction operation for a specific key */ private void evict(Object oid) { this.cache.evict(oid); } /** * Evict All operation */ private void evictAll() { this.cache.evictAll(); } /** * Check for a specific key in the cache and return true if it exists or false otherwise */ private void containsKey(Object oid, Exchange exchange) { exchange.getMessage().setBody(this.cache.containsKey(oid)); } /** * Check for a specific value in the cache and return true if it exists or false otherwise */ private void containsValue(Exchange exchange) { Object body = exchange.getIn().getBody(); exchange.getMessage().setBody(this.cache.containsValue(body)); } /** * GET keys set of objects and give it back */ private void getKeys(Exchange exchange) { exchange.getMessage().setBody(this.cache.keySet()); } }
HazelcastMapProducer
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GuavaEventBusEndpointBuilderFactory.java
{ "start": 12638, "end": 13400 }
class ____ * superclasses of eventClass. Null value of this option is equal to * setting it to the java.lang.Object i.e. the consumer will capture all * messages incoming to the event bus. This option cannot be used * together with listenerInterface option. * * The option will be converted to a * <code>java.lang.Class&lt;java.lang.Object&gt;</code> type. * * Group: common * * @param eventClass the value to set * @return the dsl builder */ default GuavaEventBusEndpointProducerBuilder eventClass(String eventClass) { doSetProperty("eventClass", eventClass); return this; } /** * The
and
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/seqno/ReplicationTracker.java
{ "start": 33349, "end": 78087 }
class ____ implements Writeable { /** * the last local checkpoint information that we have for this shard. All operations up to this point are properly fsynced to disk. */ long localCheckpoint; /** * the last global checkpoint information that we have for this shard. This is the global checkpoint that's fsynced to disk on the * respective shard, and all operations up to this point are properly fsynced to disk as well. */ long globalCheckpoint; /** * whether this shard is treated as in-sync and thus contributes to the global checkpoint calculation */ boolean inSync; /** * whether this shard is tracked in the replication group, i.e., should receive document updates from the primary. */ boolean tracked; public CheckpointState(long localCheckpoint, long globalCheckpoint, boolean inSync, boolean tracked) { this.localCheckpoint = localCheckpoint; this.globalCheckpoint = globalCheckpoint; this.inSync = inSync; this.tracked = tracked; } public CheckpointState(StreamInput in) throws IOException { this.localCheckpoint = in.readZLong(); this.globalCheckpoint = in.readZLong(); this.inSync = in.readBoolean(); this.tracked = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeZLong(localCheckpoint); out.writeZLong(globalCheckpoint); out.writeBoolean(inSync); out.writeBoolean(tracked); } /** * Returns a full copy of this object */ public CheckpointState copy() { return new CheckpointState(localCheckpoint, globalCheckpoint, inSync, tracked); } public long getLocalCheckpoint() { return localCheckpoint; } public long getGlobalCheckpoint() { return globalCheckpoint; } @Override public String toString() { return "LocalCheckpointState{" + "localCheckpoint=" + localCheckpoint + ", globalCheckpoint=" + globalCheckpoint + ", inSync=" + inSync + ", tracked=" + tracked + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CheckpointState that = (CheckpointState) o; if (localCheckpoint != that.localCheckpoint) return false; if (globalCheckpoint != that.globalCheckpoint) return false; if (inSync != that.inSync) return false; return tracked == that.tracked; } @Override public int hashCode() { int result = Long.hashCode(localCheckpoint); result = 31 * result + Long.hashCode(globalCheckpoint); result = 31 * result + Boolean.hashCode(inSync); result = 31 * result + Boolean.hashCode(tracked); return result; } } /** * Get the local knowledge of the persisted global checkpoints for all in-sync allocation IDs. * * @return a map from allocation ID to the local knowledge of the persisted global checkpoint for that allocation ID */ public synchronized Map<String, Long> getInSyncGlobalCheckpoints() { assert primaryMode; assert handoffInProgress == false; // upper bound on the size return checkpoints.entrySet() .stream() .filter(e -> e.getValue().inSync) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().globalCheckpoint)); } /** * @return true iff any tracked global checkpoint for an in-sync copy lags behind our global checkpoint */ public synchronized boolean trackedGlobalCheckpointsNeedSync() { for (final var checkpointState : checkpoints.values()) { if (checkpointState.inSync && checkpointState.globalCheckpoint < globalCheckpoint) { return true; } } return false; } /** * Returns whether the replication tracker is in primary mode, i.e., whether the current shard is acting as primary from the point of * view of replication. */ public boolean isPrimaryMode() { return primaryMode; } /** * Returns the current operation primary term. * * @return the primary term */ public long getOperationPrimaryTerm() { return operationPrimaryTerm; } /** * Sets the current operation primary term. This method should be invoked only when no other operations are possible on the shard. That * is, either from the constructor of {@link IndexShard} or while holding all permits on the {@link IndexShard} instance. * * @param operationPrimaryTerm the new operation primary term */ public void setOperationPrimaryTerm(final long operationPrimaryTerm) { this.operationPrimaryTerm = operationPrimaryTerm; } /** * Returns whether the replication tracker has relocated away to another shard copy. */ public boolean isRelocated() { return relocated; } /** * Class invariant that should hold before and after every invocation of public methods on this class. As Java lacks implication * as a logical operator, many of the invariants are written under the form (!A || B), they should be read as (A implies B) however. */ private boolean invariant() { // local checkpoints only set during primary mode assert primaryMode || checkpoints.values().stream().allMatch(lcps -> lcps.localCheckpoint == SequenceNumbers.UNASSIGNED_SEQ_NO); // global checkpoints only set during primary mode assert primaryMode || checkpoints.values().stream().allMatch(cps -> cps.globalCheckpoint == SequenceNumbers.UNASSIGNED_SEQ_NO); // relocation handoff can only occur in primary mode assert handoffInProgress == false || primaryMode; // a relocated copy is not in primary mode assert relocated == false || primaryMode == false; // the current shard is marked as in-sync when the global checkpoint tracker operates in primary mode assert primaryMode == false || checkpoints.get(shardAllocationId).inSync; // the routing table and replication group is set when the global checkpoint tracker operates in primary mode assert primaryMode == false || (routingTable != null && replicationGroup != null) : "primary mode but routing table is " + routingTable + " and replication group is " + replicationGroup; // when in primary mode, the current allocation ID is the allocation ID of the primary or the relocation allocation ID assert primaryMode == false || (routingTable.primaryShard().allocationId().getId().equals(shardAllocationId) || routingTable.primaryShard().allocationId().getRelocationId().equals(shardAllocationId)); // during relocation handoff there are no entries blocking global checkpoint advancement assert handoffInProgress == false || pendingInSync.isEmpty() : "entries blocking global checkpoint advancement during relocation handoff: " + pendingInSync; // entries blocking global checkpoint advancement can only exist in primary mode and when not having a relocation handoff assert pendingInSync.isEmpty() || (primaryMode && handoffInProgress == false); // the computed global checkpoint is always up-to-date assert primaryMode == false || globalCheckpoint == computeGlobalCheckpoint(pendingInSync, checkpoints.values(), globalCheckpoint) : "global checkpoint is not up-to-date, expected: " + computeGlobalCheckpoint(pendingInSync, checkpoints.values(), globalCheckpoint) + " but was: " + globalCheckpoint; // when in primary mode, the global checkpoint is at most the minimum local checkpoint on all in-sync shard copies assert primaryMode == false || globalCheckpoint <= inSyncCheckpointStates(checkpoints, CheckpointState::getLocalCheckpoint, LongStream::min) : "global checkpoint [" + globalCheckpoint + "] " + "for primary mode allocation ID [" + shardAllocationId + "] " + "more than in-sync local checkpoints [" + checkpoints + "]"; // we have a routing table iff we have a replication group assert (routingTable == null) == (replicationGroup == null) : "routing table is " + routingTable + " but replication group is " + replicationGroup; assert replicationGroup == null || replicationGroup.equals(calculateReplicationGroup()) : "cached replication group out of sync: expected: " + calculateReplicationGroup() + " but was: " + replicationGroup; if (replicationGroup != null) { assert replicationGroup.getReplicationTargets().stream().allMatch(ShardRouting::isPromotableToPrimary) : "expected all replication target shards of the replication group to be promotable to primary"; assert replicationGroup.getSkippedShards().stream().allMatch(ShardRouting::isPromotableToPrimary) : "expected all skipped shards of the replication group to be promotable to primary"; } // all assigned shards from the routing table are tracked assert routingTable == null || checkpoints.keySet().containsAll(routingTable.getPromotableAllocationIds()) : "local checkpoints " + checkpoints + " not in-sync with routing table " + routingTable; for (Map.Entry<String, CheckpointState> entry : checkpoints.entrySet()) { // blocking global checkpoint advancement only happens for shards that are not in-sync assert pendingInSync.contains(entry.getKey()) == false || entry.getValue().inSync == false : "shard copy " + entry.getKey() + " blocks global checkpoint advancement but is in-sync"; // in-sync shard copies are tracked assert entry.getValue().inSync == false || entry.getValue().tracked : "shard copy " + entry.getKey() + " is in-sync but not tracked"; } // all pending in sync shards are tracked for (String aId : pendingInSync) { assert checkpoints.get(aId) != null : "aId [" + aId + "] is pending in sync but isn't tracked"; } if (primaryMode && indexSettings.isSoftDeleteEnabled() && hasAllPeerRecoveryRetentionLeases) { // all tracked shard copies have a corresponding peer-recovery retention lease for (final ShardRouting shardRouting : routingTable.assignedShards()) { if (shardRouting.isPromotableToPrimary() && checkpoints.get(shardRouting.allocationId().getId()).tracked) { assert retentionLeases.contains(getPeerRecoveryRetentionLeaseId(shardRouting)) : "no retention lease for tracked shard [" + shardRouting + "] in " + retentionLeases; assert PEER_RECOVERY_RETENTION_LEASE_SOURCE.equals( retentionLeases.get(getPeerRecoveryRetentionLeaseId(shardRouting)).source() ) : "incorrect source [" + retentionLeases.get(getPeerRecoveryRetentionLeaseId(shardRouting)).source() + "] for [" + shardRouting + "] in " + retentionLeases; } } } return true; } private static long inSyncCheckpointStates( final Map<String, CheckpointState> checkpoints, ToLongFunction<CheckpointState> function, Function<LongStream, OptionalLong> reducer ) { final OptionalLong value = reducer.apply( checkpoints.values().stream().filter(cps -> cps.inSync).mapToLong(function).filter(v -> v != SequenceNumbers.UNASSIGNED_SEQ_NO) ); return value.isPresent() ? value.getAsLong() : SequenceNumbers.UNASSIGNED_SEQ_NO; } public ReplicationTracker( final ShardId shardId, final String allocationId, final IndexSettings indexSettings, final long operationPrimaryTerm, final long globalCheckpoint, final LongConsumer onGlobalCheckpointUpdated, final LongSupplier currentTimeMillisSupplier, final BiConsumer<RetentionLeases, ActionListener<ReplicationResponse>> onSyncRetentionLeases, final Supplier<SafeCommitInfo> safeCommitInfoSupplier ) { this( shardId, allocationId, indexSettings, operationPrimaryTerm, globalCheckpoint, onGlobalCheckpointUpdated, currentTimeMillisSupplier, onSyncRetentionLeases, safeCommitInfoSupplier, x -> {} ); } /** * Initialize the global checkpoint service. The specified global checkpoint should be set to the last known global checkpoint, or * {@link SequenceNumbers#UNASSIGNED_SEQ_NO}. * * @param shardId the shard ID * @param allocationId the allocation ID * @param indexSettings the index settings * @param operationPrimaryTerm the current primary term * @param globalCheckpoint the last known global checkpoint for this shard, or {@link SequenceNumbers#UNASSIGNED_SEQ_NO} * @param onSyncRetentionLeases a callback when a new retention lease is created or an existing retention lease expires * @param onReplicationGroupUpdated a callback when the replica group changes */ public ReplicationTracker( final ShardId shardId, final String allocationId, final IndexSettings indexSettings, final long operationPrimaryTerm, final long globalCheckpoint, final LongConsumer onGlobalCheckpointUpdated, final LongSupplier currentTimeMillisSupplier, final BiConsumer<RetentionLeases, ActionListener<ReplicationResponse>> onSyncRetentionLeases, final Supplier<SafeCommitInfo> safeCommitInfoSupplier, final Consumer<ReplicationGroup> onReplicationGroupUpdated ) { super(shardId, indexSettings); assert globalCheckpoint >= SequenceNumbers.UNASSIGNED_SEQ_NO : "illegal initial global checkpoint: " + globalCheckpoint; this.shardAllocationId = allocationId; this.primaryMode = false; this.operationPrimaryTerm = operationPrimaryTerm; this.handoffInProgress = false; this.appliedClusterStateVersion = -1L; this.globalCheckpoint = globalCheckpoint; this.checkpoints = Maps.newMapWithExpectedSize(1 + indexSettings.getNumberOfReplicas()); this.onGlobalCheckpointUpdated = Objects.requireNonNull(onGlobalCheckpointUpdated); this.currentTimeMillisSupplier = Objects.requireNonNull(currentTimeMillisSupplier); this.onSyncRetentionLeases = Objects.requireNonNull(onSyncRetentionLeases); this.pendingInSync = new HashSet<>(); this.routingTable = null; this.replicationGroup = null; this.hasAllPeerRecoveryRetentionLeases = indexSettings.getIndexVersionCreated().onOrAfter(IndexVersions.V_7_6_0) || (indexSettings.isSoftDeleteEnabled() && indexSettings.getIndexVersionCreated().onOrAfter(IndexVersions.V_7_4_0) && indexSettings.getIndexMetadata().getState() == IndexMetadata.State.OPEN); this.fileBasedRecoveryThreshold = IndexSettings.FILE_BASED_RECOVERY_THRESHOLD_SETTING.get(indexSettings.getSettings()); this.safeCommitInfoSupplier = safeCommitInfoSupplier; this.onReplicationGroupUpdated = onReplicationGroupUpdated; assert IndexVersions.ZERO.equals(indexSettings.getIndexVersionCreated()) == false; assert invariant(); } /** * Returns the current replication group for the shard. * * @return the replication group */ public ReplicationGroup getReplicationGroup() { assert primaryMode; return replicationGroup; } private void updateReplicationGroupAndNotify() { assert Thread.holdsLock(this); ReplicationGroup newReplicationGroup = calculateReplicationGroup(); replicationGroup = newReplicationGroup; onReplicationGroupUpdated.accept(newReplicationGroup); } private ReplicationGroup calculateReplicationGroup() { long newVersion; if (replicationGroup == null) { newVersion = 0; } else { newVersion = replicationGroup.getVersion() + 1; } return new ReplicationGroup( routingTable, checkpoints.entrySet().stream().filter(e -> e.getValue().inSync).map(Map.Entry::getKey).collect(Collectors.toSet()), checkpoints.entrySet().stream().filter(e -> e.getValue().tracked).map(Map.Entry::getKey).collect(Collectors.toSet()), newVersion ); } /** * Returns the in-memory global checkpoint for the shard. * * @return the global checkpoint */ public long getGlobalCheckpoint() { return globalCheckpoint; } @Override public long getAsLong() { return globalCheckpoint; } /** * Updates the global checkpoint on a replica shard after it has been updated by the primary. * * @param newGlobalCheckpoint the new global checkpoint * @param reason the reason the global checkpoint was updated */ public synchronized void updateGlobalCheckpointOnReplica(final long newGlobalCheckpoint, final String reason) { assert invariant(); assert primaryMode == false; /* * The global checkpoint here is a local knowledge which is updated under the mandate of the primary. It can happen that the primary * information is lagging compared to a replica (e.g., if a replica is promoted to primary but has stale info relative to other * replica shards). In these cases, the local knowledge of the global checkpoint could be higher than the sync from the lagging * primary. */ final long previousGlobalCheckpoint = globalCheckpoint; if (newGlobalCheckpoint > previousGlobalCheckpoint) { globalCheckpoint = newGlobalCheckpoint; logger.trace("updated global checkpoint from [{}] to [{}] due to [{}]", previousGlobalCheckpoint, globalCheckpoint, reason); onGlobalCheckpointUpdated.accept(globalCheckpoint); } assert invariant(); } /** * Update the local knowledge of the persisted global checkpoint for the specified allocation ID. * * @param allocationId the allocation ID to update the global checkpoint for * @param globalCheckpoint the global checkpoint */ public synchronized void updateGlobalCheckpointForShard(final String allocationId, final long globalCheckpoint) { assert primaryMode; assert handoffInProgress == false; assert invariant(); final CheckpointState cps = checkpoints.get(allocationId); assert this.shardAllocationId.equals(allocationId) == false || cps != null; if (cps != null && globalCheckpoint > cps.globalCheckpoint) { final long previousGlobalCheckpoint = cps.globalCheckpoint; cps.globalCheckpoint = globalCheckpoint; logger.trace( "updated local knowledge for [{}] on the primary of the global checkpoint from [{}] to [{}]", allocationId, previousGlobalCheckpoint, globalCheckpoint ); } assert invariant(); } /** * Initializes the global checkpoint tracker in primary mode (see {@link #primaryMode}. Called on primary activation or promotion. */ public synchronized void activatePrimaryMode(final long localCheckpoint) { assert invariant(); assert primaryMode == false; assert checkpoints.get(shardAllocationId) != null && checkpoints.get(shardAllocationId).inSync && checkpoints.get(shardAllocationId).localCheckpoint == SequenceNumbers.UNASSIGNED_SEQ_NO : "expected " + shardAllocationId + " to have initialized entry in " + checkpoints + " when activating primary"; assert localCheckpoint >= SequenceNumbers.NO_OPS_PERFORMED; primaryMode = true; updateLocalCheckpoint(shardAllocationId, checkpoints.get(shardAllocationId), localCheckpoint); updateGlobalCheckpointOnPrimary(); addPeerRecoveryRetentionLeaseForSolePrimary(); assert invariant(); } /** * Creates a peer recovery retention lease for this shard, if one does not already exist and this shard is the sole shard copy in the * replication group. If one does not already exist and yet there are other shard copies in this group then we must have just done * a rolling upgrade from a version before {@link Version#V_7_4_0}, in which case the missing leases should be created asynchronously * by the caller using {@link ReplicationTracker#createMissingPeerRecoveryRetentionLeases(ActionListener)}. */ private void addPeerRecoveryRetentionLeaseForSolePrimary() { assert primaryMode; assert Thread.holdsLock(this); final ShardRouting primaryShard = routingTable.primaryShard(); final String leaseId = getPeerRecoveryRetentionLeaseId(primaryShard); if (retentionLeases.get(leaseId) == null) { if (replicationGroup.getReplicationTargets().equals(Collections.singletonList(primaryShard))) { assert primaryShard.allocationId().getId().equals(shardAllocationId) : routingTable.assignedShards() + " vs " + shardAllocationId; // Safe to call innerAddRetentionLease() without a subsequent sync since there are no other members of this replication // group. logger.trace("addPeerRecoveryRetentionLeaseForSolePrimary: adding lease [{}]", leaseId); innerAddRetentionLease( leaseId, Math.max(0L, checkpoints.get(shardAllocationId).globalCheckpoint + 1), PEER_RECOVERY_RETENTION_LEASE_SOURCE ); hasAllPeerRecoveryRetentionLeases = true; } else { /* * We got here here via a rolling upgrade from an older version that doesn't create peer recovery retention * leases for every shard copy, but in this case we do not expect any leases to exist. */ assert hasAllPeerRecoveryRetentionLeases == false : routingTable + " vs " + retentionLeases; logger.debug("{} becoming primary of {} with missing lease: {}", primaryShard, routingTable, retentionLeases); } } else if (hasAllPeerRecoveryRetentionLeases == false && routingTable.assignedShards() .stream() .filter(ShardRouting::isPromotableToPrimary) .allMatch( shardRouting -> retentionLeases.contains(getPeerRecoveryRetentionLeaseId(shardRouting)) || checkpoints.get(shardRouting.allocationId().getId()).tracked == false )) { // Although this index is old enough not to have all the expected peer recovery retention leases, in fact it does, so we // don't need to do any more work. hasAllPeerRecoveryRetentionLeases = true; } } /** * Notifies the tracker of the current allocation IDs in the cluster state. * * @param applyingClusterStateVersion the cluster state version being applied when updating the allocation IDs from the master * @param inSyncAllocationIds the allocation IDs of the currently in-sync shard copies * @param routingTable the shard routing table */ public synchronized void updateFromMaster( final long applyingClusterStateVersion, final Set<String> inSyncAllocationIds, final IndexShardRoutingTable routingTable ) { assert invariant(); if (applyingClusterStateVersion > appliedClusterStateVersion) { // check that the master does not fabricate new in-sync entries out of thin air once we are in primary mode assert primaryMode == false || inSyncAllocationIds.stream().allMatch(inSyncId -> checkpoints.containsKey(inSyncId) && checkpoints.get(inSyncId).inSync) : "update from master in primary mode contains in-sync ids " + inSyncAllocationIds + " that have no matching entries in " + checkpoints; // remove entries which don't exist on master Set<String> initializingAllocationIds = routingTable.getAllInitializingShards() .stream() .filter(ShardRouting::isPromotableToPrimary) .map(ShardRouting::allocationId) .map(AllocationId::getId) .collect(Collectors.toSet()); boolean removedEntries = checkpoints.keySet() .removeIf(aid -> inSyncAllocationIds.contains(aid) == false && initializingAllocationIds.contains(aid) == false); if (primaryMode) { // add new initializingIds that are missing locally. These are fresh shard copies - and not in-sync for (String initializingId : initializingAllocationIds) { if (checkpoints.containsKey(initializingId) == false) { final boolean inSync = inSyncAllocationIds.contains(initializingId); assert inSync == false : "update from master in primary mode has " + initializingId + " as in-sync but it does not exist locally"; final long localCheckpoint = SequenceNumbers.UNASSIGNED_SEQ_NO; final long globalCheckpoint = localCheckpoint; checkpoints.put(initializingId, new CheckpointState(localCheckpoint, globalCheckpoint, inSync, inSync)); } } if (removedEntries) { pendingInSync.removeIf(aId -> checkpoints.containsKey(aId) == false); } } else { for (String initializingId : initializingAllocationIds) { final long localCheckpoint = SequenceNumbers.UNASSIGNED_SEQ_NO; final long globalCheckpoint = localCheckpoint; checkpoints.put(initializingId, new CheckpointState(localCheckpoint, globalCheckpoint, false, false)); } for (String inSyncId : inSyncAllocationIds) { final long localCheckpoint = SequenceNumbers.UNASSIGNED_SEQ_NO; final long globalCheckpoint = localCheckpoint; checkpoints.put(inSyncId, new CheckpointState(localCheckpoint, globalCheckpoint, true, true)); } } appliedClusterStateVersion = applyingClusterStateVersion; this.routingTable = routingTable; updateReplicationGroupAndNotify(); if (primaryMode && removedEntries) { updateGlobalCheckpointOnPrimary(); // notify any waiter for local checkpoint advancement to recheck that their shard is still being tracked. notifyAllWaiters(); } } assert invariant(); } /** * Called when the recovery process for a shard has opened the engine on the target shard. Ensures that the right data structures * have been set up locally to track local checkpoint information for the shard and that the shard is added to the replication group. * * @param allocationId the allocation ID of the shard for which recovery was initiated */ public synchronized void initiateTracking(final String allocationId) { assert invariant(); assert primaryMode; assert handoffInProgress == false; CheckpointState cps = checkpoints.get(allocationId); if (cps == null) { // can happen if replica was removed from cluster but recovery process is unaware of it yet throw new IllegalStateException("no local checkpoint tracking information available"); } cps.tracked = true; updateReplicationGroupAndNotify(); assert invariant(); } /** * Marks the shard with the provided allocation ID as in-sync with the primary shard. This method will block until the local checkpoint * on the specified shard advances above the current global checkpoint. * * @param allocationId the allocation ID of the shard to mark as in-sync * @param localCheckpoint the current local checkpoint on the shard */ public synchronized void markAllocationIdAsInSync(final String allocationId, final long localCheckpoint) throws InterruptedException { assert invariant(); assert primaryMode; assert handoffInProgress == false; CheckpointState cps = checkpoints.get(allocationId); if (cps == null) { // can happen if replica was removed from cluster but recovery process is unaware of it yet throw new IllegalStateException("no local checkpoint tracking information available for " + allocationId); } assert localCheckpoint >= SequenceNumbers.NO_OPS_PERFORMED : "expected known local checkpoint for " + allocationId + " but was " + localCheckpoint; assert pendingInSync.contains(allocationId) == false : "shard copy " + allocationId + " is already marked as pending in-sync"; assert cps.tracked : "shard copy " + allocationId + " cannot be marked as in-sync as it's not tracked"; updateLocalCheckpoint(allocationId, cps, localCheckpoint); // if it was already in-sync (because of a previously failed recovery attempt), global checkpoint must have been // stuck from advancing assert cps.inSync == false || (cps.localCheckpoint >= getGlobalCheckpoint()) : "shard copy " + allocationId + " that's already in-sync should have a local checkpoint " + cps.localCheckpoint + " that's above the global checkpoint " + getGlobalCheckpoint(); if (cps.localCheckpoint < getGlobalCheckpoint()) { pendingInSync.add(allocationId); try { while (true) { if (pendingInSync.contains(allocationId)) { waitForLocalCheckpointToAdvance(); } else { break; } } } finally { pendingInSync.remove(allocationId); } } else { cps.inSync = true; updateReplicationGroupAndNotify(); logger.trace("marked [{}] as in-sync", allocationId); updateGlobalCheckpointOnPrimary(); } assert invariant(); } private boolean updateLocalCheckpoint(String allocationId, CheckpointState cps, long localCheckpoint) { // a local checkpoint for a shard copy should be a valid sequence number assert localCheckpoint >= SequenceNumbers.NO_OPS_PERFORMED : "invalid local checkpoint [" + localCheckpoint + "] for shard copy [" + allocationId + "]"; if (localCheckpoint > cps.localCheckpoint) { logger.trace("updated local checkpoint of [{}] from [{}] to [{}]", allocationId, cps.localCheckpoint, localCheckpoint); cps.localCheckpoint = localCheckpoint; return true; } else { logger.trace( "skipped updating local checkpoint of [{}] from [{}] to [{}], current checkpoint is higher", allocationId, cps.localCheckpoint, localCheckpoint ); return false; } } /** * Notifies the service to update the local checkpoint for the shard with the provided allocation ID. If the checkpoint is lower than * the currently known one, this is a no-op. If the allocation ID is not tracked, it is ignored. * * @param allocationId the allocation ID of the shard to update the local checkpoint for * @param localCheckpoint the local checkpoint for the shard */ public synchronized void updateLocalCheckpoint(final String allocationId, final long localCheckpoint) { assert invariant(); assert primaryMode; assert handoffInProgress == false; CheckpointState cps = checkpoints.get(allocationId); if (cps == null) { // can happen if replica was removed from cluster but replication process is unaware of it yet return; } boolean increasedLocalCheckpoint = updateLocalCheckpoint(allocationId, cps, localCheckpoint); boolean pending = pendingInSync.contains(allocationId); if (pending && cps.localCheckpoint >= getGlobalCheckpoint()) { pendingInSync.remove(allocationId); pending = false; cps.inSync = true; updateReplicationGroupAndNotify(); logger.trace("marked [{}] as in-sync", allocationId); notifyAllWaiters(); } if (increasedLocalCheckpoint && pending == false) { updateGlobalCheckpointOnPrimary(); } assert invariant(); } /** * Computes the global checkpoint based on the given local checkpoints. In case where there are entries preventing the * computation to happen (for example due to blocking), it returns the fallback value. */ private static long computeGlobalCheckpoint( final Set<String> pendingInSync, final Collection<CheckpointState> localCheckpoints, final long fallback ) { long minLocalCheckpoint = Long.MAX_VALUE; if (pendingInSync.isEmpty() == false) { return fallback; } for (final CheckpointState cps : localCheckpoints) { if (cps.inSync) { if (cps.localCheckpoint == SequenceNumbers.UNASSIGNED_SEQ_NO) { // unassigned in-sync replica return fallback; } else { minLocalCheckpoint = Math.min(cps.localCheckpoint, minLocalCheckpoint); } } } assert minLocalCheckpoint != Long.MAX_VALUE; return minLocalCheckpoint; } /** * Scans through the currently known local checkpoint and updates the global checkpoint accordingly. */ private synchronized void updateGlobalCheckpointOnPrimary() { assert primaryMode; final long computedGlobalCheckpoint = computeGlobalCheckpoint(pendingInSync, checkpoints.values(), getGlobalCheckpoint()); assert computedGlobalCheckpoint >= globalCheckpoint : "new global checkpoint [" + computedGlobalCheckpoint + "] is lower than previous one [" + globalCheckpoint + "]"; if (globalCheckpoint != computedGlobalCheckpoint) { globalCheckpoint = computedGlobalCheckpoint; logger.trace("updated global checkpoint to [{}]", computedGlobalCheckpoint); onGlobalCheckpointUpdated.accept(computedGlobalCheckpoint); } } /** * Initiates a relocation handoff and returns the corresponding primary context. */ public synchronized PrimaryContext startRelocationHandoff(String targetAllocationId) { assert invariant(); assert handoffInProgress == false; assert pendingInSync.isEmpty() : "relocation handoff started while there are still shard copies pending in-sync: " + pendingInSync; if (checkpoints.containsKey(targetAllocationId) == false) { // can happen if the relocation target was removed from cluster but the recovery process isn't aware of that. throw new IllegalStateException("relocation target [" + targetAllocationId + "] is no longer part of the replication group"); } assert primaryMode; handoffInProgress = true; // copy clusterStateVersion and checkpoints and return // all the entries from checkpoints that are inSync: the reason we don't need to care about initializing non-insync entries // is that they will have to undergo a recovery attempt on the relocation target, and will hence be supplied by the cluster state // update on the relocation target once relocation completes). We could alternatively also copy the map as-is (it’s safe), and it // would be cleaned up on the target by cluster state updates. Map<String, CheckpointState> localCheckpointsCopy = new HashMap<>(); for (Map.Entry<String, CheckpointState> entry : checkpoints.entrySet()) { localCheckpointsCopy.put(entry.getKey(), entry.getValue().copy()); } assert invariant(); return new PrimaryContext(appliedClusterStateVersion, localCheckpointsCopy, routingTable); } /** * Fails a relocation handoff attempt. */ public synchronized void abortRelocationHandoff() { assert invariant(); assert primaryMode; assert handoffInProgress; handoffInProgress = false; assert invariant(); } /** * Marks a relocation handoff attempt as successful. Moves the tracker into replica mode. */ public synchronized void completeRelocationHandoff() { assert invariant(); assert primaryMode; assert handoffInProgress; assert relocated == false; primaryMode = false; handoffInProgress = false; relocated = true; // forget all checkpoint information checkpoints.forEach((key, cps) -> { cps.localCheckpoint = SequenceNumbers.UNASSIGNED_SEQ_NO; cps.globalCheckpoint = SequenceNumbers.UNASSIGNED_SEQ_NO; }); assert invariant(); } /** * Activates the global checkpoint tracker in primary mode (see {@link #primaryMode}. Called on primary relocation target during * primary relocation handoff. * * @param primaryContext the primary context used to initialize the state */ public synchronized void activateWithPrimaryContext(PrimaryContext primaryContext) { assert invariant(); assert primaryMode == false; final Runnable runAfter = getMasterUpdateOperationFromCurrentState(); primaryMode = true; // capture current state to possibly replay missed cluster state update appliedClusterStateVersion = primaryContext.clusterStateVersion(); checkpoints.clear(); for (Map.Entry<String, CheckpointState> entry : primaryContext.checkpoints.entrySet()) { checkpoints.put(entry.getKey(), entry.getValue().copy()); } routingTable = primaryContext.getRoutingTable(); updateReplicationGroupAndNotify(); updateGlobalCheckpointOnPrimary(); // reapply missed cluster state update // note that if there was no cluster state update between start of the engine of this shard and the call to // initializeWithPrimaryContext, we might still have missed a cluster state update. This is best effort. runAfter.run(); addPeerRecoveryRetentionLeaseForSolePrimary(); assert invariant(); } private synchronized void setHasAllPeerRecoveryRetentionLeases() { hasAllPeerRecoveryRetentionLeases = true; assert invariant(); } public synchronized boolean hasAllPeerRecoveryRetentionLeases() { return hasAllPeerRecoveryRetentionLeases; } /** * Create any required peer-recovery retention leases that do not currently exist because we just did a rolling upgrade from a version * prior to {@link Version#V_7_4_0} that does not create peer-recovery retention leases. */ public synchronized void createMissingPeerRecoveryRetentionLeases(ActionListener<Void> listener) { if (hasAllPeerRecoveryRetentionLeases == false) { try (var listeners = new RefCountingListener(listener.safeMap(ignored -> { setHasAllPeerRecoveryRetentionLeases(); return null; }))) { for (ShardRouting shardRouting : routingTable.assignedShards()) { if (shardRouting.isPromotableToPrimary() == false) { continue; } if (retentionLeases.contains(getPeerRecoveryRetentionLeaseId(shardRouting))) { continue; } final CheckpointState checkpointState = checkpoints.get(shardRouting.allocationId().getId()); if (checkpointState.tracked == false) { continue; } logger.trace("createMissingPeerRecoveryRetentionLeases: adding missing lease for {}", shardRouting); ActionListener.run( listeners.acquire((ReplicationResponse replicationResponse) -> {}), l -> addPeerRecoveryRetentionLease( shardRouting.currentNodeId(), Math.max(SequenceNumbers.NO_OPS_PERFORMED, checkpointState.globalCheckpoint), l ) ); } } } else { logger.trace("createMissingPeerRecoveryRetentionLeases: nothing to do"); listener.onResponse(null); } } private Runnable getMasterUpdateOperationFromCurrentState() { assert primaryMode == false; final long lastAppliedClusterStateVersion = appliedClusterStateVersion; final Set<String> inSyncAllocationIds = new HashSet<>(); checkpoints.entrySet().forEach(entry -> { if (entry.getValue().inSync) { inSyncAllocationIds.add(entry.getKey()); } }); final IndexShardRoutingTable lastAppliedRoutingTable = routingTable; return () -> updateFromMaster(lastAppliedClusterStateVersion, inSyncAllocationIds, lastAppliedRoutingTable); } /** * Whether there are shards blocking global checkpoint advancement. */ public synchronized boolean pendingInSync() { assert primaryMode; return pendingInSync.isEmpty() == false; } /** * Returns the local checkpoint information tracked for a specific shard. Used by tests. */ public synchronized CheckpointState getTrackedLocalCheckpointForShard(String allocationId) { assert primaryMode; return checkpoints.get(allocationId); } /** * Notify all threads waiting on the monitor on this tracker. These threads should be waiting for the local checkpoint on a specific * allocation ID to catch up to the global checkpoint. */ @SuppressForbidden(reason = "Object#notifyAll waiters for local checkpoint advancement") private synchronized void notifyAllWaiters() { this.notifyAll(); } /** * Wait for the local checkpoint to advance to the global checkpoint. * * @throws InterruptedException if this thread was interrupted before of during waiting */ @SuppressForbidden(reason = "Object#wait for local checkpoint advancement") private synchronized void waitForLocalCheckpointToAdvance() throws InterruptedException { this.wait(); } /** * Represents the sequence number component of the primary context. This is the knowledge on the primary of the in-sync and initializing * shards and their local checkpoints. */ public static
CheckpointState
java
spring-projects__spring-data-jpa
spring-data-envers/src/main/java/org/springframework/data/envers/repository/config/EnableEnversRepositories.java
{ "start": 5387, "end": 5811 }
class ____ be used to create repository proxies for this particular configuration. * * @return */ @AliasFor(annotation = EnableJpaRepositories.class) Class<?> repositoryBaseClass() default DefaultRepositoryBaseClass.class; /** * Configure a specific {@link BeanNameGenerator} to be used when creating the repository beans. * @return the {@link BeanNameGenerator} to be used or the base {@link BeanNameGenerator}
to
java
apache__flink
flink-formats/flink-json/src/test/java/org/apache/flink/formats/json/maxwell/MaxwellJsonSerDerTest.java
{ "start": 2432, "end": 16106 }
class ____ { private static final DataType PHYSICAL_DATA_TYPE = ROW( FIELD("id", INT().notNull()), FIELD("name", STRING()), FIELD("description", STRING()), FIELD("weight", FLOAT())); @Test void testDeserializationWithMetadata() throws Exception { // we only read the first line for keeping the test simple final String firstLine = readLines("maxwell-data.txt").get(0); final List<ReadableMetadata> requestedMetadata = Arrays.asList(ReadableMetadata.values()); final DataType producedDataType = DataTypeUtils.appendRowFields( PHYSICAL_DATA_TYPE, requestedMetadata.stream() .map(m -> DataTypes.FIELD(m.key, m.dataType)) .collect(Collectors.toList())); final MaxwellJsonDeserializationSchema deserializationSchema = new MaxwellJsonDeserializationSchema( PHYSICAL_DATA_TYPE, requestedMetadata, InternalTypeInfo.of(producedDataType.getLogicalType()), false, TimestampFormat.ISO_8601); open(deserializationSchema); final SimpleCollector collector = new SimpleCollector(); deserializationSchema.deserialize(firstLine.getBytes(StandardCharsets.UTF_8), collector); assertThat(collector.list).hasSize(1); assertThat(collector.list.get(0)) .satisfies( row -> { assertThat(row.getInt(0)).isEqualTo(101); assertThat(row.getString(1).toString()).isEqualTo("scooter"); assertThat(row.getString(2).toString()) .isEqualTo("Small 2-wheel scooter"); assertThat(row.getFloat(3)).isEqualTo(3.14f); assertThat(row.getString(4).toString()).isEqualTo("test"); assertThat(row.getString(5).toString()).isEqualTo("product"); assertThat(row.getArray(6).getString(0).toString()).isEqualTo("id"); assertThat(row.getTimestamp(7, 3).getMillisecond()) .isEqualTo(1596684883000L); }); } @Test void testIgnoreParseErrors() throws Exception { List<String> lines = readLines("maxwell-data.txt"); MaxwellJsonDeserializationSchema deserializationSchema = new MaxwellJsonDeserializationSchema( PHYSICAL_DATA_TYPE, Collections.emptyList(), InternalTypeInfo.of(PHYSICAL_DATA_TYPE.getLogicalType()), true, TimestampFormat.ISO_8601); open(deserializationSchema); ThrowingExceptionCollector collector = new ThrowingExceptionCollector(); assertThatThrownBy( () -> { for (String line : lines) { deserializationSchema.deserialize( line.getBytes(StandardCharsets.UTF_8), collector); } }) .isInstanceOf(RuntimeException.class) .satisfies( anyCauseMatches( RuntimeException.class, "An error occurred while collecting data.")); } @Test void testSerializationDeserialization() throws Exception { List<String> lines = readLines("maxwell-data.txt"); MaxwellJsonDeserializationSchema deserializationSchema = new MaxwellJsonDeserializationSchema( PHYSICAL_DATA_TYPE, Collections.emptyList(), InternalTypeInfo.of(PHYSICAL_DATA_TYPE.getLogicalType()), false, TimestampFormat.ISO_8601); open(deserializationSchema); SimpleCollector collector = new SimpleCollector(); for (String line : lines) { deserializationSchema.deserialize(line.getBytes(StandardCharsets.UTF_8), collector); } // Maxwell captures change data (`maxwell-data.txt`) on the `product` table: // // CREATE TABLE product ( // id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, // name VARCHAR(255), // description VARCHAR(512), // weight FLOAT // ); // ALTER TABLE product AUTO_INCREMENT = 101; // // INSERT INTO product // VALUES (default,"scooter","Small 2-wheel scooter",3.14), // (default,"car battery","12V car battery",8.1), // (default,"12-pack drill bits","12-pack of drill bits with sizes ranging from #40 // to #3",0.8), // (default,"hammer","12oz carpenter's hammer",0.75), // (default,"hammer","14oz carpenter's hammer",0.875), // (default,"hammer","16oz carpenter's hammer",1.0), // (default,"rocks","box of assorted rocks",5.3), // (default,"jacket","water resistent black wind breaker",0.1), // (default,"spare tire","24 inch spare tire",22.2); // UPDATE product SET description='18oz carpenter hammer' WHERE id=106; // UPDATE product SET weight='5.1' WHERE id=107; // INSERT INTO product VALUES (default,"jacket","water resistent white wind breaker",0.2); // INSERT INTO product VALUES (default,"scooter","Big 2-wheel scooter ",5.18); // UPDATE product SET description='new water resistent white wind breaker', weight='0.5' // WHERE id=110; // UPDATE product SET weight='5.17' WHERE id=111; // DELETE FROM product WHERE id=111; // UPDATE product SET weight='5.17' WHERE id=102 or id = 101; // DELETE FROM product WHERE id=102 or id = 103; List<String> expected = Arrays.asList( "+I(101,scooter,Small 2-wheel scooter,3.14)", "+I(102,car battery,12V car battery,8.1)", "+I(103,12-pack drill bits,12-pack of drill bits with sizes ranging from #40 to #3,0.8)", "+I(104,hammer,12oz carpenter's hammer,0.75)", "+I(105,hammer,14oz carpenter's hammer,0.875)", "+I(106,hammer,16oz carpenter's hammer,1.0)", "+I(107,rocks,box of assorted rocks,5.3)", "+I(108,jacket,water resistent black wind breaker,0.1)", "+I(109,spare tire,24 inch spare tire,22.2)", "-U(106,hammer,16oz carpenter's hammer,1.0)", "+U(106,hammer,18oz carpenter hammer,1.0)", "-U(107,rocks,box of assorted rocks,5.3)", "+U(107,rocks,box of assorted rocks,5.1)", "+I(110,jacket,water resistent white wind breaker,0.2)", "+I(111,scooter,Big 2-wheel scooter ,5.18)", "-U(110,jacket,water resistent white wind breaker,0.2)", "+U(110,jacket,new water resistent white wind breaker,0.5)", "-U(111,scooter,Big 2-wheel scooter ,5.18)", "+U(111,scooter,Big 2-wheel scooter ,5.17)", "-D(111,scooter,Big 2-wheel scooter ,5.17)", "-U(101,scooter,Small 2-wheel scooter,3.14)", "+U(101,scooter,Small 2-wheel scooter,5.17)", "-U(102,car battery,12V car battery,8.1)", "+U(102,car battery,12V car battery,5.17)", "-D(102,car battery,12V car battery,5.17)", "-D(103,12-pack drill bits,12-pack of drill bits with sizes ranging from #40 to #3,0.8)"); List<String> actual = collector.list.stream().map(Object::toString).collect(Collectors.toList()); assertThat(actual).isEqualTo(expected); MaxwellJsonSerializationSchema serializationSchema = new MaxwellJsonSerializationSchema( (RowType) PHYSICAL_DATA_TYPE.getLogicalType(), TimestampFormat.SQL, JsonFormatOptions.MapNullKeyMode.LITERAL, "null", true, false); open(serializationSchema); List<String> result = new ArrayList<>(); for (RowData rowData : collector.list) { result.add(new String(serializationSchema.serialize(rowData), StandardCharsets.UTF_8)); } List<String> expectedResult = Arrays.asList( "{\"data\":{\"id\":101,\"name\":\"scooter\",\"description\":\"Small 2-wheel scooter\",\"weight\":3.14},\"type\":\"insert\"}", "{\"data\":{\"id\":102,\"name\":\"car battery\",\"description\":\"12V car battery\",\"weight\":8.1},\"type\":\"insert\"}", "{\"data\":{\"id\":103,\"name\":\"12-pack drill bits\",\"description\":\"12-pack of drill bits with sizes ranging from #40 to #3\",\"weight\":0.8},\"type\":\"insert\"}", "{\"data\":{\"id\":104,\"name\":\"hammer\",\"description\":\"12oz carpenter's hammer\",\"weight\":0.75},\"type\":\"insert\"}", "{\"data\":{\"id\":105,\"name\":\"hammer\",\"description\":\"14oz carpenter's hammer\",\"weight\":0.875},\"type\":\"insert\"}", "{\"data\":{\"id\":106,\"name\":\"hammer\",\"description\":\"16oz carpenter's hammer\",\"weight\":1.0},\"type\":\"insert\"}", "{\"data\":{\"id\":107,\"name\":\"rocks\",\"description\":\"box of assorted rocks\",\"weight\":5.3},\"type\":\"insert\"}", "{\"data\":{\"id\":108,\"name\":\"jacket\",\"description\":\"water resistent black wind breaker\",\"weight\":0.1},\"type\":\"insert\"}", "{\"data\":{\"id\":109,\"name\":\"spare tire\",\"description\":\"24 inch spare tire\",\"weight\":22.2},\"type\":\"insert\"}", "{\"data\":{\"id\":106,\"name\":\"hammer\",\"description\":\"16oz carpenter's hammer\",\"weight\":1.0},\"type\":\"delete\"}", "{\"data\":{\"id\":106,\"name\":\"hammer\",\"description\":\"18oz carpenter hammer\",\"weight\":1.0},\"type\":\"insert\"}", "{\"data\":{\"id\":107,\"name\":\"rocks\",\"description\":\"box of assorted rocks\",\"weight\":5.3},\"type\":\"delete\"}", "{\"data\":{\"id\":107,\"name\":\"rocks\",\"description\":\"box of assorted rocks\",\"weight\":5.1},\"type\":\"insert\"}", "{\"data\":{\"id\":110,\"name\":\"jacket\",\"description\":\"water resistent white wind breaker\",\"weight\":0.2},\"type\":\"insert\"}", "{\"data\":{\"id\":111,\"name\":\"scooter\",\"description\":\"Big 2-wheel scooter \",\"weight\":5.18},\"type\":\"insert\"}", "{\"data\":{\"id\":110,\"name\":\"jacket\",\"description\":\"water resistent white wind breaker\",\"weight\":0.2},\"type\":\"delete\"}", "{\"data\":{\"id\":110,\"name\":\"jacket\",\"description\":\"new water resistent white wind breaker\",\"weight\":0.5},\"type\":\"insert\"}", "{\"data\":{\"id\":111,\"name\":\"scooter\",\"description\":\"Big 2-wheel scooter \",\"weight\":5.18},\"type\":\"delete\"}", "{\"data\":{\"id\":111,\"name\":\"scooter\",\"description\":\"Big 2-wheel scooter \",\"weight\":5.17},\"type\":\"insert\"}", "{\"data\":{\"id\":111,\"name\":\"scooter\",\"description\":\"Big 2-wheel scooter \",\"weight\":5.17},\"type\":\"delete\"}", "{\"data\":{\"id\":101,\"name\":\"scooter\",\"description\":\"Small 2-wheel scooter\",\"weight\":3.14},\"type\":\"delete\"}", "{\"data\":{\"id\":101,\"name\":\"scooter\",\"description\":\"Small 2-wheel scooter\",\"weight\":5.17},\"type\":\"insert\"}", "{\"data\":{\"id\":102,\"name\":\"car battery\",\"description\":\"12V car battery\",\"weight\":8.1},\"type\":\"delete\"}", "{\"data\":{\"id\":102,\"name\":\"car battery\",\"description\":\"12V car battery\",\"weight\":5.17},\"type\":\"insert\"}", "{\"data\":{\"id\":102,\"name\":\"car battery\",\"description\":\"12V car battery\",\"weight\":5.17},\"type\":\"delete\"}", "{\"data\":{\"id\":103,\"name\":\"12-pack drill bits\",\"description\":\"12-pack of drill bits with sizes ranging from #40 to #3\",\"weight\":0.8},\"type\":\"delete\"}"); assertThat(result).isEqualTo(expectedResult); } // -------------------------------------------------------------------------------------------- // Utilities // -------------------------------------------------------------------------------------------- private static List<String> readLines(String resource) throws IOException { final URL url = MaxwellJsonSerDerTest.class.getClassLoader().getResource(resource); assert url != null; Path path = new File(url.getFile()).toPath(); return Files.readAllLines(path); } private static
MaxwellJsonSerDerTest
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGenerator.java
{ "start": 4512, "end": 4655 }
class ____ * the original structure is created. * @param generationContext the generation context to use * @param target the chosen target
in
java
spring-projects__spring-security
test/src/main/java/org/springframework/security/test/web/servlet/response/SecurityMockMvcResultMatchers.java
{ "start": 2576, "end": 3180 }
class ____<T extends AuthenticationMatcher<T>> implements ResultMatcher { protected SecurityContext load(MvcResult result) { HttpRequestResponseHolder holder = new HttpRequestResponseHolder(result.getRequest(), result.getResponse()); SecurityContextRepository repository = WebTestUtils.getSecurityContextRepository(result.getRequest()); return repository.loadContext(holder); } } /** * A {@link MockMvc} {@link ResultMatcher} that verifies a specific user is associated * to the {@link MvcResult}. * * @author Rob Winch * @since 4.0 */ public static final
AuthenticationMatcher
java
apache__camel
components/camel-http/src/test/java/org/apache/camel/component/http/HttpServerTestSupport.java
{ "start": 1293, "end": 2366 }
class ____ extends CamelTestSupport { /** * Returns the org.apache.http.protocol.BasicHttpProcessor which should be used by the server. * * @return HttpProcessor */ protected HttpProcessor getBasicHttpProcessor() { return null; } /** * Returns the org.apache.hc.core5.http.ConnectionReuseStrategy which should be used by the server. * * @return connectionReuseStrategy */ protected ConnectionReuseStrategy getConnectionReuseStrategy() { return null; } /** * Returns the org.apache.hc.core5.http.HttpResponseFactory which should be used by the server. * * @return httpResponseFactory */ protected HttpResponseFactory<ClassicHttpResponse> getHttpResponseFactory() { return null; } /** * Returns the javax.net.ssl.SSLContext which should be used by the server. * * @return sslContext * @throws Exception */ protected SSLContext getSSLContext() throws Exception { return null; } }
HttpServerTestSupport
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/SQLListResourceGroupStatement.java
{ "start": 850, "end": 1051 }
class ____ extends SQLStatementImpl implements SQLCreateStatement { public void accept0(SQLASTVisitor v) { v.visit(this); v.endVisit(this); } }
SQLListResourceGroupStatement
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/action/ParseTables.java
{ "start": 1241, "end": 12613 }
class ____ { public static final Set<DataType> SUPPORTED_TYPES = Set.of(DataType.INTEGER, DataType.KEYWORD, DataType.LONG); private static final int MAX_LENGTH = (int) ByteSizeValue.ofMb(1).getBytes(); private final BlockFactory blockFactory; private final EsqlQueryRequest request; private final XContentParser p; private int length; ParseTables(EsqlQueryRequest request, XContentParser p) { // TODO use a real block factory this.blockFactory = new BlockFactory(new NoopCircuitBreaker(CircuitBreaker.REQUEST), BigArrays.NON_RECYCLING_INSTANCE); this.request = request; this.p = p; } void parseTables() throws IOException { if (p.currentToken() != XContentParser.Token.START_OBJECT) { throw new XContentParseException(p.getTokenLocation(), "expected " + XContentParser.Token.START_OBJECT); } while (true) { switch (p.nextToken()) { case END_OBJECT -> { return; } case FIELD_NAME -> { String name = p.currentName(); p.nextToken(); request.addTable(name, parseTable()); } } } } /** * Parse a table from the request. Object keys are in the format {@code name:type} * so we can be sure we'll always have a type. */ private Map<String, Column> parseTable() throws IOException { Map<String, Column> columns = new LinkedHashMap<>(); boolean success = false; try { if (p.currentToken() != XContentParser.Token.START_OBJECT) { throw new XContentParseException(p.getTokenLocation(), "expected " + XContentParser.Token.START_OBJECT); } while (true) { switch (p.nextToken()) { case END_OBJECT -> { success = true; return columns; } case FIELD_NAME -> { String name = p.currentName(); if (columns.containsKey(name)) { throw new XContentParseException(p.getTokenLocation(), "duplicate column name [" + name + "]"); } columns.put(name, parseColumn()); } default -> throw new XContentParseException( p.getTokenLocation(), "expected " + XContentParser.Token.END_OBJECT + " or " + XContentParser.Token.FIELD_NAME ); } } } finally { if (success == false) { Releasables.close(columns.values()); } } } private Column parseColumn() throws IOException { if (p.nextToken() != XContentParser.Token.START_OBJECT) { throw new XContentParseException(p.getTokenLocation(), "expected " + XContentParser.Token.START_OBJECT); } if (p.nextToken() != XContentParser.Token.FIELD_NAME) { throw new XContentParseException(p.getTokenLocation(), "expected " + XContentParser.Token.FIELD_NAME); } String type = p.currentName(); Column result = switch (type) { case "integer" -> parseIntColumn(); case "keyword" -> parseKeywordColumn(); case "long" -> parseLongColumn(); case "double" -> parseDoubleColumn(); default -> throw new XContentParseException(p.getTokenLocation(), "unsupported type [" + type + "]"); }; if (p.nextToken() != XContentParser.Token.END_OBJECT) { result.close(); throw new XContentParseException(p.getTokenLocation(), "expected " + XContentParser.Token.END_OBJECT); } return result; } private Column parseKeywordColumn() throws IOException { try (BytesRefBlock.Builder builder = blockFactory.newBytesRefBlockBuilder(100)) { // TODO 100?! XContentParser.Token token = p.nextToken(); if (token != XContentParser.Token.START_ARRAY) { throw new XContentParseException(p.getTokenLocation(), "expected " + XContentParser.Token.START_ARRAY); } BytesRefBuilder scratch = new BytesRefBuilder(); while (true) { switch (p.nextToken()) { case END_ARRAY -> { return new Column(DataType.KEYWORD, builder.build()); } case START_ARRAY -> parseTextArray(builder, scratch); case VALUE_NULL -> builder.appendNull(); case VALUE_STRING, VALUE_NUMBER, VALUE_BOOLEAN -> appendText(builder, scratch); default -> throw new XContentParseException(p.getTokenLocation(), "expected string, array of strings, or null"); } } } } private void parseTextArray(BytesRefBlock.Builder builder, BytesRefBuilder scratch) throws IOException { builder.beginPositionEntry(); while (true) { switch (p.nextToken()) { case END_ARRAY -> { builder.endPositionEntry(); return; } case VALUE_STRING -> appendText(builder, scratch); default -> throw new XContentParseException(p.getTokenLocation(), "expected string"); } } } private void appendText(BytesRefBlock.Builder builder, BytesRefBuilder scratch) throws IOException { scratch.clear(); String v = p.text(); scratch.copyChars(v, 0, v.length()); length += scratch.length(); if (length > MAX_LENGTH) { throw new XContentParseException(p.getTokenLocation(), "tables too big"); } builder.appendBytesRef(scratch.get()); } private Column parseIntColumn() throws IOException { try (IntBlock.Builder builder = blockFactory.newIntBlockBuilder(100)) { // TODO 100?! XContentParser.Token token = p.nextToken(); if (token != XContentParser.Token.START_ARRAY) { throw new XContentParseException(p.getTokenLocation(), "expected " + XContentParser.Token.START_ARRAY); } while (true) { switch (p.nextToken()) { case END_ARRAY -> { return new Column(DataType.INTEGER, builder.build()); } case START_ARRAY -> parseIntArray(builder); case VALUE_NULL -> builder.appendNull(); case VALUE_NUMBER, VALUE_STRING -> appendInt(builder); default -> throw new XContentParseException(p.getTokenLocation(), "expected number, array of numbers, or null"); } } } } private void parseIntArray(IntBlock.Builder builder) throws IOException { builder.beginPositionEntry(); while (true) { switch (p.nextToken()) { case END_ARRAY -> { builder.endPositionEntry(); return; } case VALUE_NUMBER, VALUE_STRING -> appendInt(builder); default -> throw new XContentParseException(p.getTokenLocation(), "expected number"); } } } private void appendInt(IntBlock.Builder builder) throws IOException { length += Integer.BYTES; if (length > MAX_LENGTH) { throw new XContentParseException(p.getTokenLocation(), "tables too big"); } builder.appendInt(p.intValue()); } private Column parseLongColumn() throws IOException { try (LongBlock.Builder builder = blockFactory.newLongBlockBuilder(100)) { // TODO 100?! XContentParser.Token token = p.nextToken(); if (token != XContentParser.Token.START_ARRAY) { throw new XContentParseException(p.getTokenLocation(), "expected " + XContentParser.Token.START_ARRAY); } while (true) { switch (p.nextToken()) { case END_ARRAY -> { return new Column(DataType.LONG, builder.build()); } case START_ARRAY -> parseLongArray(builder); case VALUE_NULL -> builder.appendNull(); case VALUE_NUMBER, VALUE_STRING -> appendLong(builder); default -> throw new XContentParseException(p.getTokenLocation(), "expected number, array of numbers, or null"); } } } } private void parseLongArray(LongBlock.Builder builder) throws IOException { builder.beginPositionEntry(); while (true) { switch (p.nextToken()) { case END_ARRAY -> { builder.endPositionEntry(); return; } case VALUE_NUMBER, VALUE_STRING -> appendLong(builder); default -> throw new XContentParseException(p.getTokenLocation(), "expected number"); } } } private void appendLong(LongBlock.Builder builder) throws IOException { length += Long.BYTES; if (length > MAX_LENGTH) { throw new XContentParseException(p.getTokenLocation(), "tables too big"); } builder.appendLong(p.longValue()); } private Column parseDoubleColumn() throws IOException { try (DoubleBlock.Builder builder = blockFactory.newDoubleBlockBuilder(100)) { // TODO 100?! XContentParser.Token token = p.nextToken(); if (token != XContentParser.Token.START_ARRAY) { throw new XContentParseException(p.getTokenLocation(), "expected " + XContentParser.Token.START_ARRAY); } while (true) { switch (p.nextToken()) { case END_ARRAY -> { return new Column(DataType.DOUBLE, builder.build()); } case START_ARRAY -> parseDoubleArray(builder); case VALUE_NULL -> builder.appendNull(); case VALUE_NUMBER, VALUE_STRING -> appendDouble(builder); default -> throw new XContentParseException(p.getTokenLocation(), "expected number, array of numbers, or null"); } } } } private void parseDoubleArray(DoubleBlock.Builder builder) throws IOException { builder.beginPositionEntry(); while (true) { switch (p.nextToken()) { case END_ARRAY -> { builder.endPositionEntry(); return; } case VALUE_NUMBER, VALUE_STRING -> appendDouble(builder); default -> throw new XContentParseException(p.getTokenLocation(), "expected number"); } } } private void appendDouble(DoubleBlock.Builder builder) throws IOException { length += Double.BYTES; if (length > MAX_LENGTH) { throw new XContentParseException(p.getTokenLocation(), "tables too big"); } builder.appendDouble(p.doubleValue()); } }
ParseTables
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/router/TestRouterFederationRename.java
{ "start": 2617, "end": 2708 }
class ____ extends TestRouterFederationRenameBase { public static
TestRouterFederationRename
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpsServerImplicitSSLWithClientAuthTestSupport.java
{ "start": 1290, "end": 1669 }
class ____ extends FtpsServerTestSupport { @RegisterExtension static FtpsEmbeddedService service = FtpServiceFactory .createSecureEmbeddedService(new EmbeddedConfiguration.SecurityConfiguration(true, AUTH_VALUE_SSL, true)); @Deprecated public static int getPort() { return service.getPort(); } }
FtpsServerImplicitSSLWithClientAuthTestSupport
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UngroupedOverloadsTest.java
{ "start": 17740, "end": 18112 }
class ____ { BelowLimit() {} void foo() {} void foo(int x) {} void bar() {} } """) .doTest(); } @Test public void ungroupedOverloadsRefactoring_fiveMethods() { refactoringHelper .addInputLines( "in/AboveLimit.java", """
BelowLimit
java
apache__camel
components/camel-cron/src/main/java/org/apache/camel/component/cron/CronEndpoint.java
{ "start": 1639, "end": 3194 }
class ____ extends DefaultEndpoint implements DelegateEndpoint { private Endpoint delegate; @UriParam private CamelCronConfiguration configuration; public CronEndpoint(String endpointUri, CronComponent component, CamelCronConfiguration configuration) { super(endpointUri, component); this.configuration = configuration; } @Override public boolean isRemote() { return false; } public void setDelegate(Endpoint delegate) { this.delegate = delegate; } @Override public Endpoint getEndpoint() { return delegate; } @Override public Producer createProducer() throws Exception { throw new UnsupportedOperationException(); } @Override public Consumer createConsumer(Processor processor) throws Exception { Consumer consumer = delegate.createConsumer(processor); configureConsumer(consumer); return consumer; } public CamelCronConfiguration getConfiguration() { return configuration; } @Override protected void doStart() throws Exception { super.doStart(); ObjectHelper.notNull(delegate, "delegate endpoint"); ServiceHelper.startService(delegate); } @Override protected void doStop() throws Exception { super.doStop(); ServiceHelper.stopService(delegate); } @Override protected void doShutdown() throws Exception { super.doShutdown(); ServiceHelper.stopAndShutdownService(delegate); } }
CronEndpoint
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/metadata/MetadataIndexStateService.java
{ "start": 62260, "end": 71890 }
class ____ implements ClusterStateTaskExecutor<OpenIndicesTask> { @Override public ClusterState execute(BatchExecutionContext<OpenIndicesTask> batchExecutionContext) { var listener = new AllocationActionMultiListener<AcknowledgedResponse>(threadPool.getThreadContext()); var state = batchExecutionContext.initialState(); try (var ignored = batchExecutionContext.dropHeadersContext()) { // we may encounter deprecated settings but they are not directly related to opening the indices, nor are they really // associated with any particular tasks, so we drop them // build an in-order de-duplicated array of all the indices to open final Set<Index> indicesToOpen = Sets.newLinkedHashSetWithExpectedSize(batchExecutionContext.taskContexts().size()); for (final var taskContext : batchExecutionContext.taskContexts()) { Collections.addAll(indicesToOpen, taskContext.getTask().request.indices()); } Index[] indices = indicesToOpen.toArray(Index.EMPTY_ARRAY); // open them // NOTE the tasks are batched and the indices can be from different projects state = openIndices(indices, state); // do a final reroute state = allocationService.reroute(state, "indices opened", listener.reroute()); for (final var taskContext : batchExecutionContext.taskContexts()) { final var task = taskContext.getTask(); taskContext.success(task.getAckListener(listener)); } } catch (Exception e) { for (final var taskContext : batchExecutionContext.taskContexts()) { taskContext.onFailure(e); } } return state; } private ClusterState openIndices(final Index[] indices, final ClusterState currentState) { final List<Tuple<ProjectId, IndexMetadata>> indicesToOpen = new ArrayList<>(indices.length); for (Index index : indices) { final ProjectMetadata projectMetadata = currentState.metadata().projectFor(index); final IndexMetadata indexMetadata = projectMetadata.getIndexSafe(index); if (indexMetadata.getState() != IndexMetadata.State.OPEN) { indicesToOpen.add(new Tuple<>(projectMetadata.id(), indexMetadata)); } else if (currentState.blocks().hasIndexBlockWithId(projectMetadata.id(), index.getName(), INDEX_CLOSED_BLOCK_ID)) { indicesToOpen.add(new Tuple<>(projectMetadata.id(), indexMetadata)); } } shardLimitValidator.validateShardLimit(currentState.nodes(), currentState.metadata(), indices); if (indicesToOpen.isEmpty()) { return currentState; } logger.info(() -> { final StringBuilder indexNames = new StringBuilder(); Strings.collectionToDelimitedStringWithLimit( indicesToOpen.stream().map(i -> (CharSequence) i.v2().getIndex().toString()).toList(), ",", 512, indexNames ); return "opening indices [" + indexNames + "]"; }); final Metadata.Builder metadata = Metadata.builder(currentState.metadata()); final ClusterBlocks.Builder blocks = ClusterBlocks.builder(currentState.blocks()); final IndexVersion minIndexCompatibilityVersion = currentState.getNodes().getMinSupportedIndexVersion(); final IndexVersion minReadOnlyIndexCompatibilityVersion = currentState.getNodes().getMinReadOnlySupportedIndexVersion(); for (var indexToOpen : indicesToOpen) { final ProjectId projectId = indexToOpen.v1(); final IndexMetadata indexMetadata = indexToOpen.v2(); final Index index = indexMetadata.getIndex(); if (indexMetadata.getState() != IndexMetadata.State.OPEN) { final Settings.Builder updatedSettings = Settings.builder().put(indexMetadata.getSettings()); updatedSettings.remove(VERIFIED_BEFORE_CLOSE_SETTING.getKey()); // Reopening a read-only compatible index that has not been marked as read-only is possible if the index was // verified-before-close in the first place. var compatibilityVersion = indexMetadata.getCompatibilityVersion(); if (compatibilityVersion.before(minIndexCompatibilityVersion) && hasReadOnlyBlocks(indexMetadata) == false) { if (isIndexVerifiedBeforeClosed(indexMetadata)) { updatedSettings.put(VERIFIED_READ_ONLY_SETTING.getKey(), true); // at least set a write block if the index was verified-before-close at the time the cluster was upgraded blocks.addIndexBlock(projectId, index.getName(), APIBlock.WRITE.block); updatedSettings.put(APIBlock.WRITE.settingName(), true); } // or else, the following indexMetadataVerifier.verifyIndexMetadata() should throw. } IndexMetadata newIndexMetadata = IndexMetadata.builder(indexMetadata) .state(IndexMetadata.State.OPEN) .settingsVersion(indexMetadata.getSettingsVersion() + 1) .settings(updatedSettings) .timestampRange(IndexLongFieldRange.NO_SHARDS) .eventIngestedRange(IndexLongFieldRange.NO_SHARDS) .build(); // The index might be closed because we couldn't import it due to an old incompatible // version, so we need to verify its compatibility. newIndexMetadata = indexMetadataVerifier.verifyIndexMetadata( newIndexMetadata, minIndexCompatibilityVersion, minReadOnlyIndexCompatibilityVersion ); try { indicesService.verifyIndexMetadata(newIndexMetadata, newIndexMetadata); } catch (Exception e) { throw new ElasticsearchException("Failed to verify index " + index, e); } metadata.getProject(projectId).put(newIndexMetadata, true); } // Always removes index closed blocks (note: this can fail on-going close index actions) blocks.removeIndexBlockWithId(projectId, index.getName(), INDEX_CLOSED_BLOCK_ID); } ClusterState updatedState = ClusterState.builder(currentState).metadata(metadata).blocks(blocks).build(); final Map<ProjectId, RoutingTable.Builder> routingTableBuilders = new HashMap<>(); for (var indexToOpen : indicesToOpen) { final ProjectId projectId = indexToOpen.v1(); final IndexMetadata previousIndexMetadata = indexToOpen.v2(); if (previousIndexMetadata.getState() != IndexMetadata.State.OPEN) { final RoutingTable.Builder routingTable = routingTableBuilders.computeIfAbsent( projectId, k -> RoutingTable.builder(allocationService.getShardRoutingRoleStrategy(), updatedState.routingTable(k)) ); routingTable.addAsFromCloseToOpen( updatedState.metadata().getProject(projectId).getIndexSafe(previousIndexMetadata.getIndex()) ); } } final GlobalRoutingTable.Builder globalRoutingTableBuilder = GlobalRoutingTable.builder(updatedState.globalRoutingTable()); routingTableBuilders.forEach((globalRoutingTableBuilder::put)); return ClusterState.builder(updatedState).routingTable(globalRoutingTableBuilder.build()).build(); } } private record OpenIndicesTask(OpenIndexClusterStateUpdateRequest request, ActionListener<AcknowledgedResponse> listener) implements ClusterStateTaskListener { @Override public void onFailure(Exception e) { listener.onFailure(e); } public ClusterStateAckListener getAckListener(AllocationActionMultiListener<AcknowledgedResponse> multiListener) { return new ClusterStateAckListener() { @Override public boolean mustAck(DiscoveryNode discoveryNode) { return true; } @Override public void onAllNodesAcked() { multiListener.delay(listener).onResponse(AcknowledgedResponse.of(true)); } @Override public void onAckFailure(Exception e) { multiListener.delay(listener).onResponse(AcknowledgedResponse.of(false)); } @Override public void onAckTimeout() { multiListener.delay(listener).onResponse(AcknowledgedResponse.FALSE); } @Override public TimeValue ackTimeout() { return request.ackTimeout(); } }; } } }
OpenIndicesExecutor
java
google__guice
core/test/com/google/inject/ImplicitBindingTest.java
{ "start": 1658, "end": 1701 }
interface ____ { void go(); } static
I
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/introspect/IntrospectorPairTest.java
{ "start": 26981, "end": 27356 }
class ____ extends NopAnnotationIntrospector { @Override public JacksonInject.Value findInjectableValue(MapperConfig<?> config, AnnotatedMember m) { if (m.getRawType() == UnreadableBean.class) { return JacksonInject.Value.forId("jjj"); } return null; } } static
TestIntrospector
java
apache__flink
flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/hybrid/SwitchedSources.java
{ "start": 1252, "end": 2081 }
class ____ { private final SortedMap<Integer, Source> sources = new TreeMap<>(); private final Map<Integer, SimpleVersionedSerializer<SourceSplit>> cachedSerializers = new HashMap<>(); public Source sourceOf(int sourceIndex) { return Preconditions.checkNotNull( sources.get(sourceIndex), "Source for index=%s not available", sourceIndex); } public SimpleVersionedSerializer<SourceSplit> serializerOf(int sourceIndex) { return cachedSerializers.computeIfAbsent( sourceIndex, (k -> sourceOf(k).getSplitSerializer())); } public void put(int sourceIndex, Source source) { sources.put(sourceIndex, Preconditions.checkNotNull(source)); } public int getFirstSourceIndex() { return sources.firstKey(); } }
SwitchedSources
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/gateway/PersistedClusterStateService.java
{ "start": 7955, "end": 15978 }
class ____ { private static final Logger logger = LogManager.getLogger(PersistedClusterStateService.class); private static final String CURRENT_TERM_KEY = "current_term"; private static final String LAST_ACCEPTED_VERSION_KEY = "last_accepted_version"; private static final String NODE_ID_KEY = "node_id"; private static final String CLUSTER_UUID_KEY = "cluster_uuid"; private static final String CLUSTER_UUID_COMMITTED_KEY = "cluster_uuid_committed"; private static final String OVERRIDDEN_NODE_VERSION_KEY = "overridden_node_version"; static final String NODE_VERSION_KEY = "node_version"; private static final String OLDEST_INDEX_VERSION_KEY = "oldest_index_version"; public static final String TYPE_FIELD_NAME = "type"; public static final String GLOBAL_TYPE_NAME = "global"; public static final String INDEX_TYPE_NAME = "index"; public static final String MAPPING_TYPE_NAME = "mapping"; public static final String PROJECT_ID_FIELD_NAME = "project_id"; private static final String DATA_FIELD_NAME = "data"; private static final String INDEX_UUID_FIELD_NAME = "index_uuid"; private static final String MAPPING_HASH_FIELD_NAME = "mapping_hash"; public static final String PAGE_FIELD_NAME = "page"; public static final String LAST_PAGE_FIELD_NAME = "last_page"; public static final int IS_LAST_PAGE = 1; public static final int IS_NOT_LAST_PAGE = 0; private static final int COMMIT_DATA_SIZE = 7; private static final MergePolicy NO_MERGE_POLICY = noMergePolicy(); private static final MergePolicy DEFAULT_MERGE_POLICY = defaultMergePolicy(); public static final String METADATA_DIRECTORY_NAME = MetadataStateFormat.STATE_DIR_NAME; public static final Setting<TimeValue> SLOW_WRITE_LOGGING_THRESHOLD = Setting.timeSetting( "gateway.slow_write_logging_threshold", TimeValue.timeValueSeconds(10), TimeValue.ZERO, Setting.Property.NodeScope, Setting.Property.Dynamic ); public static final Setting<ByteSizeValue> DOCUMENT_PAGE_SIZE = Setting.byteSizeSetting( "cluster_state.document_page_size", ByteSizeValue.ofMb(1), ByteSizeValue.ONE, ByteSizeValue.ofGb(1), Setting.Property.NodeScope ); private final Path[] dataPaths; private final String nodeId; private final XContentParserConfiguration parserConfig; private final LongSupplier relativeTimeMillisSupplier; private final ByteSizeValue documentPageSize; private volatile TimeValue slowWriteLoggingThreshold; // Whether the cluster has multi-project mode enabled, see also ProjectResolver#supportsMultipleProjects private final BooleanSupplier supportsMultipleProjects; public PersistedClusterStateService( NodeEnvironment nodeEnvironment, NamedXContentRegistry namedXContentRegistry, ClusterSettings clusterSettings, LongSupplier relativeTimeMillisSupplier, BooleanSupplier supportsMultipleProjects ) { this( nodeEnvironment.nodeDataPaths(), nodeEnvironment.nodeId(), namedXContentRegistry, clusterSettings, relativeTimeMillisSupplier, supportsMultipleProjects ); } public PersistedClusterStateService( Path[] dataPaths, String nodeId, NamedXContentRegistry namedXContentRegistry, ClusterSettings clusterSettings, LongSupplier relativeTimeMillisSupplier, BooleanSupplier supportsMultipleProjects ) { this.dataPaths = dataPaths; this.nodeId = nodeId; this.parserConfig = XContentParserConfiguration.EMPTY.withDeprecationHandler(LoggingDeprecationHandler.INSTANCE) .withRegistry(namedXContentRegistry); this.relativeTimeMillisSupplier = relativeTimeMillisSupplier; this.slowWriteLoggingThreshold = clusterSettings.get(SLOW_WRITE_LOGGING_THRESHOLD); this.supportsMultipleProjects = supportsMultipleProjects; clusterSettings.addSettingsUpdateConsumer(SLOW_WRITE_LOGGING_THRESHOLD, this::setSlowWriteLoggingThreshold); this.documentPageSize = clusterSettings.get(DOCUMENT_PAGE_SIZE); } private void setSlowWriteLoggingThreshold(TimeValue slowWriteLoggingThreshold) { this.slowWriteLoggingThreshold = slowWriteLoggingThreshold; } public String getNodeId() { return nodeId; } /** * Creates a new disk-based writer for cluster states */ public Writer createWriter() throws IOException { final List<MetadataIndexWriter> metadataIndexWriters = new ArrayList<>(); final List<Closeable> closeables = new ArrayList<>(); boolean success = false; try { for (final Path path : dataPaths) { final Directory directory = createDirectory(path.resolve(METADATA_DIRECTORY_NAME)); closeables.add(directory); final IndexWriter indexWriter = createIndexWriter(directory, false); closeables.add(indexWriter); metadataIndexWriters.add(new MetadataIndexWriter(path, directory, indexWriter, supportsMultipleProjects.getAsBoolean())); } success = true; } finally { if (success == false) { IOUtils.closeWhileHandlingException(closeables); } } return new Writer( metadataIndexWriters, nodeId, documentPageSize, relativeTimeMillisSupplier, () -> slowWriteLoggingThreshold, getAssertOnCommit() ); } CheckedBiConsumer<Path, DirectoryReader, IOException> getAssertOnCommit() { return Assertions.ENABLED ? this::loadOnDiskState : null; } private static IndexWriter createIndexWriter(Directory directory, boolean openExisting) throws IOException { final IndexWriterConfig indexWriterConfig = new IndexWriterConfig(new KeywordAnalyzer()); indexWriterConfig.setInfoStream(InfoStream.NO_OUTPUT); // start empty since we re-write the whole cluster state to ensure it is all using the same format version indexWriterConfig.setOpenMode(openExisting ? IndexWriterConfig.OpenMode.APPEND : IndexWriterConfig.OpenMode.CREATE); // only commit when specifically instructed, we must not write any intermediate states indexWriterConfig.setCommitOnClose(false); // most of the data goes into stored fields which are not buffered, so each doc written accounts for ~500B of indexing buffer // (see e.g. BufferedUpdates#BYTES_PER_DEL_TERM); a 1MB buffer therefore gets flushed every ~2000 docs. indexWriterConfig.setRAMBufferSizeMB(1.0); // merge on the write thread (e.g. while flushing) indexWriterConfig.setMergeScheduler(new SerialMergeScheduler()); // apply the adjusted merge policy indexWriterConfig.setMergePolicy(DEFAULT_MERGE_POLICY); return new IndexWriter(directory, indexWriterConfig); } /** * Remove all persisted cluster states from the given data paths, for use in tests. Should only be called when there is no open * {@link Writer} on these paths. */ public static void deleteAll(Path[] dataPaths) throws IOException { for (Path dataPath : dataPaths) { Lucene.cleanLuceneIndex(new NIOFSDirectory(dataPath.resolve(METADATA_DIRECTORY_NAME))); } } protected Directory createDirectory(Path path) throws IOException { // it is possible to disable the use of MMapDirectory for indices, and it may be surprising to users that have done so if we still // use a MMapDirectory here, which might happen with FSDirectory.open(path), so we force an NIOFSDirectory to be on the safe side. return new NIOFSDirectory(path); } public Path[] getDataPaths() { return dataPaths; } public static
PersistedClusterStateService
java
apache__camel
components/camel-elasticsearch/src/test/java/org/apache/camel/component/es/integration/ElasticsearchClusterIndexIT.java
{ "start": 1517, "end": 4066 }
class ____ extends ElasticsearchTestSupport { @Test void indexWithIpAndPort() throws Exception { Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<>(); headers.put(ElasticsearchConstants.PARAM_OPERATION, ElasticsearchOperation.Index); headers.put(ElasticsearchConstants.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConstants.PARAM_INDEX_ID, "1"); String indexId = template.requestBodyAndHeaders("direct:indexWithIpAndPort", map, headers, String.class); assertNotNull(indexId, "indexId should be set"); indexId = template.requestBodyAndHeaders("direct:indexWithIpAndPort", map, headers, String.class); assertNotNull(indexId, "indexId should be set"); assertTrue(client.get(new GetRequest.Builder().index("twitter").id("1").build(), ObjectNode.class).found(), "Index id 1 must exists"); } @Test void indexWithSnifferEnable() throws Exception { Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<>(); headers.put(ElasticsearchConstants.PARAM_OPERATION, ElasticsearchOperation.Index); headers.put(ElasticsearchConstants.PARAM_INDEX_NAME, "facebook"); headers.put(ElasticsearchConstants.PARAM_INDEX_ID, "4"); String indexId = template.requestBodyAndHeaders("direct:indexWithSniffer", map, headers, String.class); assertNotNull(indexId, "indexId should be set"); assertTrue(client.get(new GetRequest.Builder().index("facebook").id("4").build(), ObjectNode.class).found(), "Index id 4 must exists"); final BasicResponseHandler responseHandler = new BasicResponseHandler(); Request request = new Request("GET", "/_cluster/health?pretty"); String body = responseHandler.handleEntity(restClient.performRequest(request).getEntity()); assertStringContains(body, "\"number_of_data_nodes\" : 1"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:indexWithIpAndPort") .to("elasticsearch://" + clusterName + "?operation=Index&indexName=twitter"); from("direct:indexWithSniffer") .to("elasticsearch://" + clusterName + "?operation=Index&indexName=twitter&enableSniffer=true"); } }; } }
ElasticsearchClusterIndexIT
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/snapshots/sourceonly/SourceOnlySnapshot.java
{ "start": 2964, "end": 15939 }
class ____ { private static final String FIELDS_INDEX_EXTENSION = INDEX_EXTENSION; private static final String FIELDS_META_EXTENSION = META_EXTENSION; private final LinkedFilesDirectory targetDirectory; private final Supplier<Query> deleteByQuerySupplier; public SourceOnlySnapshot(LinkedFilesDirectory targetDirectory, Supplier<Query> deleteByQuerySupplier) { this.targetDirectory = targetDirectory; this.deleteByQuerySupplier = deleteByQuerySupplier; } public SourceOnlySnapshot(LinkedFilesDirectory targetDirectory) { this(targetDirectory, null); } public synchronized List<String> syncSnapshot(IndexCommit commit) throws IOException { long generation; Map<BytesRef, SegmentCommitInfo> existingSegments = new HashMap<>(); if (Lucene.indexExists(targetDirectory.getWrapped())) { SegmentInfos existingsSegmentInfos = Lucene.readSegmentInfos(targetDirectory.getWrapped()); for (SegmentCommitInfo info : existingsSegmentInfos) { existingSegments.put(new BytesRef(info.info.getId()), info); } generation = existingsSegmentInfos.getGeneration(); } else { generation = 1; } List<String> createdFiles = new ArrayList<>(); String segmentFileName; try ( Lock writeLock = targetDirectory.obtainLock(IndexWriter.WRITE_LOCK_NAME); StandardDirectoryReader reader = (StandardDirectoryReader) DirectoryReader.open(commit) ) { SegmentInfos segmentInfos = reader.getSegmentInfos().clone(); DirectoryReader wrappedReader = wrapReader(reader); List<SegmentCommitInfo> newInfos = new ArrayList<>(); for (LeafReaderContext ctx : wrappedReader.leaves()) { LeafReader leafReader = ctx.reader(); SegmentCommitInfo info = Lucene.segmentReader(leafReader).getSegmentInfo(); LiveDocs liveDocs = getLiveDocs(leafReader); if (leafReader.numDocs() != 0) { // fully deleted segments don't need to be processed SegmentCommitInfo newInfo = syncSegment(info, liveDocs, leafReader.getFieldInfos(), existingSegments, createdFiles); newInfos.add(newInfo); } } segmentInfos.clear(); segmentInfos.addAll(newInfos); segmentInfos.setNextWriteGeneration(Math.max(segmentInfos.getGeneration(), generation) + 1); String pendingSegmentFileName = IndexFileNames.fileNameFromGeneration( IndexFileNames.PENDING_SEGMENTS, "", segmentInfos.getGeneration() ); try (IndexOutput segnOutput = targetDirectory.createOutput(pendingSegmentFileName, IOContext.DEFAULT)) { segmentInfos.write(segnOutput); } targetDirectory.sync(Collections.singleton(pendingSegmentFileName)); targetDirectory.sync(createdFiles); segmentFileName = IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", segmentInfos.getGeneration()); targetDirectory.rename(pendingSegmentFileName, segmentFileName); } Lucene.pruneUnreferencedFiles(segmentFileName, targetDirectory); assert assertCheckIndex(); return Collections.unmodifiableList(createdFiles); } private LiveDocs getLiveDocs(LeafReader reader) throws IOException { if (deleteByQuerySupplier != null) { // we have this additional delete by query functionality to filter out documents before we snapshot them // we can't filter after the fact since we don't have an index anymore. Query query = deleteByQuerySupplier.get(); IndexSearcher s = new IndexSearcher(reader); s.setQueryCache(null); Query rewrite = s.rewrite(query); Weight weight = s.createWeight(rewrite, ScoreMode.COMPLETE_NO_SCORES, 1.0f); Scorer scorer = weight.scorer(reader.getContext()); if (scorer != null) { DocIdSetIterator iterator = scorer.iterator(); if (iterator != null) { Bits liveDocs = reader.getLiveDocs(); final FixedBitSet bits; if (liveDocs != null) { bits = FixedBitSet.copyOf(liveDocs); } else { bits = new FixedBitSet(reader.maxDoc()); bits.set(0, reader.maxDoc()); } int newDeletes = apply(iterator, bits); if (newDeletes != 0) { int numDeletes = reader.numDeletedDocs() + newDeletes; return new LiveDocs(numDeletes, bits); } } } } return new LiveDocs(reader.numDeletedDocs(), reader.getLiveDocs()); } private static int apply(DocIdSetIterator iterator, FixedBitSet bits) throws IOException { int docID = -1; int newDeletes = 0; while ((docID = iterator.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { if (bits.get(docID)) { bits.clear(docID); newDeletes++; } } return newDeletes; } private boolean assertCheckIndex() throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(1024); try (CheckIndex checkIndex = new CheckIndex(targetDirectory)) { checkIndex.setFailFast(true); checkIndex.setInfoStream(new PrintStream(output, false, IOUtils.UTF_8), false); CheckIndex.Status status = checkIndex.checkIndex(); if (status == null || status.clean == false) { throw new RuntimeException("CheckIndex failed: " + output.toString(IOUtils.UTF_8)); } return true; } } DirectoryReader wrapReader(DirectoryReader reader) throws IOException { String softDeletesField = null; for (LeafReaderContext ctx : reader.leaves()) { String field = ctx.reader().getFieldInfos().getSoftDeletesField(); if (field != null) { softDeletesField = field; break; } } return softDeletesField == null ? reader : new SoftDeletesDirectoryReaderWrapper(reader, softDeletesField); } private SegmentCommitInfo syncSegment( SegmentCommitInfo segmentCommitInfo, LiveDocs liveDocs, FieldInfos fieldInfos, Map<BytesRef, SegmentCommitInfo> existingSegments, List<String> createdFiles ) throws IOException { Directory toClose = null; try { SegmentInfo si = segmentCommitInfo.info; Codec codec = si.getCodec(); Directory sourceDir = si.dir; if (si.getUseCompoundFile()) { sourceDir = new LinkedFilesDirectory.CloseMePleaseWrapper(codec.compoundFormat().getCompoundReader(sourceDir, si)); toClose = sourceDir; } final String segmentSuffix = ""; SegmentCommitInfo newInfo; final TrackingDirectoryWrapper trackingDir = new TrackingDirectoryWrapper(targetDirectory); BytesRef segmentId = new BytesRef(si.getId()); boolean exists = existingSegments.containsKey(segmentId); if (exists == false) { SegmentInfo newSegmentInfo = new SegmentInfo( targetDirectory, si.getVersion(), si.getMinVersion(), si.name, si.maxDoc(), false, si.getHasBlocks(), si.getCodec(), si.getDiagnostics(), si.getId(), si.getAttributes(), null ); // we drop the sort on purpose since the field we sorted on doesn't exist in the target index anymore. newInfo = new SegmentCommitInfo(newSegmentInfo, 0, 0, -1, -1, -1, StringHelper.randomId()); List<FieldInfo> fieldInfoCopy = new ArrayList<>(fieldInfos.size()); for (FieldInfo fieldInfo : fieldInfos) { fieldInfoCopy.add( new FieldInfo( fieldInfo.name, fieldInfo.number, false, false, false, IndexOptions.NONE, DocValuesType.NONE, DocValuesSkipIndexType.NONE, -1, fieldInfo.attributes(), 0, 0, 0, 0, VectorEncoding.FLOAT32, VectorSimilarityFunction.EUCLIDEAN, fieldInfo.isSoftDeletesField(), fieldInfo.isParentField() ) ); } FieldInfos newFieldInfos = new FieldInfos(fieldInfoCopy.toArray(new FieldInfo[0])); codec.fieldInfosFormat().write(trackingDir, newSegmentInfo, segmentSuffix, newFieldInfos, IOContext.DEFAULT); newInfo.setFieldInfosFiles(trackingDir.getCreatedFiles()); } else { newInfo = existingSegments.get(segmentId); assert newInfo.info.getUseCompoundFile() == false; } // link files for stored fields to target directory final String idxFile = IndexFileNames.segmentFileName(newInfo.info.name, segmentSuffix, FIELDS_INDEX_EXTENSION); final String dataFile = IndexFileNames.segmentFileName(newInfo.info.name, segmentSuffix, FIELDS_EXTENSION); final String metaFile = IndexFileNames.segmentFileName(newInfo.info.name, segmentSuffix, FIELDS_META_EXTENSION); trackingDir.copyFrom(sourceDir, idxFile, idxFile, IOContext.DEFAULT); assert targetDirectory.linkedFiles.containsKey(idxFile); assert trackingDir.getCreatedFiles().contains(idxFile); trackingDir.copyFrom(sourceDir, dataFile, dataFile, IOContext.DEFAULT); assert targetDirectory.linkedFiles.containsKey(dataFile); assert trackingDir.getCreatedFiles().contains(dataFile); if (Arrays.asList(sourceDir.listAll()).contains(metaFile)) { // only exists for Lucene 8.5+ indices trackingDir.copyFrom(sourceDir, metaFile, metaFile, IOContext.DEFAULT); assert targetDirectory.linkedFiles.containsKey(metaFile); assert trackingDir.getCreatedFiles().contains(metaFile); } if (liveDocs.bits != null && liveDocs.numDeletes != 0 && liveDocs.numDeletes != newInfo.getDelCount()) { assert newInfo.getDelCount() == 0 || assertLiveDocs(liveDocs.bits, liveDocs.numDeletes); codec.liveDocsFormat() .writeLiveDocs(liveDocs.bits, trackingDir, newInfo, liveDocs.numDeletes - newInfo.getDelCount(), IOContext.DEFAULT); SegmentCommitInfo info = new SegmentCommitInfo( newInfo.info, liveDocs.numDeletes, 0, newInfo.getNextDelGen(), -1, -1, StringHelper.randomId() ); info.setFieldInfosFiles(newInfo.getFieldInfosFiles()); info.info.setFiles(trackingDir.getCreatedFiles()); newInfo = info; } if (exists == false) { newInfo.info.setFiles(trackingDir.getCreatedFiles()); codec.segmentInfoFormat().write(trackingDir, newInfo.info, IOContext.DEFAULT); } final Set<String> createdFilesForThisSegment = trackingDir.getCreatedFiles(); createdFilesForThisSegment.remove(idxFile); createdFilesForThisSegment.remove(dataFile); createdFilesForThisSegment.remove(metaFile); createdFiles.addAll(createdFilesForThisSegment); return newInfo; } finally { IOUtils.close(toClose); } } private static boolean assertLiveDocs(Bits liveDocs, int deletes) { int actualDeletes = 0; for (int i = 0; i < liveDocs.length(); i++) { if (liveDocs.get(i) == false) { actualDeletes++; } } assert actualDeletes == deletes : " actual: " + actualDeletes + " deletes: " + deletes; return true; } private static
SourceOnlySnapshot
java
spring-projects__spring-boot
module/spring-boot-webflux/src/test/java/org/springframework/boot/webflux/autoconfigure/actuate/endpoint/web/WebFluxHealthEndpointExtensionAutoConfigurationTests.java
{ "start": 4156, "end": 4412 }
class ____ { @Bean ReactiveHealthIndicator simpleHealthIndicator() { return () -> Mono.just(Health.up().build()); } @Bean HealthIndicator additionalHealthIndicator() { return () -> Health.up().build(); } } }
HealthIndicatorsConfiguration
java
grpc__grpc-java
core/src/main/java/io/grpc/internal/ClientStreamListener.java
{ "start": 733, "end": 2138 }
interface ____ extends StreamListener { /** * Called upon receiving all header information from the remote end-point. Note that transports * are not required to call this method if no header information is received, this would occur * when a stream immediately terminates with an error and only * {@link #closed(io.grpc.Status, RpcProgress, Metadata)} is called. * * <p>This method should return quickly, as the same thread may be used to process other streams. * * @param headers the fully buffered received headers. */ void headersRead(Metadata headers); /** * Called when the stream is fully closed. {@link * io.grpc.Status.Code#OK} is the only status code that is guaranteed * to have been sent from the remote server. Any other status code may have been caused by * abnormal stream termination. This is guaranteed to always be the final call on a listener. No * further callbacks will be issued. * * <p>This method should return quickly, as the same thread may be used to process other streams. * * @param status details about the remote closure * @param rpcProgress RPC progress when client stream listener is closed * @param trailers trailing metadata */ void closed(Status status, RpcProgress rpcProgress, Metadata trailers); /** * The progress of the RPC when client stream listener is closed. */
ClientStreamListener
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/AutoQueueTemplatePropertiesInfo.java
{ "start": 1209, "end": 1511 }
class ____ { private ArrayList<ConfItem> property = new ArrayList<>(); public AutoQueueTemplatePropertiesInfo() { } public ArrayList<ConfItem> getProperty() { return property; } public void add(ConfItem confItem) { property.add(confItem); } }
AutoQueueTemplatePropertiesInfo
java
quarkusio__quarkus
extensions/scheduler/common/src/main/java/io/quarkus/scheduler/common/runtime/CronParser.java
{ "start": 656, "end": 3518 }
class ____ { private final CronType cronType; private final com.cronutils.parser.CronParser cronParser; public CronParser(CronType cronType) { this.cronType = cronType; this.cronParser = new com.cronutils.parser.CronParser(CronDefinitionBuilder.instanceDefinitionFor(cronType)); } public CronType cronType() { return cronType; } public Cron parse(String value) { return cronParser.parse(value); } public Cron mapToQuartz(Cron cron) { switch (cronType) { case QUARTZ: return cron; case UNIX: return CronMapper.fromUnixToQuartz().map(cron); case CRON4J: return CronMapper.fromCron4jToQuartz().map(cron); case SPRING: return CronMapper.fromSpringToQuartz().map(cron); case SPRING53: // https://github.com/jmrozanec/cron-utils/issues/579 return new CronMapper( CronDefinitionBuilder.instanceDefinitionFor(CronType.SPRING53), CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ), setQuestionMark()).map(cron); default: throw new IllegalStateException("Unsupported cron type: " + cronType); } } // Copy from com.cronutils.mapper.CronMapper#setQuestionMark() private static Function<Cron, Cron> setQuestionMark() { return cron -> { final CronField dow = cron.retrieve(CronFieldName.DAY_OF_WEEK); final CronField dom = cron.retrieve(CronFieldName.DAY_OF_MONTH); if (dow == null && dom == null) { return cron; } if (dow.getExpression() instanceof QuestionMark || dom.getExpression() instanceof QuestionMark) { return cron; } final Map<CronFieldName, CronField> fields = new EnumMap<>(CronFieldName.class); fields.putAll(cron.retrieveFieldsAsMap()); if (dow.getExpression() instanceof Always) { fields.put(CronFieldName.DAY_OF_WEEK, new CronField(CronFieldName.DAY_OF_WEEK, questionMark(), fields.get(CronFieldName.DAY_OF_WEEK).getConstraints())); } else { if (dom.getExpression() instanceof Always) { fields.put(CronFieldName.DAY_OF_MONTH, new CronField(CronFieldName.DAY_OF_MONTH, questionMark(), fields.get(CronFieldName.DAY_OF_MONTH).getConstraints())); } else { cron.validate(); } } return new SingleCron(cron.getCronDefinition(), new ArrayList<>(fields.values())); }; } }
CronParser
java
alibaba__nacos
istio/src/main/java/com/alibaba/nacos/istio/config/IstioEnabledFilter.java
{ "start": 1102, "end": 2452 }
class ____ implements NacosPackageExcludeFilter { private static final Logger LOGGER = LoggerFactory.getLogger(IstioEnabledFilter.class); private static final String ISTIO_ENABLED_KEY = "nacos.extension.naming.istio.enabled"; @Override public String getResponsiblePackagePrefix() { return IstioApp.class.getPackage().getName(); } @Override public boolean isExcluded(String className, Set<String> annotationNames) { String functionMode = EnvUtil.getFunctionMode(); // When not specified naming mode or specified all mode, the naming module not start and load. if (isNamingDisabled(functionMode)) { LOGGER.warn("Istio module disabled because function mode is {}, and Istio depend naming module", functionMode); return true; } boolean istioDisabled = !EnvUtil.getProperty(ISTIO_ENABLED_KEY, Boolean.class, false); if (istioDisabled) { LOGGER.warn("Istio module disabled because set {} as false", ISTIO_ENABLED_KEY); } return istioDisabled; } private boolean isNamingDisabled(String functionMode) { if (StringUtils.isEmpty(functionMode)) { return false; } return !FUNCTION_MODE_NAMING.equals(functionMode); } }
IstioEnabledFilter
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/aliasmap/TestSecureAliasMap.java
{ "start": 2425, "end": 5838 }
class ____ { private static HdfsConfiguration baseConf; private static File baseDir; private static MiniKdc kdc; private static String keystoresDir; private static String sslConfDir; private MiniDFSCluster cluster; private HdfsConfiguration conf; private FileSystem fs; @BeforeAll public static void init() throws Exception { baseDir = GenericTestUtils.getTestDir(TestSecureAliasMap.class.getSimpleName()); FileUtil.fullyDelete(baseDir); assertTrue(baseDir.mkdirs()); Properties kdcConf = MiniKdc.createConf(); kdc = new MiniKdc(kdcConf, baseDir); kdc.start(); baseConf = new HdfsConfiguration(); SecurityUtil.setAuthenticationMethod( UserGroupInformation.AuthenticationMethod.KERBEROS, baseConf); UserGroupInformation.setConfiguration(baseConf); assertTrue(UserGroupInformation.isSecurityEnabled(), "Expected configuration to enable security"); String userName = UserGroupInformation.getLoginUser().getShortUserName(); File keytabFile = new File(baseDir, userName + ".keytab"); String keytab = keytabFile.getAbsolutePath(); // Windows will not reverse name lookup "127.0.0.1" to "localhost". String krbInstance = Path.WINDOWS ? "127.0.0.1" : "localhost"; kdc.createPrincipal(keytabFile, userName + "/" + krbInstance, "HTTP/" + krbInstance); keystoresDir = baseDir.getAbsolutePath(); sslConfDir = KeyStoreTestUtil.getClasspathDir(TestSecureNNWithQJM.class); MiniDFSCluster.setupKerberosConfiguration(baseConf, userName, kdc.getRealm(), keytab, keystoresDir, sslConfDir); } @AfterAll public static void destroy() throws Exception { if (kdc != null) { kdc.stop(); } FileUtil.fullyDelete(baseDir); KeyStoreTestUtil.cleanupSSLConfig(keystoresDir, sslConfDir); } @AfterEach public void shutdown() throws IOException { IOUtils.cleanupWithLogger(null, fs); if (cluster != null) { cluster.shutdown(); cluster = null; } } @Test public void testSecureConnectionToAliasMap() throws Exception { conf = new HdfsConfiguration(baseConf); MiniDFSCluster.setupNamenodeProvidedConfiguration(conf); conf.set(DFSConfigKeys.DFS_PROVIDED_ALIASMAP_INMEMORY_RPC_ADDRESS, "127.0.0.1:" + NetUtils.getFreeSocketPort()); int numNodes = 1; cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numNodes) .storageTypes( new StorageType[] {StorageType.DISK, StorageType.PROVIDED}) .build(); cluster.waitActive(); fs = cluster.getFileSystem(); FSNamesystem namesystem = cluster.getNamesystem(); BlockManager blockManager = namesystem.getBlockManager(); DataNode dn = cluster.getDataNodes().get(0); FsDatasetSpi.FsVolumeReferences volumes = dn.getFSDataset().getFsVolumeReferences(); FsVolumeSpi providedVolume = null; for (FsVolumeSpi volume : volumes) { if (volume.getStorageType().equals(StorageType.PROVIDED)) { providedVolume = volume; break; } } String[] bps = providedVolume.getBlockPoolList(); assertEquals(1, bps.length, "Missing provided volume"); BlockAliasMap aliasMap = blockManager.getProvidedStorageMap().getAliasMap(); BlockAliasMap.Reader reader = aliasMap.getReader(null, bps[0]); assertNotNull(reader, "Failed to create blockAliasMap reader"); } }
TestSecureAliasMap
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/util/HandlerUtils.java
{ "start": 3469, "end": 13429 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(HandlerUtils.class); private static final ObjectMapper mapper = RestMapperUtils.getStrictObjectMapper(); /** * Sends the given response and status code to the given channel. * * @param channelHandlerContext identifying the open channel * @param httpRequest originating http request * @param response which should be sent * @param statusCode of the message to send * @param headers additional header values * @param <P> type of the response */ public static <P extends ResponseBody> CompletableFuture<Void> sendResponse( ChannelHandlerContext channelHandlerContext, HttpRequest httpRequest, P response, HttpResponseStatus statusCode, Map<String, String> headers) { StringWriter sw = new StringWriter(); try { mapper.writeValue(sw, response); } catch (IOException ioe) { LOG.error("Internal server error. Could not map response to JSON.", ioe); return sendErrorResponse( channelHandlerContext, httpRequest, new ErrorResponseBody("Internal server error. Could not map response to JSON."), HttpResponseStatus.INTERNAL_SERVER_ERROR, headers); } return sendResponse(channelHandlerContext, httpRequest, sw.toString(), statusCode, headers); } /** * Sends the given error response and status code to the given channel. * * @param channelHandlerContext identifying the open channel * @param httpRequest originating http request * @param errorMessage which should be sent * @param statusCode of the message to send * @param headers additional header values */ public static CompletableFuture<Void> sendErrorResponse( ChannelHandlerContext channelHandlerContext, HttpRequest httpRequest, ErrorResponseBody errorMessage, HttpResponseStatus statusCode, Map<String, String> headers) { return sendErrorResponse( channelHandlerContext, HttpUtil.isKeepAlive(httpRequest), errorMessage, statusCode, headers); } /** * Sends the given error response and status code to the given channel. * * @param channelHandlerContext identifying the open channel * @param keepAlive If the connection should be kept alive. * @param errorMessage which should be sent * @param statusCode of the message to send * @param headers additional header values */ public static CompletableFuture<Void> sendErrorResponse( ChannelHandlerContext channelHandlerContext, boolean keepAlive, ErrorResponseBody errorMessage, HttpResponseStatus statusCode, Map<String, String> headers) { StringWriter sw = new StringWriter(); try { mapper.writeValue(sw, errorMessage); } catch (IOException e) { // this should never happen LOG.error("Internal server error. Could not map error response to JSON.", e); return sendResponse( channelHandlerContext, keepAlive, "Internal server error. Could not map error response to JSON.", HttpResponseStatus.INTERNAL_SERVER_ERROR, headers); } return sendResponse(channelHandlerContext, keepAlive, sw.toString(), statusCode, headers); } /** * Sends the given response and status code to the given channel. * * @param channelHandlerContext identifying the open channel * @param httpRequest originating http request * @param message which should be sent * @param statusCode of the message to send * @param headers additional header values */ public static CompletableFuture<Void> sendResponse( @Nonnull ChannelHandlerContext channelHandlerContext, @Nonnull HttpRequest httpRequest, @Nonnull String message, @Nonnull HttpResponseStatus statusCode, @Nonnull Map<String, String> headers) { return sendResponse( channelHandlerContext, HttpUtil.isKeepAlive(httpRequest), message, statusCode, headers); } /** * Sends the given response and status code to the given channel. * * @param channelHandlerContext identifying the open channel * @param keepAlive If the connection should be kept alive. * @param message which should be sent * @param statusCode of the message to send * @param headers additional header values */ public static CompletableFuture<Void> sendResponse( @Nonnull ChannelHandlerContext channelHandlerContext, boolean keepAlive, @Nonnull String message, @Nonnull HttpResponseStatus statusCode, @Nonnull Map<String, String> headers) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, statusCode); response.headers().set(CONTENT_TYPE, RestConstants.REST_CONTENT_TYPE); for (Map.Entry<String, String> headerEntry : headers.entrySet()) { response.headers().set(headerEntry.getKey(), headerEntry.getValue()); } if (keepAlive) { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); } byte[] buf = message.getBytes(ConfigConstants.DEFAULT_CHARSET); ByteBuf b = Unpooled.copiedBuffer(buf); HttpUtil.setContentLength(response, buf.length); // write the initial line and the header. channelHandlerContext.write(response); channelHandlerContext.write(b); ChannelFuture lastContentFuture = channelHandlerContext.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // close the connection, if no keep-alive is needed if (!keepAlive) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } return toCompletableFuture(lastContentFuture); } public static void transferFile(ChannelHandlerContext ctx, File file, HttpRequest httpRequest) throws FlinkException { final RandomAccessFile randomAccessFile; try { randomAccessFile = new RandomAccessFile(file, "r"); } catch (FileNotFoundException e) { throw new FlinkException("Can not find file " + file + ".", e); } try { final long fileLength = randomAccessFile.length(); final FileChannel fileChannel = randomAccessFile.getChannel(); try { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.headers().set(CONTENT_TYPE, "text/plain"); if (HttpUtil.isKeepAlive(httpRequest)) { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); } HttpUtil.setContentLength(response, fileLength); // write the initial line and the header. ctx.write(response); // write the content. final ChannelFuture lastContentFuture; final GenericFutureListener<Future<? super Void>> completionListener = future -> { fileChannel.close(); randomAccessFile.close(); }; if (ctx.pipeline().get(SslHandler.class) == null) { ctx.write( new DefaultFileRegion(fileChannel, 0, fileLength), ctx.newProgressivePromise()) .addListener(completionListener); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { lastContentFuture = ctx.writeAndFlush( new HttpChunkedInput( new ChunkedFile( randomAccessFile, 0, fileLength, 8192)), ctx.newProgressivePromise()) .addListener(completionListener); // HttpChunkedInput will write the end marker (LastHttpContent) for us. } // close the connection, if no keep-alive is needed if (!HttpUtil.isKeepAlive(httpRequest)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } catch (IOException ex) { fileChannel.close(); throw ex; } } catch (IOException ioe) { try { randomAccessFile.close(); } catch (IOException e) { throw new FlinkException("Close file or channel error.", e); } throw new FlinkException("Could not transfer file " + file + " to the client.", ioe); } } private static CompletableFuture<Void> toCompletableFuture(final ChannelFuture channelFuture) { final CompletableFuture<Void> completableFuture = new CompletableFuture<>(); channelFuture.addListener( future -> { if (future.isSuccess()) { completableFuture.complete(null); } else { completableFuture.completeExceptionally(future.cause()); } }); return completableFuture; } }
HandlerUtils
java
google__gson
gson/src/main/java/com/google/gson/JsonElement.java
{ "start": 3102, "end": 3344 }
class ____ corresponding methods as well: * * <ul> * <li>{@link TypeAdapter#fromJsonTree(JsonElement)} * <li>{@link TypeAdapter#toJsonTree(Object)} * </ul> * * @author Inderjeet Singh * @author Joel Leitch */ public abstract
provides
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/connector/source/SplitEnumeratorContext.java
{ "start": 1177, "end": 1590 }
class ____ the following purposes: * * <ol> * <li>Host information necessary for the SplitEnumerator to make split assignment decisions. * <li>Accept and track the split assignment from the enumerator. * <li>Provide a managed threading model so the split enumerators do not need to create their own * internal threads. * </ol> * * @param <SplitT> the type of the splits. */ @Public public
serves
java
quarkusio__quarkus
core/deployment/src/test/java/io/quarkus/deployment/recording/TestRecorderWithNonSerializableInjectedInConstructor.java
{ "start": 80, "end": 421 }
class ____ { private final NonSerializable constant; @Inject public TestRecorderWithNonSerializableInjectedInConstructor(NonSerializable constant) { this.constant = constant; } public void retrieveConstant() { TestRecorder.RESULT.add(constant); } }
TestRecorderWithNonSerializableInjectedInConstructor
java
netty__netty
common/src/main/java/io/netty/util/internal/ObjectCleaner.java
{ "start": 6058, "end": 6622 }
class ____ extends WeakReference<Object> { private final Runnable cleanupTask; AutomaticCleanerReference(Object referent, Runnable cleanupTask) { super(referent, REFERENCE_QUEUE); this.cleanupTask = cleanupTask; } void cleanup() { cleanupTask.run(); } @Override public Thread get() { return null; } @Override public void clear() { LIVE_SET.remove(this); super.clear(); } } }
AutomaticCleanerReference
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/insert/OracleInsertTest6.java
{ "start": 937, "end": 6187 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = "insert into \"OPS$ADMIN\".\"ORASTAT\" select /*+ rule */ :5 statid, 'C' type, :6 version, bitand(h.spare2,7) flags, ot.name c1, null c2, null c3, c.name c4, u.name c5, h.distcnt n1, h.density n2, h.spare1 n3, h.sample_size n4, h.null_cnt n5, h.minimum n6, h.maximum n7, h.avgcln n8, decode(h.cache_cnt,0,null,1) n9, hg.bucket n10, hg.endpoint n11, null n12, h.timestamp# d1, h.lowval r1, h.hival r2, hg.epvalue ch1 from sys.user$ u, sys.obj$ ot, sys.col$ c, sys.hist_head$ h, histgrm$ hg where :3 is null and u.name = :1 and ot.owner# = u.user# and ot.name = :2 and ot.type# = 2 and c.obj# = ot.obj# and (:4 is null or c.name = :4) and h.obj# = ot.obj# and h.intcol# = c.intcol# and hg.obj#(+) = h.obj# and hg.intcol#(+) = h.intcol# union all select :5 statid, 'C' type, :6 version, bitand(h.spare2,7) flags, ot.name c1, op.subname c2, null c3, c.name c4, u.name c5, h.distcnt n1, h.density n2, h.spare1 n3, h.sample_size n4, h.null_cnt n5, h.minimum n6, h.maximum n7, h.avgcln n8, decode(h.cache_cnt,0,null,1) n9, hg.bucket n10, hg.endpoint n11, null n12, h.timestamp# d1, h.lowval r1, h.hival r2, hg.epvalue ch1 from sys.user$ u, sys.obj$ ot, sys.col$ c, sys.tabpart$ tp, sys.obj$ op, sys.hist_head$ h, histgrm$ hg where u.name = :1 and ot.owner# = u.user# and ot.name = :2 and ot.type# = 2 and c.obj# = ot.obj# and (:4 is null or c.name = :4) and tp.bo# = ot.obj# and tp.obj# = op.obj# and ((:3 is null and :vc_cascade_parts is not null) or op.subname = :3) and h.obj# = op.obj# and h.intcol# = c.intcol# and hg.obj#(+) = h.obj# and hg.intcol#(+) = h.intcol# union all select :5 statid, 'C' type, :6 version, bitand(h.spare2,7) flags, op.name c1, op.subname c2, null c3, c.name c4, u.name c5, h.distcnt n1, h.density n2, h.spare1 n3, h.sample_size n4, h.null_cnt n5, h.minimum n6, h.maximum n7, h.avgcln n8, decode(h.cache_cnt,0,null,1) n9, hg.bucket n10, hg.endpoint n11, null n12, h.timestamp# d1, h.lowval r1, h.hival r2, hg.epvalue ch1 from sys.user$ u, sys.col$ c, sys.tabcompart$ tp, sys.obj$ op, sys.hist_head$ h, histgrm$ hg where u.name = :1 and op.owner# = u.user# and op.name = :2 and op.type# = 19 and ((:3 is null and :vc_cascade_parts is not null) or op.subname = :3) and tp.obj# = op.obj# and c.obj# = tp.bo# and (:4 is null or c.name = :4) and h.obj# = op.obj# and h.intcol# = c.intcol# and hg.obj#(+) = h.obj# and hg.intcol#(+) = h.intcol# union all select :5 statid, 'C' type, :6 version, bitand(h.spare2,7) flags, op.name c1, op.subname c2, os.subname c3, c.name c4, u.name c5, h.distcnt n1, h.density n2, h.spare1 n3, h.sample_size n4, h.null_cnt n5, h.minimum n6, h.maximum n7, h.avgcln n8, decode(h.cache_cnt,0,null,1) n9, hg.bucket n10, hg.endpoint n11, null n12, h.timestamp# d1, h.lowval r1, h.hival r2, hg.epvalue ch1 from sys.user$ u, sys.col$ c, sys.tabcompart$ tp, sys.obj$ op, sys.tabsubpart$ ts, sys.obj$ os, sys.hist_head$ h, histgrm$ hg where u.name = :1 and op.owner# = u.user# and op.name = :2 and op.type# = 19 and tp.obj# = op.obj# and c.obj# = tp.bo# and (:4 is null or c.name = :4) and ts.pobj# = tp.obj# and ts.obj# = os.obj# and ((:3 is null and :vc_cascade_parts is not null) or (op.subname = :3 and (:vc_cascade_parts is not null or os.subname is null)) or os.subname = :3) and h.obj# = os.obj# and h.intcol# = c.intcol# and hg.obj#(+) = h.obj# and hg.intcol#(+) = h.intcol# order by c5,c1,c2,c3,c4,n10"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); statemen.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); assertEquals(9, visitor.getTables().size()); assertEquals(36, visitor.getColumns().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("raises"))); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("employees"))); // // assertTrue(visitor.getColumns().contains(new TableStat.Column("employees", "employee_id"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("employees", "salary"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("employees", "commission_pct"))); } }
OracleInsertTest6
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ErrorTests.java
{ "start": 1406, "end": 2366 }
class ____ { private final WebTestClient client = WebTestClient.bindToController(new TestController()).build(); @Test void notFound(){ this.client.get().uri("/invalid") .exchange() .expectStatus().isNotFound() .expectBody(Void.class); } @Test void serverException() { this.client.get().uri("/server-error") .exchange() .expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) .expectBody(Void.class); } @Test // SPR-17363 void badRequestBeforeRequestBodyConsumed() { EntityExchangeResult<Void> result = this.client.post() .uri("/post") .contentType(MediaType.APPLICATION_JSON) .bodyValue(new Person("Dan")) .exchange() .expectStatus().isBadRequest() .expectBody().isEmpty(); byte[] content = result.getRequestBodyContent(); assertThat(content).isNotNull(); assertThat(new String(content, StandardCharsets.UTF_8)).isEqualTo("{\"name\":\"Dan\"}"); } @RestController static
ErrorTests
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_1800/Issue1834.java
{ "start": 998, "end": 1441 }
class ____{ List<? extends Comparable> keys; public List<? extends Comparable> getKeys() { return keys; } public void setKeys(List<? extends Comparable> keys) { this.keys = keys; } @Override public String toString() { return "IndexQuery{" + "keys=" + keys + '}'; } } static
IndexQuery_Comparable
java
quarkusio__quarkus
integration-tests/oidc-code-flow/src/test/java/io/quarkus/it/keycloak/CodeFlowInGraalITCase.java
{ "start": 187, "end": 240 }
class ____ extends CodeFlowTest { }
CodeFlowInGraalITCase
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/config/SpringRouteNoFromTest.java
{ "start": 1289, "end": 2154 }
class ____ extends SpringTestSupport { @Override @BeforeEach public void setUp() throws Exception { createApplicationContext(); } @Test public void testRouteNoFrom() { // noop } @Override protected AbstractXmlApplicationContext createApplicationContext() { AbstractXmlApplicationContext answer; try { answer = new ClassPathXmlApplicationContext("org/apache/camel/spring/config/SpringRouteNoFromTest.xml"); fail("Should have thrown exception"); } catch (RuntimeCamelException e) { IllegalArgumentException iae = (IllegalArgumentException) e.getCause(); assertEquals("Route myRoute has no inputs: Route(myRoute)[ -> [to[mock:result]]]", iae.getMessage()); return null; } return answer; } }
SpringRouteNoFromTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/messages/webmonitor/RequestJobsOverview.java
{ "start": 1019, "end": 2126 }
class ____ implements InfoMessage { private static final long serialVersionUID = 3052933564788843275L; // ------------------------------------------------------------------------ private static final RequestJobsOverview INSTANCE = new RequestJobsOverview(); public static RequestJobsOverview getInstance() { return INSTANCE; } // ------------------------------------------------------------------------ @Override public int hashCode() { return RequestJobsOverview.class.hashCode(); } @Override public boolean equals(Object obj) { return obj != null && obj.getClass() == RequestJobsOverview.class; } @Override public String toString() { return RequestJobsOverview.class.getSimpleName(); } // ------------------------------------------------------------------------ /** No external instantiation */ private RequestJobsOverview() {} /** Preserve the singleton property by returning the singleton instance */ private Object readResolve() { return INSTANCE; } }
RequestJobsOverview
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ProcessBaseCommand.java
{ "start": 1383, "end": 4840 }
class ____ extends CamelCommand { public ProcessBaseCommand(CamelJBangMain main) { super(main); } List<Long> findPids(String name) { List<Long> pids = new ArrayList<>(); // we need to know the pids of the running camel integrations if (name.matches("\\d+")) { return List.of(Long.parseLong(name)); } else { if (name.endsWith("!")) { // exclusive this name only name = name.substring(0, name.length() - 1); } else if (!name.endsWith("*")) { // lets be open and match all that starts with this pattern name = name + "*"; } } final long cur = ProcessHandle.current().pid(); final String pattern = name; ProcessHandle.allProcesses() .filter(ph -> ph.pid() != cur) .forEach(ph -> { JsonObject root = loadStatus(ph.pid()); // there must be a status file for the running Camel integration if (root != null) { String pName = ProcessHelper.extractName(root, ph); // ignore file extension, so it is easier to match by name pName = FileUtil.onlyName(pName); if (pName != null && !pName.isEmpty() && PatternHelper.matchPattern(pName, pattern)) { pids.add(ph.pid()); } else { // try camel context name JsonObject context = (JsonObject) root.get("context"); if (context != null) { pName = context.getString("name"); if ("CamelJBang".equals(pName)) { pName = null; } if (pName != null && !pName.isEmpty() && PatternHelper.matchPattern(pName, pattern)) { pids.add(ph.pid()); } } } } }); return pids; } public static long extractSince(ProcessHandle ph) { long since = 0; if (ph.info().startInstant().isPresent()) { since = ph.info().startInstant().get().toEpochMilli(); } return since; } JsonObject loadStatus(long pid) { try { Path f = getStatusFile(Long.toString(pid)); if (f != null && Files.exists(f)) { String text = Files.readString(f); return (JsonObject) Jsoner.deserialize(text); } } catch (Exception e) { // ignore } return null; } String sourceLocLine(String location) { while (StringHelper.countChar(location, ':') > 1) { location = location.substring(location.indexOf(':') + 1); } int pos = location.indexOf(':'); // is the colon as scheme or line number String last = location.substring(pos + 1); boolean digits = last.matches("\\d+"); if (!digits) { // it must be scheme so clip that location = location.substring(pos + 1); } location = FileUtil.stripPath(location); return location; } }
ProcessBaseCommand
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/SameSiteNoneIncompatibleClientChecker.java
{ "start": 122, "end": 1640 }
class ____ can check known user agents which are known to be incompatible with SameSite=None attribute. * <p> * <ul> * <li>Versions of Chrome from Chrome 51 to Chrome 66 (inclusive on both ends). * These Chrome versions will reject a cookie with `SameSite=None`. This also * affects older versions of Chromium-derived browsers, as well as Android WebView. * This behavior was correct according to the version of the cookie specification * at that time, but with the addition of the new "None" value to the specification, * this behavior has been updated in Chrome 67 and newer. (Prior to Chrome 51, * the SameSite attribute was ignored entirely and all cookies were treated as if * they were `SameSite=None`.)</li> * <li>Versions of UC Browser on Android prior to version 12.13.2. Older versions * will reject a cookie with `SameSite=None`. This behavior was correct according * to the version of the cookie specification at that time, but with the addition of * the new "None" value to the specification, this behavior has been updated in newer * versions of UC Browser. * <li>Versions of Safari and embedded browsers on MacOS 10.14 and all browsers on iOS 12. * These versions will erroneously treat cookies marked with `SameSite=None` as if they * were marked `SameSite=Strict`. This bug has been fixed on newer versions of iOS and MacOS. * </ul> * <p> * * @see <a href="https://www.chromium.org/updates/same-site/incompatible-clients">SameSite=None: Known Incompatible Clients</a>. */ final
that
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/PromqlBaseParser.java
{ "start": 80989, "end": 99612 }
class ____ extends ParserRuleContext { public TerminalNode AND() { return getToken(PromqlBaseParser.AND, 0); } public TerminalNode BOOL() { return getToken(PromqlBaseParser.BOOL, 0); } public TerminalNode BY() { return getToken(PromqlBaseParser.BY, 0); } public TerminalNode GROUP_LEFT() { return getToken(PromqlBaseParser.GROUP_LEFT, 0); } public TerminalNode GROUP_RIGHT() { return getToken(PromqlBaseParser.GROUP_RIGHT, 0); } public TerminalNode IGNORING() { return getToken(PromqlBaseParser.IGNORING, 0); } public TerminalNode OFFSET() { return getToken(PromqlBaseParser.OFFSET, 0); } public TerminalNode OR() { return getToken(PromqlBaseParser.OR, 0); } public TerminalNode ON() { return getToken(PromqlBaseParser.ON, 0); } public TerminalNode UNLESS() { return getToken(PromqlBaseParser.UNLESS, 0); } public TerminalNode WITHOUT() { return getToken(PromqlBaseParser.WITHOUT, 0); } @SuppressWarnings("this-escape") public NonReservedContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_nonReserved; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PromqlBaseParserListener ) ((PromqlBaseParserListener)listener).enterNonReserved(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PromqlBaseParserListener ) ((PromqlBaseParserListener)listener).exitNonReserved(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof PromqlBaseParserVisitor ) return ((PromqlBaseParserVisitor<? extends T>)visitor).visitNonReserved(this); else return visitor.visitChildren(this); } } public final NonReservedContext nonReserved() throws RecognitionException { NonReservedContext _localctx = new NonReservedContext(_ctx, getState()); enterRule(_localctx, 46, RULE_nonReserved); int _la; try { enterOuterAlt(_localctx, 1); { setState(277); _la = _input.LA(1); if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & 134152192L) != 0)) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) { switch (ruleIndex) { case 1: return expression_sempred((ExpressionContext)_localctx, predIndex); } return true; } private boolean expression_sempred(ExpressionContext _localctx, int predIndex) { switch (predIndex) { case 0: return precpred(_ctx, 10); case 1: return precpred(_ctx, 8); case 2: return precpred(_ctx, 7); case 3: return precpred(_ctx, 6); case 4: return precpred(_ctx, 5); case 5: return precpred(_ctx, 4); case 6: return precpred(_ctx, 1); } return true; } public static final String _serializedATN = "\u0004\u0001/\u0118\u0002\u0000\u0007\u0000\u0002\u0001\u0007\u0001\u0002"+ "\u0002\u0007\u0002\u0002\u0003\u0007\u0003\u0002\u0004\u0007\u0004\u0002"+ "\u0005\u0007\u0005\u0002\u0006\u0007\u0006\u0002\u0007\u0007\u0007\u0002"+ "\b\u0007\b\u0002\t\u0007\t\u0002\n\u0007\n\u0002\u000b\u0007\u000b\u0002"+ "\f\u0007\f\u0002\r\u0007\r\u0002\u000e\u0007\u000e\u0002\u000f\u0007\u000f"+ "\u0002\u0010\u0007\u0010\u0002\u0011\u0007\u0011\u0002\u0012\u0007\u0012"+ "\u0002\u0013\u0007\u0013\u0002\u0014\u0007\u0014\u0002\u0015\u0007\u0015"+ "\u0002\u0016\u0007\u0016\u0002\u0017\u0007\u0017\u0001\u0000\u0001\u0000"+ "\u0001\u0000\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001"+ "\u0001\u0001\u0001\u0001\u0001\u0001\u0003\u0001<\b\u0001\u0001\u0001"+ "\u0001\u0001\u0001\u0001\u0003\u0001A\b\u0001\u0001\u0001\u0001\u0001"+ "\u0001\u0001\u0001\u0001\u0003\u0001G\b\u0001\u0001\u0001\u0001\u0001"+ "\u0001\u0001\u0001\u0001\u0003\u0001M\b\u0001\u0001\u0001\u0001\u0001"+ "\u0001\u0001\u0001\u0001\u0003\u0001S\b\u0001\u0001\u0001\u0003\u0001"+ "V\b\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0003\u0001"+ "\\\b\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0003\u0001"+ "b\b\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001"+ "\u0001\u0001\u0001\u0001\u0003\u0001k\b\u0001\u0005\u0001m\b\u0001\n\u0001"+ "\f\u0001p\t\u0001\u0001\u0002\u0001\u0002\u0003\u0002t\b\u0002\u0001\u0002"+ "\u0001\u0002\u0001\u0002\u0001\u0002\u0001\u0002\u0001\u0002\u0001\u0002"+ "\u0001\u0002\u0001\u0002\u0001\u0002\u0003\u0002\u0080\b\u0002\u0001\u0003"+ "\u0001\u0003\u0001\u0003\u0003\u0003\u0085\b\u0003\u0001\u0004\u0001\u0004"+ "\u0001\u0004\u0003\u0004\u008a\b\u0004\u0001\u0004\u0001\u0004\u0001\u0004"+ "\u0001\u0004\u0001\u0004\u0001\u0004\u0001\u0004\u0001\u0004\u0001\u0004"+ "\u0001\u0004\u0001\u0004\u0001\u0004\u0001\u0004\u0003\u0004\u0099\b\u0004"+ "\u0001\u0005\u0001\u0005\u0001\u0005\u0005\u0005\u009e\b\u0005\n\u0005"+ "\f\u0005\u00a1\t\u0005\u0001\u0006\u0001\u0006\u0001\u0006\u0001\u0007"+ "\u0001\u0007\u0001\u0007\u0001\u0007\u0001\u0007\u0003\u0007\u00ab\b\u0007"+ "\u0001\u0007\u0003\u0007\u00ae\b\u0007\u0001\b\u0001\b\u0001\b\u0003\b"+ "\u00b3\b\b\u0001\b\u0003\b\u00b6\b\b\u0001\b\u0001\b\u0001\b\u0001\b\u0003"+ "\b\u00bc\b\b\u0001\t\u0001\t\u0001\t\u0001\t\u0003\t\u00c2\b\t\u0003\t"+ "\u00c4\b\t\u0001\n\u0001\n\u0001\n\u0003\n\u00c9\b\n\u0005\n\u00cb\b\n"+ "\n\n\f\n\u00ce\t\n\u0001\n\u0001\n\u0001\u000b\u0001\u000b\u0001\u000b"+ "\u0003\u000b\u00d5\b\u000b\u0005\u000b\u00d7\b\u000b\n\u000b\f\u000b\u00da"+ "\t\u000b\u0001\f\u0001\f\u0001\f\u0003\f\u00df\b\f\u0001\r\u0001\r\u0001"+ "\r\u0003\r\u00e4\b\r\u0001\u000e\u0001\u000e\u0003\u000e\u00e8\b\u000e"+ "\u0001\u000f\u0001\u000f\u0003\u000f\u00ec\b\u000f\u0001\u000f\u0001\u000f"+ "\u0003\u000f\u00f0\b\u000f\u0003\u000f\u00f2\b\u000f\u0001\u0010\u0001"+ "\u0010\u0003\u0010\u00f6\b\u0010\u0001\u0010\u0001\u0010\u0001\u0011\u0001"+ "\u0011\u0001\u0012\u0001\u0012\u0003\u0012\u00fe\b\u0012\u0001\u0012\u0001"+ "\u0012\u0001\u0012\u0003\u0012\u0103\b\u0012\u0001\u0013\u0001\u0013\u0001"+ "\u0013\u0003\u0013\u0108\b\u0013\u0001\u0014\u0001\u0014\u0001\u0014\u0003"+ "\u0014\u010d\b\u0014\u0001\u0015\u0001\u0015\u0001\u0016\u0001\u0016\u0001"+ "\u0016\u0003\u0016\u0114\b\u0016\u0001\u0017\u0001\u0017\u0001\u0017\u0000"+ "\u0001\u0002\u0018\u0000\u0002\u0004\u0006\b\n\f\u000e\u0010\u0012\u0014"+ "\u0016\u0018\u001a\u001c\u001e \"$&(*,.\u0000\u000b\u0001\u0000\u0001"+ "\u0002\u0001\u0000\u0003\u0005\u0001\u0000\u0007\f\u0002\u0000\u0010\u0010"+ "\u0012\u0012\u0001\u0000\u0003\u0004\u0001\u0000\u0013\u0014\u0001\u0000"+ "\u0015\u0016\u0001\u0000\u0017\u0018\u0002\u0000\b\b\r\u000f\u0001\u0000"+ "\u001c\u001d\u0001\u0000\u0010\u001a\u0136\u00000\u0001\u0000\u0000\u0000"+ "\u0002;\u0001\u0000\u0000\u0000\u0004\u007f\u0001\u0000\u0000\u0000\u0006"+ "\u0084\u0001\u0000\u0000\u0000\b\u0098\u0001\u0000\u0000\u0000\n\u009a"+ "\u0001\u0000\u0000\u0000\f\u00a2\u0001\u0000\u0000\u0000\u000e\u00a5\u0001"+ "\u0000\u0000\u0000\u0010\u00bb\u0001\u0000\u0000\u0000\u0012\u00bd\u0001"+ "\u0000\u0000\u0000\u0014\u00c5\u0001\u0000\u0000\u0000\u0016\u00d1\u0001"+ "\u0000\u0000\u0000\u0018\u00db\u0001\u0000\u0000\u0000\u001a\u00e3\u0001"+ "\u0000\u0000\u0000\u001c\u00e7\u0001\u0000\u0000\u0000\u001e\u00f1\u0001"+ "\u0000\u0000\u0000 \u00f3\u0001\u0000\u0000\u0000\"\u00f9\u0001\u0000"+ "\u0000\u0000$\u0102\u0001\u0000\u0000\u0000&\u0107\u0001\u0000\u0000\u0000"+ "(\u010c\u0001\u0000\u0000\u0000*\u010e\u0001\u0000\u0000\u0000,\u0113"+ "\u0001\u0000\u0000\u0000.\u0115\u0001\u0000\u0000\u000001\u0003\u0002"+ "\u0001\u000012\u0005\u0000\u0000\u00012\u0001\u0001\u0000\u0000\u0000"+ "34\u0006\u0001\uffff\uffff\u000045\u0007\u0000\u0000\u00005<\u0003\u0002"+ "\u0001\t6<\u0003\u0006\u0003\u000078\u0005\"\u0000\u000089\u0003\u0002"+ "\u0001\u00009:\u0005#\u0000\u0000:<\u0001\u0000\u0000\u0000;3\u0001\u0000"+ "\u0000\u0000;6\u0001\u0000\u0000\u0000;7\u0001\u0000\u0000\u0000<n\u0001"+ "\u0000\u0000\u0000=>\n\n\u0000\u0000>@\u0005\u0006\u0000\u0000?A\u0003"+ "\u0012\t\u0000@?\u0001\u0000\u0000\u0000@A\u0001\u0000\u0000\u0000AB\u0001"+ "\u0000\u0000\u0000Bm\u0003\u0002\u0001\nCD\n\b\u0000\u0000DF\u0007\u0001"+ "\u0000\u0000EG\u0003\u0012\t\u0000FE\u0001\u0000\u0000\u0000FG\u0001\u0000"+ "\u0000\u0000GH\u0001\u0000\u0000\u0000Hm\u0003\u0002\u0001\tIJ\n\u0007"+ "\u0000\u0000JL\u0007\u0000\u0000\u0000KM\u0003\u0012\t\u0000LK\u0001\u0000"+ "\u0000\u0000LM\u0001\u0000\u0000\u0000MN\u0001\u0000\u0000\u0000Nm\u0003"+ "\u0002\u0001\bOP\n\u0006\u0000\u0000PR\u0007\u0002\u0000\u0000QS\u0005"+ "\u0019\u0000\u0000RQ\u0001\u0000\u0000\u0000RS\u0001\u0000\u0000\u0000"+ "SU\u0001\u0000\u0000\u0000TV\u0003\u0012\t\u0000UT\u0001\u0000\u0000\u0000"+ "UV\u0001\u0000\u0000\u0000VW\u0001\u0000\u0000\u0000Wm\u0003\u0002\u0001"+ "\u0007XY\n\u0005\u0000\u0000Y[\u0007\u0003\u0000\u0000Z\\\u0003\u0012"+ "\t\u0000[Z\u0001\u0000\u0000\u0000[\\\u0001\u0000\u0000\u0000\\]\u0001"+ "\u0000\u0000\u0000]m\u0003\u0002\u0001\u0006^_\n\u0004\u0000\u0000_a\u0005"+ "\u0011\u0000\u0000`b\u0003\u0012\t\u0000a`\u0001\u0000\u0000\u0000ab\u0001"+ "\u0000\u0000\u0000bc\u0001\u0000\u0000\u0000cm\u0003\u0002\u0001\u0005"+ "de\n\u0001\u0000\u0000ef\u0005 \u0000\u0000fg\u0003\"\u0011\u0000gh\u0003"+ "\u0004\u0002\u0000hj\u0005!\u0000\u0000ik\u0003\u001e\u000f\u0000ji\u0001"+ "\u0000\u0000\u0000jk\u0001\u0000\u0000\u0000km\u0001\u0000\u0000\u0000"+ "l=\u0001\u0000\u0000\u0000lC\u0001\u0000\u0000\u0000lI\u0001\u0000\u0000"+ "\u0000lO\u0001\u0000\u0000\u0000lX\u0001\u0000\u0000\u0000l^\u0001\u0000"+ "\u0000\u0000ld\u0001\u0000\u0000\u0000mp\u0001\u0000\u0000\u0000nl\u0001"+ "\u0000\u0000\u0000no\u0001\u0000\u0000\u0000o\u0003\u0001\u0000\u0000"+ "\u0000pn\u0001\u0000\u0000\u0000qs\u0005$\u0000\u0000rt\u0003\"\u0011"+ "\u0000sr\u0001\u0000\u0000\u0000st\u0001\u0000\u0000\u0000t\u0080\u0001"+ "\u0000\u0000\u0000uv\u0005*\u0000\u0000vw\u0005\u0006\u0000\u0000w\u0080"+ "\u0003\u0002\u0001\u0000xy\u0005*\u0000\u0000yz\u0007\u0004\u0000\u0000"+ "z\u0080\u0003\u0002\u0001\u0000{|\u0005*\u0000\u0000|}\u0007\u0000\u0000"+ "\u0000}\u0080\u0003\u0002\u0001\u0000~\u0080\u0005*\u0000\u0000\u007f"+ "q\u0001\u0000\u0000\u0000\u007fu\u0001\u0000\u0000\u0000\u007fx\u0001"+ "\u0000\u0000\u0000\u007f{\u0001\u0000\u0000\u0000\u007f~\u0001\u0000\u0000"+ "\u0000\u0080\u0005\u0001\u0000\u0000\u0000\u0081\u0085\u0003\b\u0004\u0000"+ "\u0082\u0085\u0003\u000e\u0007\u0000\u0083\u0085\u0003&\u0013\u0000\u0084"+ "\u0081\u0001\u0000\u0000\u0000\u0084\u0082\u0001\u0000\u0000\u0000\u0084"+ "\u0083\u0001\u0000\u0000\u0000\u0085\u0007\u0001\u0000\u0000\u0000\u0086"+ "\u0087\u0005,\u0000\u0000\u0087\u0089\u0005\"\u0000\u0000\u0088\u008a"+ "\u0003\n\u0005\u0000\u0089\u0088\u0001\u0000\u0000\u0000\u0089\u008a\u0001"+ "\u0000\u0000\u0000\u008a\u008b\u0001\u0000\u0000\u0000\u008b\u0099\u0005"+ "#\u0000\u0000\u008c\u008d\u0005,\u0000\u0000\u008d\u008e\u0005\"\u0000"+ "\u0000\u008e\u008f\u0003\n\u0005\u0000\u008f\u0090\u0005#\u0000\u0000"+ "\u0090\u0091\u0003\f\u0006\u0000\u0091\u0099\u0001\u0000\u0000\u0000\u0092"+ "\u0093\u0005,\u0000\u0000\u0093\u0094\u0003\f\u0006\u0000\u0094\u0095"+ "\u0005\"\u0000\u0000\u0095\u0096\u0003\n\u0005\u0000\u0096\u0097\u0005"+ "#\u0000\u0000\u0097\u0099\u0001\u0000\u0000\u0000\u0098\u0086\u0001\u0000"+ "\u0000\u0000\u0098\u008c\u0001\u0000\u0000\u0000\u0098\u0092\u0001\u0000"+ "\u0000\u0000\u0099\t\u0001\u0000\u0000\u0000\u009a\u009f\u0003\u0002\u0001"+ "\u0000\u009b\u009c\u0005%\u0000\u0000\u009c\u009e\u0003\u0002\u0001\u0000"+ "\u009d\u009b\u0001\u0000\u0000\u0000\u009e\u00a1\u0001\u0000\u0000\u0000"+ "\u009f\u009d\u0001\u0000\u0000\u0000\u009f\u00a0\u0001\u0000\u0000\u0000"+ "\u00a0\u000b\u0001\u0000\u0000\u0000\u00a1\u009f\u0001\u0000\u0000\u0000"+ "\u00a2\u00a3\u0007\u0005\u0000\u0000\u00a3\u00a4\u0003\u0014\n\u0000\u00a4"+ "\r\u0001\u0000\u0000\u0000\u00a5\u00aa\u0003\u0010\b\u0000\u00a6\u00a7"+ "\u0005 \u0000\u0000\u00a7\u00a8\u0003\"\u0011\u0000\u00a8\u00a9\u0005"+ "!\u0000\u0000\u00a9\u00ab\u0001\u0000\u0000\u0000\u00aa\u00a6\u0001\u0000"+ "\u0000\u0000\u00aa\u00ab\u0001\u0000\u0000\u0000\u00ab\u00ad\u0001\u0000"+ "\u0000\u0000\u00ac\u00ae\u0003\u001e\u000f\u0000\u00ad\u00ac\u0001\u0000"+ "\u0000\u0000\u00ad\u00ae\u0001\u0000\u0000\u0000\u00ae\u000f\u0001\u0000"+ "\u0000\u0000\u00af\u00b5\u0003\u001c\u000e\u0000\u00b0\u00b2\u0005\u001e"+ "\u0000\u0000\u00b1\u00b3\u0003\u0016\u000b\u0000\u00b2\u00b1\u0001\u0000"+ "\u0000\u0000\u00b2\u00b3\u0001\u0000\u0000\u0000\u00b3\u00b4\u0001\u0000"+ "\u0000\u0000\u00b4\u00b6\u0005\u001f\u0000\u0000\u00b5\u00b0\u0001\u0000"+ "\u0000\u0000\u00b5\u00b6\u0001\u0000\u0000\u0000\u00b6\u00bc\u0001\u0000"+ "\u0000\u0000\u00b7\u00b8\u0005\u001e\u0000\u0000\u00b8\u00b9\u0003\u0016"+ "\u000b\u0000\u00b9\u00ba\u0005\u001f\u0000\u0000\u00ba\u00bc\u0001\u0000"+ "\u0000\u0000\u00bb\u00af\u0001\u0000\u0000\u0000\u00bb\u00b7\u0001\u0000"+ "\u0000\u0000\u00bc\u0011\u0001\u0000\u0000\u0000\u00bd\u00be\u0007\u0006"+ "\u0000\u0000\u00be\u00c3\u0003\u0014\n\u0000\u00bf\u00c1\u0007\u0007\u0000"+ "\u0000\u00c0\u00c2\u0003\u0014\n\u0000\u00c1\u00c0\u0001\u0000\u0000\u0000"+ "\u00c1\u00c2\u0001\u0000\u0000\u0000\u00c2\u00c4\u0001\u0000\u0000\u0000"+ "\u00c3\u00bf\u0001\u0000\u0000\u0000\u00c3\u00c4\u0001\u0000\u0000\u0000"+ "\u00c4\u0013\u0001\u0000\u0000\u0000\u00c5\u00cc\u0005\"\u0000\u0000\u00c6"+ "\u00c8\u0003\u001a\r\u0000\u00c7\u00c9\u0005%\u0000\u0000\u00c8\u00c7"+ "\u0001\u0000\u0000\u0000\u00c8\u00c9\u0001\u0000\u0000\u0000\u00c9\u00cb"+ "\u0001\u0000\u0000\u0000\u00ca\u00c6\u0001\u0000\u0000\u0000\u00cb\u00ce"+ "\u0001\u0000\u0000\u0000\u00cc\u00ca\u0001\u0000\u0000\u0000\u00cc\u00cd"+ "\u0001\u0000\u0000\u0000\u00cd\u00cf\u0001\u0000\u0000\u0000\u00ce\u00cc"+ "\u0001\u0000\u0000\u0000\u00cf\u00d0\u0005#\u0000\u0000\u00d0\u0015\u0001"+ "\u0000\u0000\u0000\u00d1\u00d8\u0003\u0018\f\u0000\u00d2\u00d4\u0005%"+ "\u0000\u0000\u00d3\u00d5\u0003\u0018\f\u0000\u00d4\u00d3\u0001\u0000\u0000"+ "\u0000\u00d4\u00d5\u0001\u0000\u0000\u0000\u00d5\u00d7\u0001\u0000\u0000"+ "\u0000\u00d6\u00d2\u0001\u0000\u0000\u0000\u00d7\u00da\u0001\u0000\u0000"+ "\u0000\u00d8\u00d6\u0001\u0000\u0000\u0000\u00d8\u00d9\u0001\u0000\u0000"+ "\u0000\u00d9\u0017\u0001\u0000\u0000\u0000\u00da\u00d8\u0001\u0000\u0000"+ "\u0000\u00db\u00de\u0003\u001a\r\u0000\u00dc\u00dd\u0007\b\u0000\u0000"+ "\u00dd\u00df\u0005&\u0000\u0000\u00de\u00dc\u0001\u0000\u0000\u0000\u00de"+ "\u00df\u0001\u0000\u0000\u0000\u00df\u0019\u0001\u0000\u0000\u0000\u00e0"+ "\u00e4\u0003\u001c\u000e\u0000\u00e1\u00e4\u0005&\u0000\u0000\u00e2\u00e4"+ "\u0003(\u0014\u0000\u00e3\u00e0\u0001\u0000\u0000\u0000\u00e3\u00e1\u0001"+ "\u0000\u0000\u0000\u00e3\u00e2\u0001\u0000\u0000\u0000\u00e4\u001b\u0001"+ "\u0000\u0000\u0000\u00e5\u00e8\u0005,\u0000\u0000\u00e6\u00e8\u0003.\u0017"+ "\u0000\u00e7\u00e5\u0001\u0000\u0000\u0000\u00e7\u00e6\u0001\u0000\u0000"+ "\u0000\u00e8\u001d\u0001\u0000\u0000\u0000\u00e9\u00eb\u0003 \u0010\u0000"+ "\u00ea\u00ec\u0003$\u0012\u0000\u00eb\u00ea\u0001\u0000\u0000\u0000\u00eb"+ "\u00ec\u0001\u0000\u0000\u0000\u00ec\u00f2\u0001\u0000\u0000\u0000\u00ed"+ "\u00ef\u0003$\u0012\u0000\u00ee\u00f0\u0003 \u0010\u0000\u00ef\u00ee\u0001"+ "\u0000\u0000\u0000\u00ef\u00f0\u0001\u0000\u0000\u0000\u00f0\u00f2\u0001"+ "\u0000\u0000\u0000\u00f1\u00e9\u0001\u0000\u0000\u0000\u00f1\u00ed\u0001"+ "\u0000\u0000\u0000\u00f2\u001f\u0001\u0000\u0000\u0000\u00f3\u00f5\u0005"+ "\u001a\u0000\u0000\u00f4\u00f6\u0005\u0002\u0000\u0000\u00f5\u00f4\u0001"+ "\u0000\u0000\u0000\u00f5\u00f6\u0001\u0000\u0000\u0000\u00f6\u00f7\u0001"+ "\u0000\u0000\u0000\u00f7\u00f8\u0003\"\u0011\u0000\u00f8!\u0001\u0000"+ "\u0000\u0000\u00f9\u00fa\u0003\u0002\u0001\u0000\u00fa#\u0001\u0000\u0000"+ "\u0000\u00fb\u00fd\u0005\u001b\u0000\u0000\u00fc\u00fe\u0005\u0002\u0000"+ "\u0000\u00fd\u00fc\u0001\u0000\u0000\u0000\u00fd\u00fe\u0001\u0000\u0000"+ "\u0000\u00fe\u00ff\u0001\u0000\u0000\u0000\u00ff\u0103\u0003,\u0016\u0000"+ "\u0100\u0101\u0005\u001b\u0000\u0000\u0101\u0103\u0007\t\u0000\u0000\u0102"+ "\u00fb\u0001\u0000\u0000\u0000\u0102\u0100\u0001\u0000\u0000\u0000\u0103"+ "%\u0001\u0000\u0000\u0000\u0104\u0108\u0003(\u0014\u0000\u0105\u0108\u0003"+ "*\u0015\u0000\u0106\u0108\u0003,\u0016\u0000\u0107\u0104\u0001\u0000\u0000"+ "\u0000\u0107\u0105\u0001\u0000\u0000\u0000\u0107\u0106\u0001\u0000\u0000"+ "\u0000\u0108\'\u0001\u0000\u0000\u0000\u0109\u010d\u0005(\u0000\u0000"+ "\u010a\u010d\u0005\'\u0000\u0000\u010b\u010d\u0005)\u0000\u0000\u010c"+ "\u0109\u0001\u0000\u0000\u0000\u010c\u010a\u0001\u0000\u0000\u0000\u010c"+ "\u010b\u0001\u0000\u0000\u0000\u010d)\u0001\u0000\u0000\u0000\u010e\u010f"+ "\u0005&\u0000\u0000\u010f+\u0001\u0000\u0000\u0000\u0110\u0114\u0005*"+ "\u0000\u0000\u0111\u0114\u0005+\u0000\u0000\u0112\u0114\u0003(\u0014\u0000"+ "\u0113\u0110\u0001\u0000\u0000\u0000\u0113\u0111\u0001\u0000\u0000\u0000"+ "\u0113\u0112\u0001\u0000\u0000\u0000\u0114-\u0001\u0000\u0000\u0000\u0115"+ "\u0116\u0007\n\u0000\u0000\u0116/\u0001\u0000\u0000\u0000(;@FLRU[ajln"+ "s\u007f\u0084\u0089\u0098\u009f\u00aa\u00ad\u00b2\u00b5\u00bb\u00c1\u00c3"+ "\u00c8\u00cc\u00d4\u00d8\u00de\u00e3\u00e7\u00eb\u00ef\u00f1\u00f5\u00fd"+ "\u0102\u0107\u010c\u0113"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
NonReservedContext
java
apache__spark
mllib/src/test/java/org/apache/spark/mllib/random/JavaRandomRDDsSuite.java
{ "start": 1219, "end": 8181 }
class ____ extends SharedSparkSession { @Test public void testUniformRDD() { long m = 1000L; int p = 2; long seed = 1L; JavaDoubleRDD rdd1 = uniformJavaRDD(jsc, m); JavaDoubleRDD rdd2 = uniformJavaRDD(jsc, m, p); JavaDoubleRDD rdd3 = uniformJavaRDD(jsc, m, p, seed); for (JavaDoubleRDD rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); } } @Test public void testNormalRDD() { long m = 1000L; int p = 2; long seed = 1L; JavaDoubleRDD rdd1 = normalJavaRDD(jsc, m); JavaDoubleRDD rdd2 = normalJavaRDD(jsc, m, p); JavaDoubleRDD rdd3 = normalJavaRDD(jsc, m, p, seed); for (JavaDoubleRDD rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); } } @Test public void testLNormalRDD() { double mean = 4.0; double std = 2.0; long m = 1000L; int p = 2; long seed = 1L; JavaDoubleRDD rdd1 = logNormalJavaRDD(jsc, mean, std, m); JavaDoubleRDD rdd2 = logNormalJavaRDD(jsc, mean, std, m, p); JavaDoubleRDD rdd3 = logNormalJavaRDD(jsc, mean, std, m, p, seed); for (JavaDoubleRDD rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); } } @Test public void testPoissonRDD() { double mean = 2.0; long m = 1000L; int p = 2; long seed = 1L; JavaDoubleRDD rdd1 = poissonJavaRDD(jsc, mean, m); JavaDoubleRDD rdd2 = poissonJavaRDD(jsc, mean, m, p); JavaDoubleRDD rdd3 = poissonJavaRDD(jsc, mean, m, p, seed); for (JavaDoubleRDD rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); } } @Test public void testExponentialRDD() { double mean = 2.0; long m = 1000L; int p = 2; long seed = 1L; JavaDoubleRDD rdd1 = exponentialJavaRDD(jsc, mean, m); JavaDoubleRDD rdd2 = exponentialJavaRDD(jsc, mean, m, p); JavaDoubleRDD rdd3 = exponentialJavaRDD(jsc, mean, m, p, seed); for (JavaDoubleRDD rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); } } @Test public void testGammaRDD() { double shape = 1.0; double jscale = 2.0; long m = 1000L; int p = 2; long seed = 1L; JavaDoubleRDD rdd1 = gammaJavaRDD(jsc, shape, jscale, m); JavaDoubleRDD rdd2 = gammaJavaRDD(jsc, shape, jscale, m, p); JavaDoubleRDD rdd3 = gammaJavaRDD(jsc, shape, jscale, m, p, seed); for (JavaDoubleRDD rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); } } @Test public void testUniformVectorRDD() { long m = 100L; int n = 10; int p = 2; long seed = 1L; JavaRDD<Vector> rdd1 = uniformJavaVectorRDD(jsc, m, n); JavaRDD<Vector> rdd2 = uniformJavaVectorRDD(jsc, m, n, p); JavaRDD<Vector> rdd3 = uniformJavaVectorRDD(jsc, m, n, p, seed); for (JavaRDD<Vector> rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); Assertions.assertEquals(n, rdd.first().size()); } } @Test public void testNormalVectorRDD() { long m = 100L; int n = 10; int p = 2; long seed = 1L; JavaRDD<Vector> rdd1 = normalJavaVectorRDD(jsc, m, n); JavaRDD<Vector> rdd2 = normalJavaVectorRDD(jsc, m, n, p); JavaRDD<Vector> rdd3 = normalJavaVectorRDD(jsc, m, n, p, seed); for (JavaRDD<Vector> rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); Assertions.assertEquals(n, rdd.first().size()); } } @Test public void testLogNormalVectorRDD() { double mean = 4.0; double std = 2.0; long m = 100L; int n = 10; int p = 2; long seed = 1L; JavaRDD<Vector> rdd1 = logNormalJavaVectorRDD(jsc, mean, std, m, n); JavaRDD<Vector> rdd2 = logNormalJavaVectorRDD(jsc, mean, std, m, n, p); JavaRDD<Vector> rdd3 = logNormalJavaVectorRDD(jsc, mean, std, m, n, p, seed); for (JavaRDD<Vector> rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); Assertions.assertEquals(n, rdd.first().size()); } } @Test public void testPoissonVectorRDD() { double mean = 2.0; long m = 100L; int n = 10; int p = 2; long seed = 1L; JavaRDD<Vector> rdd1 = poissonJavaVectorRDD(jsc, mean, m, n); JavaRDD<Vector> rdd2 = poissonJavaVectorRDD(jsc, mean, m, n, p); JavaRDD<Vector> rdd3 = poissonJavaVectorRDD(jsc, mean, m, n, p, seed); for (JavaRDD<Vector> rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); Assertions.assertEquals(n, rdd.first().size()); } } @Test public void testExponentialVectorRDD() { double mean = 2.0; long m = 100L; int n = 10; int p = 2; long seed = 1L; JavaRDD<Vector> rdd1 = exponentialJavaVectorRDD(jsc, mean, m, n); JavaRDD<Vector> rdd2 = exponentialJavaVectorRDD(jsc, mean, m, n, p); JavaRDD<Vector> rdd3 = exponentialJavaVectorRDD(jsc, mean, m, n, p, seed); for (JavaRDD<Vector> rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); Assertions.assertEquals(n, rdd.first().size()); } } @Test public void testGammaVectorRDD() { double shape = 1.0; double jscale = 2.0; long m = 100L; int n = 10; int p = 2; long seed = 1L; JavaRDD<Vector> rdd1 = gammaJavaVectorRDD(jsc, shape, jscale, m, n); JavaRDD<Vector> rdd2 = gammaJavaVectorRDD(jsc, shape, jscale, m, n, p); JavaRDD<Vector> rdd3 = gammaJavaVectorRDD(jsc, shape, jscale, m, n, p, seed); for (JavaRDD<Vector> rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); Assertions.assertEquals(n, rdd.first().size()); } } @Test public void testArbitrary() { long size = 10; long seed = 1L; int numPartitions = 0; StringGenerator gen = new StringGenerator(); JavaRDD<String> rdd1 = randomJavaRDD(jsc, gen, size); JavaRDD<String> rdd2 = randomJavaRDD(jsc, gen, size, numPartitions); JavaRDD<String> rdd3 = randomJavaRDD(jsc, gen, size, numPartitions, seed); for (JavaRDD<String> rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(size, rdd.count()); Assertions.assertEquals(2, rdd.first().length()); } } @Test public void testRandomVectorRDD() { UniformGenerator generator = new UniformGenerator(); long m = 100L; int n = 10; int p = 2; long seed = 1L; JavaRDD<Vector> rdd1 = randomJavaVectorRDD(jsc, generator, m, n); JavaRDD<Vector> rdd2 = randomJavaVectorRDD(jsc, generator, m, n, p); JavaRDD<Vector> rdd3 = randomJavaVectorRDD(jsc, generator, m, n, p, seed); for (JavaRDD<Vector> rdd : Arrays.asList(rdd1, rdd2, rdd3)) { Assertions.assertEquals(m, rdd.count()); Assertions.assertEquals(n, rdd.first().size()); } } } // This is just a test generator, it always returns a string of 42
JavaRandomRDDsSuite
java
junit-team__junit5
junit-vintage-engine/src/testFixtures/java/org/junit/vintage/engine/samples/junit4/ParameterizedTimingTestCase.java
{ "start": 905, "end": 1697 }
class ____ { public static Map<String, Instant> EVENTS = new LinkedHashMap<>(); @BeforeClass public static void beforeClass() throws Exception { EVENTS.clear(); } @BeforeParam public static void beforeParam(String param) throws Exception { EVENTS.put("beforeParam(" + param + ")", Instant.now()); Thread.sleep(100); } @AfterParam public static void afterParam(String param) throws Exception { Thread.sleep(100); System.out.println("ParameterizedTimingTestCase.afterParam"); EVENTS.put("afterParam(" + param + ")", Instant.now()); } @Parameters(name = "{0}") public static Iterable<String> parameters() { return List.of("foo", "bar"); } @Parameter public String value; @Test public void test() { assertEquals("foo", value); } }
ParameterizedTimingTestCase
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/management/ManagementAndPrimaryOnPortZeroTest.java
{ "start": 944, "end": 2516 }
class ____ { private static final String APP_PROPS = """ quarkus.management.enabled=true quarkus.management.test-port=0 quarkus.http.test-port=0 """; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addAsResource(new StringAsset(APP_PROPS), "application.properties") .addClasses(MyObserver.class)) .addBuildChainCustomizer(buildCustomizer()); static Consumer<BuildChainBuilder> buildCustomizer() { return new Consumer<BuildChainBuilder>() { @Override public void accept(BuildChainBuilder builder) { builder.addBuildStep(new BuildStep() { @Override public void execute(BuildContext context) { NonApplicationRootPathBuildItem buildItem = context.consume(NonApplicationRootPathBuildItem.class); context.produce(buildItem.routeBuilder() .management() .route("management") .handler(new MyHandler()) .blockingRoute() .build()); } }).produces(RouteBuildItem.class) .consumes(NonApplicationRootPathBuildItem.class) .build(); } }; } public static
ManagementAndPrimaryOnPortZeroTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/indices/rollover/RolloverConfiguration.java
{ "start": 1373, "end": 9097 }
class ____ implements Writeable, ToXContentObject { // The conditions that have concrete values private final RolloverConditions concreteConditions; // The conditions that have the value `auto`, currently only max_age is supported private final Set<String> automaticConditions; public RolloverConfiguration(RolloverConditions concreteConditions, Set<String> automaticConditions) { validate(concreteConditions, automaticConditions); this.concreteConditions = concreteConditions; this.automaticConditions = automaticConditions; } private static void validate(RolloverConditions concreteConditions, Set<String> automaticConditions) { if (automaticConditions.isEmpty()) { return; } // The only supported condition is max_age if (automaticConditions.size() > 1 || automaticConditions.contains(MaxAgeCondition.NAME) == false) { throw new IllegalArgumentException( "Invalid automatic configuration for " + automaticConditions + ", only condition 'max_age' is supported." ); } // If max_age is automatic there should be no concrete value provided if (concreteConditions.getMaxAge() != null) { throw new IllegalArgumentException( "Invalid configuration for 'max_age' can be either have a value or be automatic but not both." ); } } public RolloverConfiguration(RolloverConditions concreteConditions) { this(concreteConditions, Set.of()); } public RolloverConfiguration(StreamInput in) throws IOException { this(new RolloverConditions(in), in.readCollectionAsSet(StreamInput::readString)); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeWriteable(concreteConditions); out.writeStringCollection(automaticConditions); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); concreteConditions.toXContentFragment(builder, params); for (String automaticCondition : automaticConditions) { builder.field(automaticCondition, "auto"); } builder.endObject(); return builder; } /** * Evaluates the automatic conditions and converts the whole configuration to XContent. * For the automatic conditions is also adds the suffix [automatic] */ public XContentBuilder evaluateAndConvertToXContent(XContentBuilder builder, Params params, @Nullable TimeValue retention) throws IOException { builder.startObject(); concreteConditions.toXContentFragment(builder, params); for (String automaticCondition : automaticConditions) { builder.field(automaticCondition, evaluateMaxAgeCondition(retention) + " [automatic]"); } builder.endObject(); return builder; } /** * Evaluates all the automatic conditions based on the provided arguments. */ public RolloverConditions resolveRolloverConditions(@Nullable TimeValue dataRetention) { if (automaticConditions.isEmpty()) { return concreteConditions; } RolloverConditions.Builder builder = RolloverConditions.newBuilder(concreteConditions); if (automaticConditions.contains(MaxAgeCondition.NAME)) { builder.addMaxIndexAgeCondition(evaluateMaxAgeCondition(dataRetention)); } return builder.build(); } // Visible for testing public RolloverConditions getConcreteConditions() { return concreteConditions; } // Visible for testing public Set<String> getAutomaticConditions() { return automaticConditions; } /** * Parses a cluster setting configuration, it expects it to have the following format: "condition1=value1,condition2=value2" * @throws SettingsException if the input is invalid, if there are unknown conditions or invalid format values. * @throws IllegalArgumentException if the input is null or blank. */ public static RolloverConfiguration parseSetting(String input, String setting) { if (Strings.isNullOrBlank(input)) { throw new IllegalArgumentException("The rollover conditions cannot be null or blank"); } String[] sConditions = input.split(","); RolloverConfiguration.ValueParser valueParser = new RolloverConfiguration.ValueParser(); for (String sCondition : sConditions) { String[] keyValue = sCondition.split("="); if (keyValue.length != 2) { throw new SettingsException("Invalid condition: '{}', format must be 'condition=value'", sCondition); } var condition = keyValue[0]; var value = keyValue[1]; if (MaxSizeCondition.NAME.equals(condition)) { valueParser.addMaxIndexSizeCondition(value, setting); } else if (MaxPrimaryShardSizeCondition.NAME.equals(condition)) { valueParser.addMaxPrimaryShardSizeCondition(value, setting); } else if (MaxAgeCondition.NAME.equals(condition)) { valueParser.addMaxIndexAgeCondition(value, setting); } else if (MaxDocsCondition.NAME.equals(condition)) { valueParser.addMaxIndexDocsCondition(value, setting); } else if (MaxPrimaryShardDocsCondition.NAME.equals(condition)) { valueParser.addMaxPrimaryShardDocsCondition(value, setting); } else if (MinSizeCondition.NAME.equals(condition)) { valueParser.addMinIndexSizeCondition(value, setting); } else if (MinPrimaryShardSizeCondition.NAME.equals(condition)) { valueParser.addMinPrimaryShardSizeCondition(value, setting); } else if (MinAgeCondition.NAME.equals(condition)) { valueParser.addMinIndexAgeCondition(value, setting); } else if (MinDocsCondition.NAME.equals(condition)) { valueParser.addMinIndexDocsCondition(value, setting); } else if (MinPrimaryShardDocsCondition.NAME.equals(condition)) { valueParser.addMinPrimaryShardDocsCondition(value, condition); } else { throw new SettingsException("Unknown condition: '{}'", condition); } } return valueParser.getRolloverConfiguration(); } /** * When max_age is auto we’ll use the following retention dependent heuristics to compute the value of max_age: * - If retention is null aka infinite (default), max_age will be 30 days * - If retention is less than or equal to 1 day, max_age will be 1 hour * - If retention is less than or equal to 14 days, max_age will be 1 day * - If retention is less than or equal to 90 days, max_age will be 7 days * - If retention is greater than 90 days, max_age will be 30 days */ static TimeValue evaluateMaxAgeCondition(@Nullable TimeValue retention) { if (retention == null) { return TimeValue.timeValueDays(30); } if (retention.compareTo(TimeValue.timeValueDays(1)) <= 0) { return TimeValue.timeValueHours(1); } if (retention.compareTo(TimeValue.timeValueDays(14)) <= 0) { return TimeValue.timeValueDays(1); } if (retention.compareTo(TimeValue.timeValueDays(90)) <= 0) { return TimeValue.timeValueDays(7); } return TimeValue.timeValueDays(30); } /** * Parses and keeps track of the condition values during parsing */ public static
RolloverConfiguration
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxOnAssembly.java
{ "start": 7419, "end": 8890 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; final int id; final String operator; final String message; int occurrenceCounter; @Nullable ObservedAtInformationNode parent; Set<ObservedAtInformationNode> children; ObservedAtInformationNode(int id, String operator, String message) { this.id = id; this.operator = operator; this.message = message; this.occurrenceCounter = 0; this.children = new LinkedHashSet<>(); } void incrementCount() { this.occurrenceCounter++; } void addNode(ObservedAtInformationNode node) { if (this == node) { return; } if (children.add(node)) { node.parent = this; } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ObservedAtInformationNode node = (ObservedAtInformationNode) o; return id == node.id && operator.equals(node.operator) && message.equals(node.message); } @Override public int hashCode() { return Objects.hash(id, operator, message); } @Override public String toString() { return operator + "{" + "@" + id + (children.isEmpty() ? "" : ", " + children.size() + " children") + '}'; } } /** * The holder for the assembly stacktrace (as its message). * * @implNote this package-private exception needs access to package-private enclosing
ObservedAtInformationNode
java
apache__camel
tests/camel-itest/src/test/java/org/apache/camel/itest/doc/EipDocumentationTest.java
{ "start": 1454, "end": 4500 }
class ____ extends CamelTestSupport { private static final Logger LOG = LoggerFactory.getLogger(EipDocumentationTest.class); @Override public boolean isUseRouteBuilder() { return false; } @Test void testDocumentation() throws Exception { try (CamelContext context = new DefaultCamelContext()) { String json = ((CatalogCamelContext) context).getEipParameterJsonSchema("from"); LOG.info(json); assertNotNull(json, "Should have found json for from"); assertTrue(json.contains("\"name\": \"from\"")); assertTrue(json.contains("\"uri\": { \"kind\": \"attribute\"")); assertTrue(json.contains("\"ref\": { \"kind\": \"attribute\"")); } } @Test void testSplitDocumentation() throws Exception { try (CamelContext context = new DefaultCamelContext()) { String json = ((CatalogCamelContext) context).getEipParameterJsonSchema("split"); LOG.info(json); assertNotNull(json, "Should have found json for split"); assertTrue(json.contains("\"name\": \"split\"")); // there should be javadoc included assertTrue(json.contains("If enabled then processing each splitted messages occurs concurrently.")); // and it support outputs assertTrue(json.contains( "\"outputs\": { \"kind\": \"element\", \"displayName\": \"Outputs\", \"required\": true, \"type\": \"array\", \"javaType\"")); } } @Test void testSimpleDocumentation() throws Exception { try (CamelContext context = new DefaultCamelContext()) { String json = ((CatalogCamelContext) context).getEipParameterJsonSchema("simple"); LOG.info(json); assertNotNull(json, "Should have found json for simple"); assertTrue(json.contains("\"label\": \"language,core,java\"")); assertTrue(json.contains("\"name\": \"simple\"")); } } @Test void testFailOverDocumentation() throws Exception { try (CamelContext context = new DefaultCamelContext()) { String json = ((CatalogCamelContext) context).getEipParameterJsonSchema("failover"); LOG.info(json); assertNotNull(json, "Should have found json for failover"); assertTrue(json.contains("\"name\": \"failover\"")); assertTrue(json.contains( "\"exception\": { \"kind\": \"element\", \"displayName\": \"Exception\", \"required\": false, \"type\": \"array\"" + ", \"javaType\": \"java.util.List<java.lang.String>\", \"deprecated\": false")); } } @Test void testNotFound() throws Exception { try (CamelContext context = new DefaultCamelContext()) { String json = ((CatalogCamelContext) context).getEipParameterJsonSchema("unknown"); assertNull(json, "Should not have found json for unknown"); } } }
EipDocumentationTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/aggregations/pipeline/GapPolicyTests.java
{ "start": 732, "end": 2385 }
class ____ extends AbstractWriteableEnumTestCase { public GapPolicyTests() { super(BucketHelpers.GapPolicy::readFrom); } @Override public void testValidOrdinals() { assertThat(BucketHelpers.GapPolicy.INSERT_ZEROS.ordinal(), equalTo(0)); assertThat(BucketHelpers.GapPolicy.SKIP.ordinal(), equalTo(1)); assertThat(BucketHelpers.GapPolicy.KEEP_VALUES.ordinal(), equalTo(2)); } @Override public void testFromString() { assertThat(BucketHelpers.GapPolicy.parse("insert_zeros", null), equalTo(BucketHelpers.GapPolicy.INSERT_ZEROS)); assertThat(BucketHelpers.GapPolicy.parse("skip", null), equalTo(BucketHelpers.GapPolicy.SKIP)); assertThat(BucketHelpers.GapPolicy.parse("keep_values", null), equalTo(BucketHelpers.GapPolicy.KEEP_VALUES)); ParsingException e = expectThrows(ParsingException.class, () -> BucketHelpers.GapPolicy.parse("does_not_exist", null)); assertThat(e.getMessage(), equalTo("Invalid gap policy: [does_not_exist], accepted values: [insert_zeros, skip, keep_values]")); } @Override public void testReadFrom() throws IOException { assertReadFromStream(0, BucketHelpers.GapPolicy.INSERT_ZEROS); assertReadFromStream(1, BucketHelpers.GapPolicy.SKIP); assertReadFromStream(2, BucketHelpers.GapPolicy.KEEP_VALUES); } @Override public void testWriteTo() throws IOException { assertWriteToStream(BucketHelpers.GapPolicy.INSERT_ZEROS, 0); assertWriteToStream(BucketHelpers.GapPolicy.SKIP, 1); assertWriteToStream(BucketHelpers.GapPolicy.KEEP_VALUES, 2); } }
GapPolicyTests
java
elastic__elasticsearch
libs/native/src/main/java/org/elasticsearch/nativeaccess/jdk/JdkVectorLibrary.java
{ "start": 5972, "end": 13753 }
class ____ implements VectorSimilarityFunctions { /** * Computes the dot product of given unsigned int7 byte vectors. * * <p> Unsigned int7 byte vectors have values in the range of 0 to 127 (inclusive). * * @param a address of the first vector * @param b address of the second vector * @param length the vector dimensions */ static int dotProduct7u(MemorySegment a, MemorySegment b, int length) { checkByteSize(a, b); Objects.checkFromIndexSize(0, length, (int) a.byteSize()); return dot7u(a, b, length); } static void dotProduct7uBulk(MemorySegment a, MemorySegment b, int length, int count, MemorySegment result) { Objects.checkFromIndexSize(0, length * count, (int) a.byteSize()); Objects.checkFromIndexSize(0, length, (int) b.byteSize()); Objects.checkFromIndexSize(0, count * Float.BYTES, (int) result.byteSize()); dot7uBulk(a, b, length, count, result); } /** * Computes the square distance of given unsigned int7 byte vectors. * * <p> Unsigned int7 byte vectors have values in the range of 0 to 127 (inclusive). * * @param a address of the first vector * @param b address of the second vector * @param length the vector dimensions */ static int squareDistance7u(MemorySegment a, MemorySegment b, int length) { checkByteSize(a, b); Objects.checkFromIndexSize(0, length, (int) a.byteSize()); return sqr7u(a, b, length); } /** * Computes the cosine of given float32 vectors. * * @param a address of the first vector * @param b address of the second vector * @param elementCount the vector dimensions, number of float32 elements in the segment */ static float cosineF32(MemorySegment a, MemorySegment b, int elementCount) { checkByteSize(a, b); Objects.checkFromIndexSize(0, elementCount, (int) a.byteSize() / Float.BYTES); return cosf32(a, b, elementCount); } /** * Computes the dot product of given float32 vectors. * * @param a address of the first vector * @param b address of the second vector * @param elementCount the vector dimensions, number of float32 elements in the segment */ static float dotProductF32(MemorySegment a, MemorySegment b, int elementCount) { checkByteSize(a, b); Objects.checkFromIndexSize(0, elementCount, (int) a.byteSize() / Float.BYTES); return dotf32(a, b, elementCount); } /** * Computes the square distance of given float32 vectors. * * @param a address of the first vector * @param b address of the second vector * @param elementCount the vector dimensions, number of float32 elements in the segment */ static float squareDistanceF32(MemorySegment a, MemorySegment b, int elementCount) { checkByteSize(a, b); Objects.checkFromIndexSize(0, elementCount, (int) a.byteSize() / Float.BYTES); return sqrf32(a, b, elementCount); } private static void checkByteSize(MemorySegment a, MemorySegment b) { if (a.byteSize() != b.byteSize()) { throw new IllegalArgumentException("dimensions differ: " + a.byteSize() + "!=" + b.byteSize()); } } private static int dot7u(MemorySegment a, MemorySegment b, int length) { try { return (int) JdkVectorLibrary.dot7u$mh.invokeExact(a, b, length); } catch (Throwable t) { throw new AssertionError(t); } } private static void dot7uBulk(MemorySegment a, MemorySegment b, int length, int count, MemorySegment result) { try { JdkVectorLibrary.dot7uBulk$mh.invokeExact(a, b, length, count, result); } catch (Throwable t) { throw new AssertionError(t); } } private static int sqr7u(MemorySegment a, MemorySegment b, int length) { try { return (int) JdkVectorLibrary.sqr7u$mh.invokeExact(a, b, length); } catch (Throwable t) { throw new AssertionError(t); } } private static float cosf32(MemorySegment a, MemorySegment b, int length) { try { return (float) JdkVectorLibrary.cosf32$mh.invokeExact(a, b, length); } catch (Throwable t) { throw new AssertionError(t); } } private static float dotf32(MemorySegment a, MemorySegment b, int length) { try { return (float) JdkVectorLibrary.dotf32$mh.invokeExact(a, b, length); } catch (Throwable t) { throw new AssertionError(t); } } private static float sqrf32(MemorySegment a, MemorySegment b, int length) { try { return (float) JdkVectorLibrary.sqrf32$mh.invokeExact(a, b, length); } catch (Throwable t) { throw new AssertionError(t); } } static final MethodHandle DOT_HANDLE_7U; static final MethodHandle DOT_HANDLE_7U_BULK; static final MethodHandle SQR_HANDLE_7U; static final MethodHandle COS_HANDLE_FLOAT32; static final MethodHandle DOT_HANDLE_FLOAT32; static final MethodHandle SQR_HANDLE_FLOAT32; static { try { var lookup = MethodHandles.lookup(); var mt = MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class, int.class); DOT_HANDLE_7U = lookup.findStatic(JdkVectorSimilarityFunctions.class, "dotProduct7u", mt); SQR_HANDLE_7U = lookup.findStatic(JdkVectorSimilarityFunctions.class, "squareDistance7u", mt); mt = MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, int.class, int.class, MemorySegment.class); DOT_HANDLE_7U_BULK = lookup.findStatic(JdkVectorSimilarityFunctions.class, "dotProduct7uBulk", mt); mt = MethodType.methodType(float.class, MemorySegment.class, MemorySegment.class, int.class); COS_HANDLE_FLOAT32 = lookup.findStatic(JdkVectorSimilarityFunctions.class, "cosineF32", mt); DOT_HANDLE_FLOAT32 = lookup.findStatic(JdkVectorSimilarityFunctions.class, "dotProductF32", mt); SQR_HANDLE_FLOAT32 = lookup.findStatic(JdkVectorSimilarityFunctions.class, "squareDistanceF32", mt); } catch (NoSuchMethodException | IllegalAccessException e) { throw new RuntimeException(e); } } @Override public MethodHandle dotProductHandle7u() { return DOT_HANDLE_7U; } @Override public MethodHandle dotProductHandle7uBulk() { return DOT_HANDLE_7U_BULK; } @Override public MethodHandle squareDistanceHandle7u() { return SQR_HANDLE_7U; } @Override public MethodHandle cosineHandleFloat32() { return COS_HANDLE_FLOAT32; } @Override public MethodHandle dotProductHandleFloat32() { return DOT_HANDLE_FLOAT32; } @Override public MethodHandle squareDistanceHandleFloat32() { return SQR_HANDLE_FLOAT32; } } }
JdkVectorSimilarityFunctions
java
google__guava
guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
{ "start": 28071, "end": 28289 }
class ____ extends ClassThatFailsToThrowForStatic {} public void testSubclassThatFailsToThrowForStatic() { shouldFail(SubclassThatFailsToThrowForStatic.class); } private static
SubclassThatFailsToThrowForStatic
java
google__guice
core/src/com/google/inject/Scope.java
{ "start": 908, "end": 1225 }
class ____ * required it, and then immediately forgets it. Associating a scope with a particular binding * allows the created instance to be "remembered" and possibly used again for other injections. * * <p>An example of a scope is {@link Scopes#SINGLETON}. * * @author crazybob@google.com (Bob Lee) */ public
that
java
google__dagger
javatests/dagger/internal/codegen/ProductionComponentProcessorTest.java
{ "start": 2696, "end": 3016 }
interface ____ abstract class"); }); } @Test public void componentOnEnum() { Source componentFile = CompilerTests.javaSource("test.NotAComponent", "package test;", "", "import dagger.producers.ProductionComponent;", "", "@ProductionComponent", "
or
java
apache__dubbo
dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrap.java
{ "start": 3452, "end": 3718 }
class ____ Dubbo * <p> * Get singleton instance by calling static method {@link #getInstance()}. * Designed as singleton because some classes inside Dubbo, such as ExtensionLoader, are designed only for one instance per process. * * @since 2.7.5 */ public final
of
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/impl/LifecycleStrategyServiceTest.java
{ "start": 1106, "end": 1751 }
class ____ extends TestSupport { private final MyLifecycleStrategy dummy1 = new MyLifecycleStrategy(); protected CamelContext createCamelContext() { CamelContext context = new DefaultCamelContext(); context.addLifecycleStrategy(dummy1); return context; } @Test public void testLifecycleStrategyService() throws Exception { assertFalse(dummy1.isStarted()); CamelContext context = createCamelContext(); context.start(); assertTrue(dummy1.isStarted()); context.stop(); assertFalse(dummy1.isStarted()); } private static
LifecycleStrategyServiceTest
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java
{ "start": 2532, "end": 10992 }
class ____ { private ApplicationContext context; private JaasAuthenticationProvider jaasProvider; private JaasEventCheck eventCheck; @BeforeEach public void setUp() { String resName = "/" + getClass().getName().replace('.', '/') + ".xml"; this.context = new ClassPathXmlApplicationContext(resName); this.eventCheck = (JaasEventCheck) this.context.getBean("eventCheck"); this.jaasProvider = (JaasAuthenticationProvider) this.context.getBean("jaasAuthenticationProvider"); } @Test public void testBadPassword() { assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.jaasProvider .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "asdf"))); assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull(); assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null") .isNotNull(); assertThat(this.eventCheck.successEvent).as("Success event was fired").isNull(); } @Test public void testBadUser() { assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.jaasProvider .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("asdf", "password"))); assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull(); assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null") .isNotNull(); assertThat(this.eventCheck.successEvent).as("Success event was fired").isNull(); } @Test public void testConfigurationLoop() throws Exception { String resName = "/" + getClass().getName().replace('.', '/') + ".conf"; URL url = getClass().getResource(resName); Security.setProperty("login.config.url.1", url.toString()); setUp(); testFull(); } @Test public void detectsMissingLoginConfig() throws Exception { JaasAuthenticationProvider myJaasProvider = new JaasAuthenticationProvider(); myJaasProvider.setApplicationEventPublisher(this.context); myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters()); myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers()); myJaasProvider.setLoginContextName(this.jaasProvider.getLoginContextName()); assertThatIllegalArgumentException().isThrownBy(() -> myJaasProvider.afterPropertiesSet()) .withMessageStartingWith("loginConfig must be set on"); } // SEC-1239 @Test public void spacesInLoginConfigPathAreAccepted() throws Exception { File configFile; // Create temp directory with a space in the name File configDir = new File(System.getProperty("java.io.tmpdir") + File.separator + "jaas test"); configDir.deleteOnExit(); if (configDir.exists()) { configDir.delete(); } configDir.mkdir(); configFile = File.createTempFile("login", "conf", configDir); configFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(configFile); PrintWriter pw = new PrintWriter(fos); pw.append( "JAASTestBlah {" + "org.springframework.security.authentication.jaas.TestLoginModule required;" + "};"); pw.flush(); pw.close(); JaasAuthenticationProvider myJaasProvider = new JaasAuthenticationProvider(); myJaasProvider.setApplicationEventPublisher(this.context); myJaasProvider.setLoginConfig(new FileSystemResource(configFile)); myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters()); myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers()); myJaasProvider.setLoginContextName(this.jaasProvider.getLoginContextName()); myJaasProvider.afterPropertiesSet(); } @Test public void detectsMissingLoginContextName() throws Exception { JaasAuthenticationProvider myJaasProvider = new JaasAuthenticationProvider(); myJaasProvider.setApplicationEventPublisher(this.context); myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters()); myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers()); myJaasProvider.setLoginConfig(this.jaasProvider.getLoginConfig()); myJaasProvider.setLoginContextName(null); assertThatIllegalArgumentException().isThrownBy(myJaasProvider::afterPropertiesSet) .withMessageStartingWith("loginContextName must be set on"); myJaasProvider.setLoginContextName(""); assertThatIllegalArgumentException().isThrownBy(myJaasProvider::afterPropertiesSet) .withMessageStartingWith("loginContextName must be set on"); } @Test public void testFull() { UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("user", "password", AuthorityUtils.createAuthorityList("ROLE_ONE")); assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); Authentication auth = this.jaasProvider.authenticate(token); assertThat(this.jaasProvider.getAuthorityGranters()).isNotNull(); assertThat(this.jaasProvider.getCallbackHandlers()).isNotNull(); assertThat(this.jaasProvider.getLoginConfig()).isNotNull(); assertThat(this.jaasProvider.getLoginContextName()).isNotNull(); Collection<? extends GrantedAuthority> list = auth.getAuthorities(); Set<String> set = AuthorityUtils.authorityListToSet(list); assertThat(set.contains("ROLE_ONE")).withFailMessage("GrantedAuthorities should not contain ROLE_ONE") .isFalse(); assertThat(set.contains("ROLE_TEST1")).withFailMessage("GrantedAuthorities should contain ROLE_TEST1").isTrue(); assertThat(set.contains("ROLE_TEST2")).withFailMessage("GrantedAuthorities should contain ROLE_TEST2").isTrue(); boolean foundit = false; for (GrantedAuthority a : list) { if (a instanceof JaasGrantedAuthority grant) { assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority") .isNotNull(); foundit = true; } } assertThat(foundit).as("Could not find a JaasGrantedAuthority").isTrue(); assertThat(this.eventCheck.successEvent).as("Success event should be fired").isNotNull(); assertThat(this.eventCheck.successEvent.getAuthentication()).withFailMessage("Auth objects should be equal") .isEqualTo(auth); assertThat(this.eventCheck.failedEvent).as("Failure event should not be fired").isNull(); } @Test public void testGetApplicationEventPublisher() { assertThat(this.jaasProvider.getApplicationEventPublisher()).isNotNull(); } @Test public void testLoginExceptionResolver() { assertThat(this.jaasProvider.getLoginExceptionResolver()).isNotNull(); this.jaasProvider.setLoginExceptionResolver((e) -> new LockedException("This is just a test!")); try { this.jaasProvider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password")); } catch (LockedException ex) { } catch (Exception ex) { fail("LockedException should have been thrown and caught"); } } @Test public void testLogout() throws Exception { MockLoginContext loginContext = new MockLoginContext(this.jaasProvider.getLoginContextName()); JaasAuthenticationToken token = new JaasAuthenticationToken(null, null, loginContext); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(token); SessionDestroyedEvent event = mock(SessionDestroyedEvent.class); given(event.getSecurityContexts()).willReturn(Arrays.asList(context)); this.jaasProvider.handleLogout(event); assertThat(loginContext.loggedOut).isTrue(); } @Test public void testNullDefaultAuthorities() { UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", "password"); assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); Authentication auth = this.jaasProvider.authenticate(token); SecurityAssertions.assertThat(auth) .roles() .withFailMessage("Only ROLE_TEST1 and ROLE_TEST2 should have been returned") .hasSize(2); } @Test public void testUnsupportedAuthenticationObjectReturnsNull() { assertThat(this.jaasProvider .authenticate(new TestingAuthenticationToken("foo", "bar", AuthorityUtils.NO_AUTHORITIES))).isNull(); } @Test public void authenticateWhenSuccessThenIssuesFactor() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password"); Authentication result = this.jaasProvider.authenticate(token); SecurityAssertions.assertThat(result).hasAuthority(FactorGrantedAuthority.PASSWORD_AUTHORITY); } private static
JaasAuthenticationProviderTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JUnit4TestNotRunTest.java
{ "start": 23719, "end": 24152 }
class ____ { // BUG: Diagnostic contains: public void testMyTheory(@FromDataPoints("foo") Object foo) { fail(); } } """) .doTest(); } @Test public void annotationOnSuperMethod() { compilationHelper .addSourceLines( "TestSuper.java", """ import org.junit.Test; public
TestTheories
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/datasource/unpooled/UnpooledDataSource.java
{ "start": 1214, "end": 7544 }
class ____ implements DataSource { private ClassLoader driverClassLoader; private Properties driverProperties; private static final Map<String, Driver> registeredDrivers = new ConcurrentHashMap<>(); private String driver; private String url; private String username; private String password; private Boolean autoCommit; private Integer defaultTransactionIsolationLevel; private Integer defaultNetworkTimeout; static { Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); registeredDrivers.put(driver.getClass().getName(), driver); } } public UnpooledDataSource() { } public UnpooledDataSource(String driver, String url, String username, String password) { this.driver = driver; this.url = url; this.username = username; this.password = password; } public UnpooledDataSource(String driver, String url, Properties driverProperties) { this.driver = driver; this.url = url; this.driverProperties = driverProperties; } public UnpooledDataSource(ClassLoader driverClassLoader, String driver, String url, String username, String password) { this.driverClassLoader = driverClassLoader; this.driver = driver; this.url = url; this.username = username; this.password = password; } public UnpooledDataSource(ClassLoader driverClassLoader, String driver, String url, Properties driverProperties) { this.driverClassLoader = driverClassLoader; this.driver = driver; this.url = url; this.driverProperties = driverProperties; } @Override public Connection getConnection() throws SQLException { return doGetConnection(username, password); } @Override public Connection getConnection(String username, String password) throws SQLException { return doGetConnection(username, password); } @Override public void setLoginTimeout(int loginTimeout) { DriverManager.setLoginTimeout(loginTimeout); } @Override public int getLoginTimeout() { return DriverManager.getLoginTimeout(); } @Override public void setLogWriter(PrintWriter logWriter) { DriverManager.setLogWriter(logWriter); } @Override public PrintWriter getLogWriter() { return DriverManager.getLogWriter(); } public ClassLoader getDriverClassLoader() { return driverClassLoader; } public void setDriverClassLoader(ClassLoader driverClassLoader) { this.driverClassLoader = driverClassLoader; } public Properties getDriverProperties() { return driverProperties; } public void setDriverProperties(Properties driverProperties) { this.driverProperties = driverProperties; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Boolean isAutoCommit() { return autoCommit; } public void setAutoCommit(Boolean autoCommit) { this.autoCommit = autoCommit; } public Integer getDefaultTransactionIsolationLevel() { return defaultTransactionIsolationLevel; } public void setDefaultTransactionIsolationLevel(Integer defaultTransactionIsolationLevel) { this.defaultTransactionIsolationLevel = defaultTransactionIsolationLevel; } /** * Gets the default network timeout. * * @return the default network timeout * * @since 3.5.2 */ public Integer getDefaultNetworkTimeout() { return defaultNetworkTimeout; } /** * Sets the default network timeout value to wait for the database operation to complete. See * {@link Connection#setNetworkTimeout(java.util.concurrent.Executor, int)} * * @param defaultNetworkTimeout * The time in milliseconds to wait for the database operation to complete. * * @since 3.5.2 */ public void setDefaultNetworkTimeout(Integer defaultNetworkTimeout) { this.defaultNetworkTimeout = defaultNetworkTimeout; } private Connection doGetConnection(String username, String password) throws SQLException { Properties props = new Properties(); if (driverProperties != null) { props.putAll(driverProperties); } if (username != null) { props.setProperty("user", username); } if (password != null) { props.setProperty("password", password); } return doGetConnection(props); } private Connection doGetConnection(Properties properties) throws SQLException { initializeDriver(); Connection connection = DriverManager.getConnection(url, properties); configureConnection(connection); return connection; } private void initializeDriver() throws SQLException { try { registeredDrivers.computeIfAbsent(driver, x -> { Class<?> driverType; try { if (driverClassLoader != null) { driverType = Class.forName(x, true, driverClassLoader); } else { driverType = Resources.classForName(x); } Driver driverInstance = (Driver) driverType.getDeclaredConstructor().newInstance(); DriverManager.registerDriver(new DriverProxy(driverInstance)); return driverInstance; } catch (Exception e) { throw new RuntimeException("Error setting driver on UnpooledDataSource.", e); } }); } catch (RuntimeException re) { throw new SQLException("Error setting driver on UnpooledDataSource.", re.getCause()); } } private void configureConnection(Connection conn) throws SQLException { if (defaultNetworkTimeout != null) { conn.setNetworkTimeout(Executors.newSingleThreadExecutor(), defaultNetworkTimeout); } if (autoCommit != null && autoCommit != conn.getAutoCommit()) { conn.setAutoCommit(autoCommit); } if (defaultTransactionIsolationLevel != null) { conn.setTransactionIsolation(defaultTransactionIsolationLevel); } } private static
UnpooledDataSource
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/client/api/TimelineClient.java
{ "start": 2035, "end": 6858 }
class ____ extends CompositeService implements Flushable { /** * Creates an instance of the timeline v.1.x client. * The current UGI when the user initialize the client will be used to do the * put and the delegation token operations. The current user may use * {@link UserGroupInformation#doAs} another user to construct and initialize * a timeline client if the following operations are supposed to be conducted * by that user. * * @return the created timeline client instance */ @Public public static TimelineClient createTimelineClient() { TimelineClient client = new TimelineClientImpl(); return client; } protected TimelineClient(String name) { super(name); } /** * <p> * Send the information of a number of conceptual entities to the timeline * server. It is a blocking API. The method will not return until it gets the * response from the timeline server. * </p> * * @param entities * the collection of {@link TimelineEntity} * @return the error information if the sent entities are not correctly stored * @throws IOException if there are I/O errors * @throws YarnException if entities are incomplete/invalid */ @Public public abstract TimelinePutResponse putEntities( TimelineEntity... entities) throws IOException, YarnException; /** * <p> * Send the information of a number of conceptual entities to the timeline * server. It is a blocking API. The method will not return until it gets the * response from the timeline server. * * This API is only for timeline service v1.5 * </p> * * @param appAttemptId {@link ApplicationAttemptId} * @param groupId {@link TimelineEntityGroupId} * @param entities * the collection of {@link TimelineEntity} * @return the error information if the sent entities are not correctly stored * @throws IOException if there are I/O errors * @throws YarnException if entities are incomplete/invalid */ @Public public abstract TimelinePutResponse putEntities( ApplicationAttemptId appAttemptId, TimelineEntityGroupId groupId, TimelineEntity... entities) throws IOException, YarnException; /** * <p> * Send the information of a domain to the timeline server. It is a * blocking API. The method will not return until it gets the response from * the timeline server. * </p> * * @param domain * an {@link TimelineDomain} object * @throws IOException io error occur. * @throws YarnException exceptions from yarn servers. */ @Public public abstract void putDomain( TimelineDomain domain) throws IOException, YarnException; /** * <p> * Send the information of a domain to the timeline server. It is a * blocking API. The method will not return until it gets the response from * the timeline server. * * This API is only for timeline service v1.5 * </p> * * @param domain * an {@link TimelineDomain} object * @param appAttemptId {@link ApplicationAttemptId} * @throws IOException io error occur. * @throws YarnException exceptions from yarn servers. */ @Public public abstract void putDomain(ApplicationAttemptId appAttemptId, TimelineDomain domain) throws IOException, YarnException; /** * <p> * Get a delegation token so as to be able to talk to the timeline server in a * secure way. * </p> * * @param renewer * Address of the renewer who can renew these tokens when needed by * securely talking to the timeline server * @return a delegation token ({@link Token}) that can be used to talk to the * timeline server * @throws IOException io error occur. * @throws YarnException exceptions from yarn servers. */ @Public public abstract Token<TimelineDelegationTokenIdentifier> getDelegationToken( String renewer) throws IOException, YarnException; /** * <p> * Renew a timeline delegation token. * </p> * * @param timelineDT * the delegation token to renew * @return the new expiration time * @throws IOException io error occur. * @throws YarnException exceptions from yarn servers. */ @Public public abstract long renewDelegationToken( Token<TimelineDelegationTokenIdentifier> timelineDT) throws IOException, YarnException; /** * <p> * Cancel a timeline delegation token. * </p> * * @param timelineDT * the delegation token to cancel * @throws IOException io error occur. * @throws YarnException exceptions from yarn servers. */ @Public public abstract void cancelDelegationToken( Token<TimelineDelegationTokenIdentifier> timelineDT) throws IOException, YarnException; }
TimelineClient
java
apache__flink
flink-examples/flink-examples-streaming/src/main/java/org/apache/flink/streaming/examples/statemachine/dfa/Transition.java
{ "start": 1312, "end": 3296 }
class ____ serializable to be able to interact cleanly with enums. private static final long serialVersionUID = 1L; /** The event that triggers the transition. */ private final EventType eventType; /** The target state after the transition. */ private final State targetState; /** The probability of the transition. */ private final float prob; /** * Creates a new transition. * * @param eventType The event that triggers the transition. * @param targetState The target state after the transition. * @param prob The probability of the transition. */ public Transition(EventType eventType, State targetState, float prob) { this.eventType = checkNotNull(eventType); this.targetState = checkNotNull(targetState); this.prob = prob; } // ------------------------------------------------------------------------ public EventType eventType() { return eventType; } public State targetState() { return targetState; } public float prob() { return prob; } // ------------------------------------------------------------------------ @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj == null || getClass() != obj.getClass()) { return false; } else { final Transition that = (Transition) obj; return this.eventType == that.eventType && this.targetState == that.targetState && Float.compare(this.prob, that.prob) == 0; } } @Override public int hashCode() { int code = 31 * eventType.hashCode() + targetState.hashCode(); return 31 * code + (prob != +0.0f ? Float.floatToIntBits(prob) : 0); } @Override public String toString() { return "--[" + eventType.name() + "]--> " + targetState.name() + " (" + prob + ')'; } }
is
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/cache/interceptor/CacheInterceptor.java
{ "start": 1144, "end": 1491 }
class ____ * contains the integration with Spring's underlying caching API. * CacheInterceptor simply calls the relevant superclass methods * in the correct order. * * <p>CacheInterceptors are thread-safe. * * @author Costin Leau * @author Juergen Hoeller * @author Sebastien Deleuze * @since 3.1 */ @SuppressWarnings("serial") public
which
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/aop/introduction/with_around/MyBean8.java
{ "start": 738, "end": 1079 }
class ____ { private Long id; private String name; public MyBean8() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
MyBean8
java
spring-projects__spring-boot
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/actuator/loggers/opentelemetry/OpenTelemetryAppenderInitializer.java
{ "start": 946, "end": 1274 }
class ____ implements InitializingBean { private final OpenTelemetry openTelemetry; OpenTelemetryAppenderInitializer(OpenTelemetry openTelemetry) { this.openTelemetry = openTelemetry; } @Override public void afterPropertiesSet() { OpenTelemetryAppender.install(this.openTelemetry); } }
OpenTelemetryAppenderInitializer
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptivebatch/DefaultAdaptiveExecutionHandlerTest.java
{ "start": 11230, "end": 12707 }
class ____ implements StreamGraphOptimizationStrategy { private static final Set<String> convertToReBalanceEdgeIds = new HashSet<>(); @Override public boolean onOperatorsFinished( OperatorsFinished operatorsFinished, StreamGraphContext context) { List<Integer> finishedStreamNodeIds = operatorsFinished.getFinishedStreamNodeIds(); List<StreamEdgeUpdateRequestInfo> requestInfos = new ArrayList<>(); for (Integer finishedStreamNodeId : finishedStreamNodeIds) { for (ImmutableStreamEdge outEdge : context.getStreamGraph() .getStreamNode(finishedStreamNodeId) .getOutEdges()) { if (convertToReBalanceEdgeIds.contains(outEdge.getEdgeId())) { StreamEdgeUpdateRequestInfo requestInfo = new StreamEdgeUpdateRequestInfo( outEdge.getEdgeId(), outEdge.getSourceId(), outEdge.getTargetId()); requestInfo.withOutputPartitioner(new RebalancePartitioner<>()); requestInfos.add(requestInfo); } } } return context.modifyStreamEdge(requestInfos); } } }
TestingStreamGraphOptimizerStrategy
java
spring-projects__spring-framework
spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java
{ "start": 22256, "end": 22338 }
class ____ { } @Aspect("percflowbelow(execution(* *(..)))") static
PerCflowAspect
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/associations/FieldWithUnderscoreTest.java
{ "start": 972, "end": 1046 }
class ____ { @Id Long _id; @ManyToOne(fetch = FetchType.LAZY) A _a; } }
B
java
elastic__elasticsearch
modules/data-streams/src/main/java/org/elasticsearch/datastreams/lifecycle/action/DeleteDataStreamLifecycleAction.java
{ "start": 1409, "end": 4263 }
class ____ extends AcknowledgedRequest<Request> implements IndicesRequest.Replaceable { private String[] names; private IndicesOptions indicesOptions = IndicesOptions.builder() .concreteTargetOptions(IndicesOptions.ConcreteTargetOptions.ERROR_WHEN_UNAVAILABLE_TARGETS) .wildcardOptions( IndicesOptions.WildcardOptions.builder() .matchOpen(true) .matchClosed(true) .includeHidden(false) .resolveAliases(false) .allowEmptyExpressions(true) .build() ) .gatekeeperOptions( IndicesOptions.GatekeeperOptions.builder() .allowAliasToMultipleIndices(false) .allowClosedIndices(true) .ignoreThrottled(false) .allowSelectors(false) .build() ) .build(); public Request(StreamInput in) throws IOException { super(in); this.names = in.readOptionalStringArray(); this.indicesOptions = IndicesOptions.readIndicesOptions(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeOptionalStringArray(names); indicesOptions.writeIndicesOptions(out); } public Request(TimeValue masterNodeTimeout, TimeValue ackTimeout, String[] names) { super(masterNodeTimeout, ackTimeout); this.names = names; } public String[] getNames() { return names; } @Override public String[] indices() { return names; } @Override public IndicesOptions indicesOptions() { return indicesOptions; } public Request indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } @Override public boolean includeDataStreams() { return true; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Request request = (Request) o; return Arrays.equals(names, request.names) && Objects.equals(indicesOptions, request.indicesOptions); } @Override public int hashCode() { int result = Objects.hash(indicesOptions); result = 31 * result + Arrays.hashCode(names); return result; } @Override public IndicesRequest indices(String... indices) { this.names = indices; return this; } } }
Request