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
apache__kafka
clients/src/test/java/org/apache/kafka/common/security/authenticator/SaslAuthenticatorTest.java
{ "start": 128503, "end": 131966 }
class ____ extends PlainServerCallbackHandler { static final String USERNAME = "TestServerCallbackHandler-user"; static final String PASSWORD = "TestServerCallbackHandler-password"; private volatile boolean configured; public static Semaphore sem = new Semaphore(1); @Override public void configure(Map<String, ?> configs, String mechanism, List<AppConfigurationEntry> jaasConfigEntries) { if (configured) throw new IllegalStateException("Server callback handler configured twice"); configured = true; super.configure(configs, mechanism, jaasConfigEntries); } @Override protected boolean authenticate(String username, char[] password) { if (!configured) throw new IllegalStateException("Server callback handler not configured"); try { sem.acquire(); return USERNAME.equals(username) && new String(password).equals(PASSWORD); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { sem.release(); } } } private SaslHandshakeRequest buildSaslHandshakeRequest(String mechanism, short version) { return new SaslHandshakeRequest.Builder( new SaslHandshakeRequestData().setMechanism(mechanism)).build(version); } @SuppressWarnings("unchecked") private void updateScramCredentialCache(String username, String password) throws NoSuchAlgorithmException { for (String mechanism : (List<String>) saslServerConfigs.get(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG)) { ScramMechanism scramMechanism = ScramMechanism.forMechanismName(mechanism); if (scramMechanism != null) { ScramFormatter formatter = new ScramFormatter(scramMechanism); ScramCredential credential = formatter.generateCredential(password, 4096); credentialCache.cache(scramMechanism.mechanismName(), ScramCredential.class).put(username, credential); } } } // Creates an ApiVersionsRequest with version 0. Using v0 in tests since // SaslClientAuthenticator always uses version 0 private ApiVersionsRequest createApiVersionsRequestV0() { return new ApiVersionsRequest.Builder((short) 0).build(); } @SuppressWarnings("unchecked") private void updateTokenCredentialCache(String username, String password) throws NoSuchAlgorithmException { for (String mechanism : (List<String>) saslServerConfigs.get(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG)) { ScramMechanism scramMechanism = ScramMechanism.forMechanismName(mechanism); if (scramMechanism != null) { ScramFormatter formatter = new ScramFormatter(scramMechanism); ScramCredential credential = formatter.generateCredential(password, 4096); server.tokenCache().credentialCache(scramMechanism.mechanismName()).put(username, credential); } } } private static void delay(long delayMillis) throws InterruptedException { final long startTime = System.currentTimeMillis(); while ((System.currentTimeMillis() - startTime) < delayMillis) Thread.sleep(CONNECTIONS_MAX_REAUTH_MS_VALUE / 5); } public static
TestServerCallbackHandler
java
alibaba__druid
core/src/main/java/com/alibaba/druid/wall/WallSqlFunctionStat.java
{ "start": 656, "end": 946 }
class ____ { private int invokeCount; public int getInvokeCount() { return invokeCount; } public void incrementInvokeCount() { this.invokeCount++; } public void addInvokeCount(int value) { this.invokeCount += value; } }
WallSqlFunctionStat
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng3887PluginExecutionOrderTest.java
{ "start": 1153, "end": 2476 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Test that multiple plugin executions bound to the same phase are executed in the order given by the POM when no * {@code <pluginManagement>} is involved. * * @throws Exception in case of failure */ @Test public void testitWithoutPluginMngt() throws Exception { testitMNG3887("test-1"); } /** * Test that multiple plugin executions bound to the same phase are executed in the order given by the POM when * {@code <pluginManagement>} is involved. * * @throws Exception in case of failure */ @Test public void testitWithPluginMngt() throws Exception { testitMNG3887("test-2"); } private void testitMNG3887(String project) throws Exception { File testDir = extractResources("/mng-3887"); Verifier verifier = newVerifier(new File(testDir, project).getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); List<String> lines = verifier.loadLines("target/it.log"); assertEquals(Arrays.asList(new String[] {"test", "----"}), lines); } }
MavenITmng3887PluginExecutionOrderTest
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/cache/NoCacheOnClassAndMethodsTest.java
{ "start": 772, "end": 2081 }
class ____ { @RegisterExtension static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest() .addScanCustomizer(new Consumer<ResteasyReactiveDeploymentManager.ScanStep>() { @Override public void accept(ResteasyReactiveDeploymentManager.ScanStep scanStep) { scanStep.addMethodScanner(new CacheControlScanner()); } }) .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClasses(ResourceWithNoCache.class); } }); @Test public void testWith() { RestAssured.get("/test/with") .then() .statusCode(200) .body(equalTo("with")) .header("Cache-Control", "no-cache=\"f1\", no-cache=\"f2\""); } @Test public void testWithout() { RestAssured.get("/test/without") .then() .statusCode(200) .body(equalTo("without")) .header("Cache-Control", "no-cache=\"f1\""); } @NoCache(fields = "f1") @Path("test") public static
NoCacheOnClassAndMethodsTest
java
spring-projects__spring-boot
module/spring-boot-jackson2/src/main/java/org/springframework/boot/jackson2/autoconfigure/Jackson2TesterTestAutoConfiguration.java
{ "start": 2317, "end": 2467 }
class ____ extends JsonMarshalTesterRuntimeHints { Jackson2TesterRuntimeHints() { super(Jackson2Tester.class); } } }
Jackson2TesterRuntimeHints
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTablePartitionLifecycle.java
{ "start": 824, "end": 1463 }
class ____ extends SQLObjectImpl implements SQLAlterTableItem { private SQLIntegerExpr lifecycle; public SQLAlterTablePartitionLifecycle() { } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, lifecycle); } visitor.endVisit(this); } public SQLIntegerExpr getLifecycle() { return lifecycle; } public void setLifecycle(SQLIntegerExpr lifecycle) { if (lifecycle != null) { lifecycle.setParent(this); } this.lifecycle = lifecycle; } }
SQLAlterTablePartitionLifecycle
java
apache__dubbo
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RetryServiceInstancesChangedEvent.java
{ "start": 929, "end": 1394 }
class ____ extends ServiceInstancesChangedEvent { private volatile long failureRecordTime; public RetryServiceInstancesChangedEvent(String serviceName) { super(serviceName, Collections.emptyList()); // instance list has been stored by ServiceInstancesChangedListener this.failureRecordTime = System.currentTimeMillis(); } public long getFailureRecordTime() { return failureRecordTime; } }
RetryServiceInstancesChangedEvent
java
quarkusio__quarkus
extensions/funqy/funqy-amazon-lambda/runtime/src/main/java/io/quarkus/funqy/lambda/event/cloudevents/CloudEventsHandler.java
{ "start": 474, "end": 1592 }
class ____ implements EventHandler<List<CloudEvent>, CloudEvent, Response> { @Override public Stream<CloudEvent> streamEvent(final List<CloudEvent> event, final FunqyAmazonConfig amazonConfig) { if (event == null) { return Stream.empty(); } return event.stream(); } @Override public String getIdentifier(final CloudEvent message, final FunqyAmazonConfig amazonConfig) { return message.getId(); } @Override public Supplier<InputStream> getBody(final CloudEvent message, final FunqyAmazonConfig amazonConfig) { return () -> new ByteArrayInputStream(message.getData().toBytes()); } @Override public Response createResponse(final List<String> failures, final FunqyAmazonConfig amazonConfig) { if (!amazonConfig.advancedEventHandling().sqs().reportBatchItemFailures()) { return null; } return new Response(failures.stream().map(BatchItemFailures::new).toList()); } @Override public Class<CloudEvent> getMessageClass() { return CloudEvent.class; } }
CloudEventsHandler
java
spring-projects__spring-boot
module/spring-boot-cache/src/test/java/org/springframework/boot/cache/metrics/HazelcastCacheMeterBinderProviderTests.java
{ "start": 1467, "end": 2394 }
class ____ { @SuppressWarnings("unchecked") @Test void hazelcastCacheProvider() { IMap<Object, Object> nativeCache = mock(IMap.class); given(nativeCache.getName()).willReturn("test"); HazelcastCache cache = new HazelcastCache(nativeCache); MeterBinder meterBinder = new HazelcastCacheMeterBinderProvider().getMeterBinder(cache, Collections.emptyList()); assertThat(meterBinder).isInstanceOf(HazelcastCacheMetrics.class); } @Test void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new HazelcastCacheMeterBinderProviderRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.reflection().onMethodInvocation(HazelcastCache.class, "getNativeCache")) .accepts(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onType(HazelcastCacheMetrics.class)).accepts(runtimeHints); } }
HazelcastCacheMeterBinderProviderTests
java
grpc__grpc-java
api/src/main/java/io/grpc/MethodDescriptor.java
{ "start": 4459, "end": 5353 }
interface ____<T> { /** * Given a message, produce an {@link InputStream} for it so that it can be written to the wire. * Where possible implementations should produce streams that are {@link io.grpc.KnownLength} * to improve transport efficiency. * * @param value to serialize. * @return serialized value as stream of bytes. */ public InputStream stream(T value); /** * Given an {@link InputStream} parse it into an instance of the declared type so that it can be * passed to application code. * * @param stream of bytes for serialized value * @return parsed value */ public T parse(InputStream stream); } /** * A marshaller that supports retrieving its type parameter {@code T} at runtime. * * @since 1.1.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/2222") public
Marshaller
java
quarkusio__quarkus
independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/DependencyLoggingConfig.java
{ "start": 239, "end": 1579 }
class ____ { private boolean built; private Builder() { } public Builder setGraph(boolean graph) { if (!built) { DependencyLoggingConfig.this.graph = graph; } return this; } public Builder setVerbose(boolean verbose) { if (!built) { DependencyLoggingConfig.this.verbose = verbose; } return this; } public Builder setMessageConsumer(Consumer<String> msgConsumer) { if (!built) { DependencyLoggingConfig.this.msgConsumer = msgConsumer; } return this; } public DependencyLoggingConfig build() { if (!built) { built = true; if (msgConsumer == null) { throw new IllegalArgumentException("msgConsumer has not been initialized"); } } return DependencyLoggingConfig.this; } } private boolean verbose; private boolean graph; private Consumer<String> msgConsumer; public boolean isGraph() { return graph; } public boolean isVerbose() { return verbose; } public Consumer<String> getMessageConsumer() { return msgConsumer; } }
Builder
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/PartTreeQueryCache.java
{ "start": 1018, "end": 1608 }
class ____ { private final Map<CacheKey, JpqlQueryCreator> cache = Collections.synchronizedMap(new LinkedHashMap<>() { @Override protected boolean removeEldestEntry(Map.Entry<CacheKey, JpqlQueryCreator> eldest) { return size() > 256; } }); @Nullable JpqlQueryCreator get(Sort sort, JpaParametersParameterAccessor accessor) { return cache.get(CacheKey.of(sort, accessor)); } @Nullable JpqlQueryCreator put(Sort sort, JpaParametersParameterAccessor accessor, JpqlQueryCreator creator) { return cache.put(CacheKey.of(sort, accessor), creator); } static
PartTreeQueryCache
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/HealthMonitor.java
{ "start": 8742, "end": 9207 }
interface ____ called from a single thread which also performs * the health monitoring. If the callback processing takes a long time, * no further health checks will be made during this period, nor will * other registered callbacks be called. * * If the callback itself throws an unchecked exception, no other * callbacks following it will be called, and the health monitor * will terminate, entering HEALTH_MONITOR_FAILED state. */ static
is
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/PQCDataFormat.java
{ "start": 5911, "end": 8810 }
class ____ implements DataFormatBuilder<PQCDataFormat> { private String keyEncapsulationAlgorithm = "MLKEM"; private String symmetricKeyAlgorithm = "AES"; private String symmetricKeyLength; private String keyPair; private String bufferSize; private String provider; private String keyGenerator; /** * The Post-Quantum KEM algorithm to use for key encapsulation. Supported values: MLKEM, BIKE, HQC, CMCE, SABER, * FRODO, NTRU, NTRULPRime, SNTRUPrime, KYBER */ public Builder keyEncapsulationAlgorithm(String keyEncapsulationAlgorithm) { this.keyEncapsulationAlgorithm = keyEncapsulationAlgorithm; return this; } /** * The symmetric encryption algorithm to use with the shared secret. Supported values: AES, ARIA, RC2, RC5, * CAMELLIA, CAST5, CAST6, CHACHA7539, etc. */ public Builder symmetricKeyAlgorithm(String symmetricKeyAlgorithm) { this.symmetricKeyAlgorithm = symmetricKeyAlgorithm; return this; } /** * The length (in bits) of the symmetric key. */ public Builder symmetricKeyLength(String symmetricKeyLength) { this.symmetricKeyLength = symmetricKeyLength; return this; } /** * The length (in bits) of the symmetric key. */ public Builder symmetricKeyLength(int symmetricKeyLength) { this.symmetricKeyLength = Integer.toString(symmetricKeyLength); return this; } /** * Refers to the KeyPair to lookup from the register to use for KEM operations. */ public Builder keyPair(String keyPair) { this.keyPair = keyPair; return this; } /** * The size of the buffer used for streaming encryption/decryption. */ public Builder bufferSize(String bufferSize) { this.bufferSize = bufferSize; return this; } /** * The size of the buffer used for streaming encryption/decryption. */ public Builder bufferSize(int bufferSize) { this.bufferSize = Integer.toString(bufferSize); return this; } /** * The JCE security provider to use. */ public Builder provider(String provider) { this.provider = provider; return this; } /** * Refers to a custom KeyGenerator to lookup from the register for KEM operations. */ public Builder keyGenerator(String keyGenerator) { this.keyGenerator = keyGenerator; return this; } @Override public PQCDataFormat end() { return new PQCDataFormat(this); } } }
Builder
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/SocketOptions.java
{ "start": 3366, "end": 10409 }
class ____ { private Duration connectTimeout = DEFAULT_CONNECT_TIMEOUT_DURATION; private KeepAliveOptions keepAlive = KeepAliveOptions.builder().enable(DEFAULT_SO_KEEPALIVE).build(); private TcpUserTimeoutOptions tcpUserTimeout = TcpUserTimeoutOptions.builder().enable(DEFAULT_TCP_USER_TIMEOUT_ENABLED) .build(); private boolean tcpNoDelay = DEFAULT_SO_NO_DELAY; private boolean extendedKeepAlive = false; private Builder() { } /** * Set connection timeout. Defaults to {@literal 10 SECONDS}. See {@link #DEFAULT_CONNECT_TIMEOUT} and * {@link #DEFAULT_CONNECT_TIMEOUT_UNIT}. * * @param connectTimeout connection timeout, must be greater {@literal 0}. * @return {@code this} * @since 5.0 */ public Builder connectTimeout(Duration connectTimeout) { LettuceAssert.notNull(connectTimeout, "Connect timeout must not be null"); LettuceAssert.isTrue(connectTimeout.toNanos() > 0, "Connect timeout must be greater 0"); this.connectTimeout = connectTimeout; return this; } /** * Set connection timeout. Defaults to {@literal 10 SECONDS}. See {@link #DEFAULT_CONNECT_TIMEOUT} and * {@link #DEFAULT_CONNECT_TIMEOUT_UNIT}. * * @param connectTimeout connection timeout, must be greater {@literal 0}. * @param connectTimeoutUnit unit for {@code connectTimeout}, must not be {@code null}. * @return {@code this} * @deprecated since 5.0, use {@link #connectTimeout(Duration)} */ @Deprecated public Builder connectTimeout(long connectTimeout, TimeUnit connectTimeoutUnit) { LettuceAssert.isTrue(connectTimeout > 0, "Connect timeout must be greater 0"); LettuceAssert.notNull(connectTimeoutUnit, "Connect timeout unit must not be null"); return connectTimeout(Duration.ofNanos(connectTimeoutUnit.toNanos(connectTimeout))); } /** * Set whether to enable TCP keepalive. Defaults to {@code false}. See {@link #DEFAULT_SO_KEEPALIVE}. * * @param keepAlive whether to enable or disable the TCP keepalive. * @return {@code this} * @see java.net.SocketOptions#SO_KEEPALIVE */ public Builder keepAlive(boolean keepAlive) { this.keepAlive = KeepAliveOptions.builder().enable(keepAlive).build(); this.extendedKeepAlive = false; return this; } /** * Configure TCP keepalive. Defaults to disabled. See {@link #DEFAULT_SO_KEEPALIVE}. * * @param keepAlive whether to enable or disable the TCP keepalive. * @return {@code this} * @since 6.1 * @see KeepAliveOptions * @see java.net.SocketOptions#SO_KEEPALIVE */ public Builder keepAlive(KeepAliveOptions keepAlive) { LettuceAssert.notNull(keepAlive, "KeepAlive options must not be null"); this.keepAlive = keepAlive; this.extendedKeepAlive = true; return this; } /** * Configure TCP User Timeout. Defaults to disabled. See {@link #DEFAULT_TCP_USER_TIMEOUT_ENABLED}. * * @param tcpUserTimeout the TCP User Timeout options. * @return {@code this} * @since 6.2.7 * @see TcpUserTimeoutOptions */ public Builder tcpUserTimeout(TcpUserTimeoutOptions tcpUserTimeout) { LettuceAssert.notNull(tcpUserTimeout, "TcpUserTimeout options must not be null"); this.tcpUserTimeout = tcpUserTimeout; return this; } /** * Set whether to disable/enable Nagle's algorithm. Defaults to {@code true} (Nagle disabled). See * {@link #DEFAULT_SO_NO_DELAY}. * <p> * Disabling TCP NoDelay delays TCP {@code ACK} packets to await more data input before confirming the packet. * * @param tcpNoDelay {@code false} to disable TCP NoDelay (enable Nagle's algorithm), {@code true} to enable TCP NoDelay * (disable Nagle's algorithm). * @return {@code this} * @see java.net.SocketOptions#TCP_NODELAY */ public Builder tcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; return this; } /** * Create a new instance of {@link SocketOptions} * * @return new instance of {@link SocketOptions} */ public SocketOptions build() { return new SocketOptions(this); } } /** * Returns a builder to create new {@link SocketOptions} whose settings are replicated from the current * {@link SocketOptions}. * * @return a {@link SocketOptions.Builder} to create new {@link SocketOptions} whose settings are replicated from the * current {@link SocketOptions} * * @since 5.3 */ public SocketOptions.Builder mutate() { SocketOptions.Builder builder = builder(); builder.connectTimeout = this.getConnectTimeout(); builder.keepAlive = this.getKeepAlive(); builder.tcpNoDelay = this.isTcpNoDelay(); return builder; } /** * Returns the connection timeout. * * @return the connection timeout. */ public Duration getConnectTimeout() { return connectTimeout; } /** * Returns whether to enable TCP keepalive. * * @return whether to enable TCP keepalive * @see java.net.SocketOptions#SO_KEEPALIVE */ public boolean isKeepAlive() { return keepAlive.isEnabled(); } /** * Returns the TCP keepalive options. * * @return TCP keepalive options * @see KeepAliveOptions */ public KeepAliveOptions getKeepAlive() { return keepAlive; } boolean isExtendedKeepAlive() { return extendedKeepAlive; } /** * Returns whether to use TCP NoDelay. * * @return {@code true} to disable Nagle's algorithm, {@code false} to enable Nagle's algorithm. * @see java.net.SocketOptions#TCP_NODELAY */ public boolean isTcpNoDelay() { return tcpNoDelay; } public boolean isEnableTcpUserTimeout() { return tcpUserTimeout.isEnabled(); } public TcpUserTimeoutOptions getTcpUserTimeout() { return tcpUserTimeout; } /** * Extended Keep-Alive options (idle, interval, count). Extended options should not be used in code intended to be portable * as options are applied only when using NIO sockets with Java 11 or newer epoll sockets, or io_uring sockets. Not * applicable for kqueue in general or NIO sockets using Java 10 or earlier. * <p> * The time granularity of {@link #getIdle()} and {@link #getInterval()} is seconds. * * @since 6.1 */ public static
Builder
java
apache__camel
components/camel-ignite/src/main/java/org/apache/camel/component/ignite/cache/IgniteCacheProducer.java
{ "start": 1608, "end": 7340 }
class ____ extends DefaultAsyncProducer { private IgniteCache<Object, Object> cache; private IgniteCacheEndpoint endpoint; public IgniteCacheProducer(IgniteCacheEndpoint endpoint, IgniteCache<Object, Object> igniteCache) { super(endpoint); this.endpoint = endpoint; this.cache = igniteCache; } @Override public boolean process(Exchange exchange, AsyncCallback callback) { Message in = exchange.getIn(); Message out = exchange.getOut(); MessageHelper.copyHeaders(exchange.getIn(), out, true); switch (cacheOperationFor(exchange)) { case GET: doGet(in, out); break; case PUT: doPut(in, out); break; case QUERY: doQuery(in, out, exchange); break; case REMOVE: doRemove(in, out); break; case CLEAR: doClear(in, out); break; case SIZE: doSize(in, out); break; case REBALANCE: doRebalance(in, out); break; case REPLACE: doReplace(in, out); break; default: break; } callback.done(false); return false; } @SuppressWarnings("unchecked") private void doGet(Message in, Message out) { Object cacheKey = cacheKey(in); if (cacheKey instanceof Set && !endpoint.isTreatCollectionsAsCacheObjects()) { out.setBody(cache.getAll((Set<Object>) cacheKey)); } else { out.setBody(cache.get(cacheKey)); } } @SuppressWarnings("unchecked") private void doPut(Message in, Message out) { Map<Object, Object> map = in.getBody(Map.class); if (map != null) { cache.putAll(map); return; } Object cacheKey = in.getHeader(IgniteConstants.IGNITE_CACHE_KEY); if (cacheKey == null) { throw new RuntimeCamelException( "Cache PUT operation requires the cache key in the CamelIgniteCacheKey header, " + "or a payload of type Map."); } cache.put(cacheKey, in.getBody()); IgniteHelper.maybePropagateIncomingBody(endpoint, in, out); } @SuppressWarnings("unchecked") private void doQuery(Message in, Message out, Exchange exchange) { Query<Object> query = in.getHeader(IgniteConstants.IGNITE_CACHE_QUERY, Query.class); if (query == null) { try { query = in.getMandatoryBody(Query.class); } catch (InvalidPayloadException e) { exchange.setException(e); return; } } final QueryCursor<Object> cursor = cache.query(query); out.setBody(cursor.iterator()); exchange.getExchangeExtension().addOnCompletion(new Synchronization() { @Override public void onFailure(Exchange exchange) { cursor.close(); } @Override public void onComplete(Exchange exchange) { cursor.close(); } }); } @SuppressWarnings("unchecked") private void doRemove(Message in, Message out) { Object cacheKey = cacheKey(in); if (cacheKey instanceof Set && !endpoint.isTreatCollectionsAsCacheObjects()) { cache.removeAll((Set<Object>) cacheKey); } else { cache.remove(cacheKey); } IgniteHelper.maybePropagateIncomingBody(endpoint, in, out); } private void doClear(Message in, Message out) { cache.removeAll(); IgniteHelper.maybePropagateIncomingBody(endpoint, in, out); } private void doRebalance(Message in, Message out) { cache.rebalance().get(); IgniteHelper.maybePropagateIncomingBody(endpoint, in, out); } @SuppressWarnings("unchecked") private void doSize(Message in, Message out) { Object peekMode = in.getHeader(IgniteConstants.IGNITE_CACHE_PEEK_MODE, endpoint.getCachePeekMode()); Integer result = null; if (peekMode instanceof Collection) { result = cache.size(((Collection<Object>) peekMode).toArray(new CachePeekMode[0])); } else if (peekMode instanceof CachePeekMode) { result = cache.size((CachePeekMode) peekMode); } out.setBody(result); } private void doReplace(Message in, Message out) { Object cacheKey = in.getHeader(IgniteConstants.IGNITE_CACHE_KEY); if (cacheKey == null) { throw new RuntimeCamelException( "Cache REPLACE operation requires the cache key in the CamelIgniteCacheKey header"); } Object oldValue = in.getHeader(IgniteConstants.IGNITE_CACHE_OLD_VALUE); if (oldValue == null) { cache.replace(cacheKey, in.getBody()); } else { cache.replace(cacheKey, oldValue, in.getBody()); } IgniteHelper.maybePropagateIncomingBody(endpoint, in, out); } private Object cacheKey(Message msg) { Object cacheKey = msg.getHeader(IgniteConstants.IGNITE_CACHE_KEY); if (cacheKey == null) { cacheKey = msg.getBody(); } return cacheKey; } private IgniteCacheOperation cacheOperationFor(Exchange exchange) { return exchange.getIn().getHeader(IgniteConstants.IGNITE_CACHE_OPERATION, endpoint.getOperation(), IgniteCacheOperation.class); } }
IgniteCacheProducer
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/support/hierarchical/ThrowableCollector.java
{ "start": 6570, "end": 6828 }
interface ____ { /** * Execute this executable, potentially throwing a {@link Throwable} * that signals abortion or failure. */ void execute() throws Throwable; } /** * Factory for {@code ThrowableCollector} instances. */ public
Executable
java
apache__camel
components/camel-spring-parent/camel-spring-ai/camel-spring-ai-tools/src/generated/java/org/apache/camel/component/springai/tools/SpringAiToolsEndpointConfigurer.java
{ "start": 741, "end": 4980 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { SpringAiToolsEndpoint target = (SpringAiToolsEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "description": target.setDescription(property(camelContext, java.lang.String.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "inputtype": case "inputType": target.setInputType(property(camelContext, java.lang.Class.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "name": target.setName(property(camelContext, java.lang.String.class, value)); return true; case "parameters": target.setParameters(property(camelContext, java.util.Map.class, value)); return true; case "returndirect": case "returnDirect": target.setReturnDirect(property(camelContext, boolean.class, value)); return true; case "tags": target.setTags(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "description": return java.lang.String.class; case "exceptionhandler": case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class; case "exchangepattern": case "exchangePattern": return org.apache.camel.ExchangePattern.class; case "inputtype": case "inputType": return java.lang.Class.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "name": return java.lang.String.class; case "parameters": return java.util.Map.class; case "returndirect": case "returnDirect": return boolean.class; case "tags": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { SpringAiToolsEndpoint target = (SpringAiToolsEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "description": return target.getDescription(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "inputtype": case "inputType": return target.getInputType(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "name": return target.getName(); case "parameters": return target.getParameters(); case "returndirect": case "returnDirect": return target.isReturnDirect(); case "tags": return target.getTags(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "inputtype": case "inputType": return java.lang.Object.class; case "parameters": return java.lang.String.class; default: return null; } } }
SpringAiToolsEndpointConfigurer
java
apache__logging-log4j2
log4j-core-test/src/main/java/org/apache/logging/log4j/core/test/appender/FailOnceAppender.java
{ "start": 4490, "end": 4684 }
class ____: " + throwableClassName); } } @SuppressWarnings("deprecation") private static void stopCurrentThread() { Thread.currentThread().stop(); } public
name
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/cohere/request/v2/CohereV2CompletionRequestTests.java
{ "start": 1102, "end": 3977 }
class ____ extends ESTestCase { public void testCreateRequest() throws IOException { var request = new CohereV2CompletionRequest( List.of("abc"), CohereCompletionModelTests.createModel(null, "secret", "required model id"), false ); var httpRequest = request.createHttpRequest(); assertThat(httpRequest.httpRequestBase(), instanceOf(HttpPost.class)); var httpPost = (HttpPost) httpRequest.httpRequestBase(); assertThat(httpPost.getURI().toString(), is("https://api.cohere.ai/v2/chat")); assertThat(httpPost.getLastHeader(HttpHeaders.CONTENT_TYPE).getValue(), is(XContentType.JSON.mediaType())); assertThat(httpPost.getLastHeader(HttpHeaders.AUTHORIZATION).getValue(), is("Bearer secret")); assertThat(httpPost.getLastHeader(CohereUtils.REQUEST_SOURCE_HEADER).getValue(), is(CohereUtils.ELASTIC_REQUEST_SOURCE)); var requestMap = entityAsMap(httpPost.getEntity().getContent()); assertThat( requestMap, is(Map.of("messages", List.of(Map.of("role", "user", "content", "abc")), "model", "required model id", "stream", false)) ); } public void testDefaultUrl() { var request = new CohereV2CompletionRequest( List.of("abc"), CohereCompletionModelTests.createModel(null, "secret", "model id"), false ); var httpRequest = request.createHttpRequest(); assertThat(httpRequest.httpRequestBase(), instanceOf(HttpPost.class)); var httpPost = (HttpPost) httpRequest.httpRequestBase(); assertThat(httpPost.getURI().toString(), is("https://api.cohere.ai/v2/chat")); } public void testOverriddenUrl() { var request = new CohereV2CompletionRequest( List.of("abc"), CohereCompletionModelTests.createModel("http://localhost", "secret", "model id"), false ); var httpRequest = request.createHttpRequest(); assertThat(httpRequest.httpRequestBase(), instanceOf(HttpPost.class)); var httpPost = (HttpPost) httpRequest.httpRequestBase(); assertThat(httpPost.getURI().toString(), is("http://localhost/v2/chat")); } public void testXContents() throws IOException { var request = new CohereV2CompletionRequest( List.of("some input"), CohereCompletionModelTests.createModel(null, "secret", "model"), false ); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); request.toXContent(builder, null); String xContentResult = Strings.toString(builder); assertThat(xContentResult, CoreMatchers.is(""" {"messages":[{"role":"user","content":"some input"}],"model":"model","stream":false}""")); } }
CohereV2CompletionRequestTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UndefinedEqualsTest.java
{ "start": 3934, "end": 4399 }
class ____ { <T> void f(Queue<String> a, Queue<T> b) { // BUG: Diagnostic contains: Queue a.equals(b); } } """) .doTest(); } @Test public void positiveTruth() { compilationHelper .addSourceLines( "Test.java", """ import static com.google.common.truth.Truth.assertThat; import java.util.Queue;
Test
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/support/PropertyComparator.java
{ "start": 1381, "end": 5094 }
class ____<T> implements Comparator<T> { protected final Log logger = LogFactory.getLog(getClass()); private final SortDefinition sortDefinition; /** * Create a new PropertyComparator for the given SortDefinition. * @see MutableSortDefinition */ public PropertyComparator(SortDefinition sortDefinition) { this.sortDefinition = sortDefinition; } /** * Create a PropertyComparator for the given settings. * @param property the property to compare * @param ignoreCase whether upper and lower case in String values should be ignored * @param ascending whether to sort ascending (true) or descending (false) */ public PropertyComparator(String property, boolean ignoreCase, boolean ascending) { this.sortDefinition = new MutableSortDefinition(property, ignoreCase, ascending); } /** * Return the SortDefinition that this comparator uses. */ public final SortDefinition getSortDefinition() { return this.sortDefinition; } @Override @SuppressWarnings("unchecked") public int compare(T o1, T o2) { Object v1 = getPropertyValue(o1); Object v2 = getPropertyValue(o2); if (this.sortDefinition.isIgnoreCase() && (v1 instanceof String text1) && (v2 instanceof String text2)) { v1 = text1.toLowerCase(Locale.ROOT); v2 = text2.toLowerCase(Locale.ROOT); } int result; // Put an object with null property at the end of the sort result. try { if (v1 != null) { result = (v2 != null ? ((Comparable<Object>) v1).compareTo(v2) : -1); } else { result = (v2 != null ? 1 : 0); } } catch (RuntimeException ex) { if (logger.isDebugEnabled()) { logger.debug("Could not sort objects [" + o1 + "] and [" + o2 + "]", ex); } return 0; } return (this.sortDefinition.isAscending() ? result : -result); } /** * Get the SortDefinition's property value for the given object. * @param obj the object to get the property value for * @return the property value */ private @Nullable Object getPropertyValue(Object obj) { // If a nested property cannot be read, simply return null // (similar to JSTL EL). If the property doesn't exist in the // first place, let the exception through. try { BeanWrapperImpl beanWrapper = new BeanWrapperImpl(false); beanWrapper.setWrappedInstance(obj); return beanWrapper.getPropertyValue(this.sortDefinition.getProperty()); } catch (BeansException ex) { logger.debug("PropertyComparator could not access property - treating as null for sorting", ex); return null; } } /** * Sort the given List according to the given sort definition. * <p>Note: Contained objects have to provide the given property * in the form of a bean property, i.e. a getXXX method. * @param source the input List * @param sortDefinition the parameters to sort by * @throws java.lang.IllegalArgumentException in case of a missing propertyName */ public static void sort(List<?> source, SortDefinition sortDefinition) throws BeansException { if (StringUtils.hasText(sortDefinition.getProperty())) { source.sort(new PropertyComparator<>(sortDefinition)); } } /** * Sort the given source according to the given sort definition. * <p>Note: Contained objects have to provide the given property * in the form of a bean property, i.e. a getXXX method. * @param source input source * @param sortDefinition the parameters to sort by * @throws java.lang.IllegalArgumentException in case of a missing propertyName */ public static void sort(Object[] source, SortDefinition sortDefinition) throws BeansException { if (StringUtils.hasText(sortDefinition.getProperty())) { Arrays.sort(source, new PropertyComparator<>(sortDefinition)); } } }
PropertyComparator
java
hibernate__hibernate-orm
hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/GaussDBArrayJdbcType.java
{ "start": 979, "end": 3722 }
class ____ extends ArrayJdbcType { public GaussDBArrayJdbcType(JdbcType elementJdbcType) { super( elementJdbcType ); } @Override public <X> ValueBinder<X> getBinder(final JavaType<X> javaTypeDescriptor) { @SuppressWarnings("unchecked") final BasicPluralJavaType<X> pluralJavaType = (BasicPluralJavaType<X>) javaTypeDescriptor; final ValueBinder<X> elementBinder = getElementJdbcType().getBinder( pluralJavaType.getElementJavaType() ); return new BasicBinder<>( javaTypeDescriptor, this ) { @Override protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { st.setArray( index, getArray( value, options ) ); } @Override protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException { final java.sql.Array arr = getArray( value, options ); try { st.setObject( name, arr, java.sql.Types.ARRAY ); } catch (SQLException ex) { throw new HibernateException( "JDBC driver does not support named parameters for setArray. Use positional.", ex ); } } @Override public Object getBindValue(X value, WrapperOptions options) throws SQLException { return ( (GaussDBArrayJdbcType) getJdbcType() ).getArray( this, elementBinder, value, options ); } private java.sql.Array getArray(X value, WrapperOptions options) throws SQLException { final GaussDBArrayJdbcType arrayJdbcType = (GaussDBArrayJdbcType) getJdbcType(); final Object[] objects; final JdbcType elementJdbcType = arrayJdbcType.getElementJdbcType(); if ( elementJdbcType instanceof AggregateJdbcType ) { // The GaussDB JDBC driver does not support arrays of structs, which contain byte[] final AggregateJdbcType aggregateJdbcType = (AggregateJdbcType) elementJdbcType; final Object[] domainObjects = getJavaType().unwrap( value, Object[].class, options ); objects = new Object[domainObjects.length]; for ( int i = 0; i < domainObjects.length; i++ ) { if ( domainObjects[i] != null ) { objects[i] = aggregateJdbcType.createJdbcValue( domainObjects[i], options ); } } } else { objects = arrayJdbcType.getArray( this, elementBinder, value, options ); } final SharedSessionContractImplementor session = options.getSession(); final String typeName = arrayJdbcType.getElementTypeName( getJavaType(), session ); return session.getJdbcCoordinator().getLogicalConnection().getPhysicalConnection() .createArrayOf( typeName, objects ); } }; } @Override public String toString() { return "GaussDBArrayTypeDescriptor(" + getElementJdbcType().toString() + ")"; } }
GaussDBArrayJdbcType
java
apache__flink
flink-core/src/main/java/org/apache/flink/types/Record.java
{ "start": 54919, "end": 74329 }
class ____ implements DataInputView, DataOutputView, Serializable { private static final long serialVersionUID = 1L; private byte[] memory; private int position; private int end; // ---------------------------------------------------------------------------------------- // Data Input // ---------------------------------------------------------------------------------------- @Override public boolean readBoolean() throws IOException { if (this.position < this.end) { return this.memory[this.position++] != 0; } else { throw new EOFException(); } } @Override public byte readByte() throws IOException { if (this.position < this.end) { return this.memory[this.position++]; } else { throw new EOFException(); } } @Override public char readChar() throws IOException { if (this.position < this.end - 1) { return (char) (((this.memory[this.position++] & 0xff) << 8) | ((this.memory[this.position++] & 0xff) << 0)); } else { throw new EOFException(); } } @Override public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } @Override public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } @Override public void readFully(byte[] b) throws IOException { readFully(b, 0, b.length); } @Override public void readFully(byte[] b, int off, int len) throws IOException { if (len >= 0) { if (off <= b.length - len) { if (this.position <= this.end - len) { System.arraycopy(this.memory, position, b, off, len); position += len; } else { throw new EOFException(); } } else { throw new ArrayIndexOutOfBoundsException(); } } else if (len < 0) { throw new IllegalArgumentException("Length may not be negative."); } } @Override public int readInt() throws IOException { if (this.position >= 0 && this.position < this.end - 3) { @SuppressWarnings("restriction") int value = UNSAFE.getInt(this.memory, BASE_OFFSET + this.position); if (LITTLE_ENDIAN) { value = Integer.reverseBytes(value); } this.position += 4; return value; } else { throw new EOFException(); } } @Override public String readLine() throws IOException { if (this.position < this.end) { // read until a newline is found StringBuilder bld = new StringBuilder(); char curr = (char) readUnsignedByte(); while (position < this.end && curr != '\n') { bld.append(curr); curr = (char) readUnsignedByte(); } // trim a trailing carriage return int len = bld.length(); if (len > 0 && bld.charAt(len - 1) == '\r') { bld.setLength(len - 1); } String s = bld.toString(); bld.setLength(0); return s; } else { return null; } } @Override public long readLong() throws IOException { if (position >= 0 && position < this.end - 7) { @SuppressWarnings("restriction") long value = UNSAFE.getLong(this.memory, BASE_OFFSET + this.position); if (LITTLE_ENDIAN) { value = Long.reverseBytes(value); } this.position += 8; return value; } else { throw new EOFException(); } } @Override public short readShort() throws IOException { if (position >= 0 && position < this.end - 1) { return (short) ((((this.memory[position++]) & 0xff) << 8) | (((this.memory[position++]) & 0xff) << 0)); } else { throw new EOFException(); } } @Override public String readUTF() throws IOException { int utflen = readUnsignedShort(); byte[] bytearr = new byte[utflen]; char[] chararr = new char[utflen]; int c, char2, char3; int count = 0; int chararr_count = 0; readFully(bytearr, 0, utflen); while (count < utflen) { c = (int) bytearr[count] & 0xff; if (c > 127) { break; } count++; chararr[chararr_count++] = (char) c; } while (count < utflen) { c = (int) bytearr[count] & 0xff; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: /* 0xxxxxxx */ count++; chararr[chararr_count++] = (char) c; break; case 12: case 13: /* 110x xxxx 10xx xxxx */ count += 2; if (count > utflen) { throw new UTFDataFormatException( "malformed input: partial character at end"); } char2 = (int) bytearr[count - 1]; if ((char2 & 0xC0) != 0x80) { throw new UTFDataFormatException( "malformed input around byte " + count); } chararr[chararr_count++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: /* 1110 xxxx 10xx xxxx 10xx xxxx */ count += 3; if (count > utflen) { throw new UTFDataFormatException( "malformed input: partial character at end"); } char2 = (int) bytearr[count - 2]; char3 = (int) bytearr[count - 1]; if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) { throw new UTFDataFormatException( "malformed input around byte " + (count - 1)); } chararr[chararr_count++] = (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; default: /* 10xx xxxx, 1111 xxxx */ throw new UTFDataFormatException("malformed input around byte " + count); } } // The number of chars produced may be less than utflen return new String(chararr, 0, chararr_count); } @Override public int readUnsignedByte() throws IOException { if (this.position < this.end) { return (this.memory[this.position++] & 0xff); } else { throw new EOFException(); } } @Override public int readUnsignedShort() throws IOException { if (this.position < this.end - 1) { return ((this.memory[this.position++] & 0xff) << 8) | ((this.memory[this.position++] & 0xff) << 0); } else { throw new EOFException(); } } @Override public int skipBytes(int n) throws IOException { if (this.position <= this.end - n) { this.position += n; return n; } else { n = this.end - this.position; this.position = this.end; return n; } } @Override public void skipBytesToRead(int numBytes) throws IOException { if (this.end - this.position < numBytes) { throw new EOFException("Could not skip " + numBytes + "."); } skipBytes(numBytes); } @Override public int read(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException("Byte array b cannot be null."); } if (off < 0) { throw new IndexOutOfBoundsException("Offset cannot be negative."); } if (len < 0) { throw new IndexOutOfBoundsException("Length cannot be negative."); } if (b.length - off < len) { throw new IndexOutOfBoundsException( "Byte array does not provide enough space to store requested data" + "."); } if (this.position >= this.end) { return len == 0 ? 0 : -1; } else { int toRead = Math.min(this.end - this.position, len); System.arraycopy(this.memory, this.position, b, off, toRead); this.position += toRead; return toRead; } } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } // ---------------------------------------------------------------------------------------- // Data Output // ---------------------------------------------------------------------------------------- @Override public void write(int b) throws IOException { if (this.position >= this.memory.length) { resize(1); } this.memory[this.position++] = (byte) (b & 0xff); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { if (len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } if (this.position > this.memory.length - len) { resize(len); } System.arraycopy(b, off, this.memory, this.position, len); this.position += len; } @Override public void writeBoolean(boolean v) throws IOException { write(v ? 1 : 0); } @Override public void writeByte(int v) throws IOException { write(v); } @Override public void writeBytes(String s) throws IOException { final int sLen = s.length(); if (this.position >= this.memory.length - sLen) { resize(sLen); } for (int i = 0; i < sLen; i++) { writeByte(s.charAt(i)); } this.position += sLen; } @Override public void writeChar(int v) throws IOException { if (this.position >= this.memory.length - 1) { resize(2); } this.memory[this.position++] = (byte) (v >> 8); this.memory[this.position++] = (byte) v; } @Override public void writeChars(String s) throws IOException { final int sLen = s.length(); if (this.position >= this.memory.length - 2 * sLen) { resize(2 * sLen); } for (int i = 0; i < sLen; i++) { writeChar(s.charAt(i)); } } @Override public void writeDouble(double v) throws IOException { writeLong(Double.doubleToLongBits(v)); } @Override public void writeFloat(float v) throws IOException { writeInt(Float.floatToIntBits(v)); } @SuppressWarnings("restriction") @Override public void writeInt(int v) throws IOException { if (this.position >= this.memory.length - 3) { resize(4); } if (LITTLE_ENDIAN) { v = Integer.reverseBytes(v); } UNSAFE.putInt(this.memory, BASE_OFFSET + this.position, v); this.position += 4; } @SuppressWarnings("restriction") @Override public void writeLong(long v) throws IOException { if (this.position >= this.memory.length - 7) { resize(8); } if (LITTLE_ENDIAN) { v = Long.reverseBytes(v); } UNSAFE.putLong(this.memory, BASE_OFFSET + this.position, v); this.position += 8; } @Override public void writeShort(int v) throws IOException { if (this.position >= this.memory.length - 1) { resize(2); } this.memory[this.position++] = (byte) ((v >>> 8) & 0xff); this.memory[this.position++] = (byte) ((v >>> 0) & 0xff); } @Override public void writeUTF(String str) throws IOException { int strlen = str.length(); int utflen = 0; int c; /* use charAt instead of copying String to char array */ for (int i = 0; i < strlen; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { utflen++; } else if (c > 0x07FF) { utflen += 3; } else { utflen += 2; } } if (utflen > 65535) { throw new UTFDataFormatException("Encoded string is too long: " + utflen); } else if (this.position > this.memory.length - utflen - 2) { resize(utflen + 2); } byte[] bytearr = this.memory; int count = this.position; bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF); bytearr[count++] = (byte) ((utflen >>> 0) & 0xFF); int i = 0; for (i = 0; i < strlen; i++) { c = str.charAt(i); if (!((c >= 0x0001) && (c <= 0x007F))) { break; } bytearr[count++] = (byte) c; } for (; i < strlen; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { bytearr[count++] = (byte) c; } else if (c > 0x07FF) { bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); bytearr[count++] = (byte) (0x80 | ((c >> 6) & 0x3F)); bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F)); } else { bytearr[count++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F)); } } this.position = count; } private void writeValLenIntBackwards(int value) throws IOException { if (this.position > this.memory.length - 4) { resize(4); } if (value <= 0x7f) { this.memory[this.position++] = (byte) value; } else if (value <= 0x3fff) { this.memory[this.position++] = (byte) (value >>> 7); this.memory[this.position++] = (byte) (value | MAX_BIT); } else if (value <= 0x1fffff) { this.memory[this.position++] = (byte) (value >>> 14); this.memory[this.position++] = (byte) ((value >>> 7) | MAX_BIT); this.memory[this.position++] = (byte) (value | MAX_BIT); } else if (value <= 0xfffffff) { this.memory[this.position++] = (byte) (value >>> 21); this.memory[this.position++] = (byte) ((value >>> 14) | MAX_BIT); this.memory[this.position++] = (byte) ((value >>> 7) | MAX_BIT); this.memory[this.position++] = (byte) (value | MAX_BIT); } else { this.memory[this.position++] = (byte) (value >>> 28); this.memory[this.position++] = (byte) ((value >>> 21) | MAX_BIT); this.memory[this.position++] = (byte) ((value >>> 14) | MAX_BIT); this.memory[this.position++] = (byte) ((value >>> 7) | MAX_BIT); this.memory[this.position++] = (byte) (value | MAX_BIT); } } private void resize(int minCapacityAdd) throws IOException { try { final int newLen = Math.max(this.memory.length * 2, this.memory.length + minCapacityAdd); final byte[] nb = new byte[newLen]; System.arraycopy(this.memory, 0, nb, 0, this.position); this.memory = nb; } catch (NegativeArraySizeException nasex) { throw new IOException( "Serialization failed because the record length would exceed 2GB."); } } @SuppressWarnings("restriction") private static final sun.misc.Unsafe UNSAFE = MemoryUtils.UNSAFE; @SuppressWarnings("restriction") private static final long BASE_OFFSET = UNSAFE.arrayBaseOffset(byte[].class); private static final boolean LITTLE_ENDIAN = (MemoryUtils.NATIVE_BYTE_ORDER == ByteOrder.LITTLE_ENDIAN); @Override public void skipBytesToWrite(int numBytes) throws IOException { int skippedBytes = skipBytes(numBytes); if (skippedBytes != numBytes) { throw new EOFException("Could not skip " + numBytes + " bytes."); } } @Override public void write(DataInputView source, int numBytes) throws IOException { if (numBytes > this.end - this.position) { throw new IOException( "Could not write " + numBytes + " bytes since the buffer is full."); } source.readFully(this.memory, this.position, numBytes); this.position += numBytes; } } }
InternalDeSerializer
java
redisson__redisson
redisson/src/main/java/org/redisson/api/NodeListener.java
{ "start": 684, "end": 797 }
interface ____ { void onConnect(RedisClient client); void onDisconnect(RedisClient client); }
NodeListener
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/FilterExec.java
{ "start": 572, "end": 2224 }
class ____ extends UnaryExec implements Unexecutable { private final Expression condition; // indicates whether the filter is regular or agg-based (HAVING xxx) // gets setup automatically and then copied over during cloning private final boolean isHaving; public FilterExec(Source source, PhysicalPlan child, Expression condition) { this(source, child, condition, child instanceof AggregateExec); } public FilterExec(Source source, PhysicalPlan child, Expression condition, boolean isHaving) { super(source, child); this.condition = condition; this.isHaving = isHaving; } @Override protected NodeInfo<FilterExec> info() { return NodeInfo.create(this, FilterExec::new, child(), condition, isHaving); } @Override protected FilterExec replaceChild(PhysicalPlan newChild) { return new FilterExec(source(), newChild, condition, isHaving); } public Expression condition() { return condition; } public boolean isHaving() { return isHaving; } @Override public List<Attribute> output() { return child().output(); } @Override public int hashCode() { return Objects.hash(condition, isHaving, child()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } FilterExec other = (FilterExec) obj; return Objects.equals(condition, other.condition) && Objects.equals(child(), other.child()); } }
FilterExec
java
apache__dubbo
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/IEcho.java
{ "start": 848, "end": 895 }
interface ____ { String echo(String e); }
IEcho
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/accept/QueryApiVersionResolver.java
{ "start": 918, "end": 1289 }
class ____ implements ApiVersionResolver { private final String queryParamName; public QueryApiVersionResolver(String queryParamName) { this.queryParamName = queryParamName; } @Override public @Nullable String resolveVersion(ServerWebExchange exchange) { return exchange.getRequest().getQueryParams().getFirst(this.queryParamName); } }
QueryApiVersionResolver
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/db/TestDbClasses.java
{ "start": 6459, "end": 7055 }
class ____ extends OracleDataDrivenDBInputFormat<NullDBWritable> { @Override public DBConfiguration getDBConf() { String[] names = { "field1", "field2" }; DBConfiguration result = mock(DBConfiguration.class); when(result.getInputConditions()).thenReturn("conditions"); when(result.getInputFieldNames()).thenReturn(names); when(result.getInputTableName()).thenReturn("table"); return result; } @Override public Connection getConnection() { return DriverForTest.getConnection(); } } }
OracleDataDrivenDBInputFormatForTest
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/metrics/MetricValueProvider.java
{ "start": 968, "end": 1310 }
interface ____<T> { /** * Returns the current value associated with this metric. * * @param config The configuration for this metric * @param now The POSIX time in milliseconds the measurement is being taken * @return the current metric value */ T value(MetricConfig config, long now); }
MetricValueProvider
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/annotations/Lang.java
{ "start": 1355, "end": 1562 }
interface ____ { /** * Returns the {@link LanguageDriver} implementation type to use. * * @return the {@link LanguageDriver} implementation type */ Class<? extends LanguageDriver> value(); }
Lang
java
apache__camel
test-infra/camel-test-infra-hivemq/src/main/java/org/apache/camel/test/infra/hivemq/common/HiveMQProperties.java
{ "start": 868, "end": 1989 }
class ____ { public static final String HIVEMQ_SERVICE_MQTT_HOST = "hivemq.service.mqtt.host"; public static final String HIVEMQ_SERVICE_MQTT_PORT = "hivemq.service.mqtt.port"; public static final String HIVEMQ_SERVICE_MQTT_HOST_ADDRESS = "hivemq.service.mqtt.hostaddress"; public static final String HIVEMQ_SERVICE_USER_NAME = "hivemq.service.user.name"; public static final String HIVEMQ_SERVICE_USER_PASSWORD = "hivemq.service.user.password"; public static final String HIVEMQ_CONTAINER = "hivemq.container"; public static final String HIVEMQ_RESOURCE_PATH = "hivemq.resource.path"; public static final String HIVEMQ_SPARKPLUG_CONTAINER = "hivemq.sparkplug.container"; public static final String HIVEMQ_SPARKPLUG_INSTANCE_SELECTOR = "hivemq-sparkplug"; public static final String HIVEMQ_TEST_SERVICE_NAME = "hivemq"; public static final String HIVEMQ_PROPERTY_NAME_FORMAT = "%s.instance.type"; public static final String HIVEMQ_INSTANCE_TYPE = String.format(HIVEMQ_PROPERTY_NAME_FORMAT, HIVEMQ_TEST_SERVICE_NAME); private HiveMQProperties() { } }
HiveMQProperties
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/engine/support/hierarchical/LockManagerTests.java
{ "start": 1210, "end": 4852 }
class ____ { private final LockManager lockManager = new LockManager(); @Test void returnsNopLockWithoutExclusiveResources() { Collection<ExclusiveResource> resources = Set.of(); var locks = getLocks(resources, NopLock.class); assertThat(locks).isEmpty(); } @Test void returnsSingleLockForSingleExclusiveResource() { Collection<ExclusiveResource> resources = Set.of(new ExclusiveResource("foo", READ)); var locks = getLocks(resources, SingleLock.class); assertThat(locks).hasSize(1); assertThat(locks.getFirst()).isInstanceOf(ReadLock.class); } @Test void returnsCompositeLockForMultipleDifferentExclusiveResources() { Collection<ExclusiveResource> resources = List.of( // new ExclusiveResource("a", READ), // new ExclusiveResource("b", READ_WRITE)); var locks = getLocks(resources, CompositeLock.class); assertThat(locks).hasSize(2); assertThat(locks.get(0)).isInstanceOf(ReadLock.class); assertThat(locks.get(1)).isInstanceOf(WriteLock.class); } @Test void reusesSameLockForExclusiveResourceWithSameKey() { Collection<ExclusiveResource> resources = Set.of(new ExclusiveResource("foo", READ)); var locks1 = getLocks(resources, SingleLock.class); var locks2 = getLocks(resources, SingleLock.class); assertThat(locks1).hasSize(1); assertThat(locks2).hasSize(1); assertThat(locks1.getFirst()).isSameAs(locks2.getFirst()); } @Test void returnsWriteLockForExclusiveResourceWithBothLockModes() { Collection<ExclusiveResource> resources = List.of( // new ExclusiveResource("bar", READ), // new ExclusiveResource("foo", READ), // new ExclusiveResource("foo", READ_WRITE), // new ExclusiveResource("bar", READ_WRITE)); var locks = getLocks(resources, CompositeLock.class); assertThat(locks).hasSize(2); assertThat(locks.get(0)).isInstanceOf(WriteLock.class); assertThat(locks.get(1)).isInstanceOf(WriteLock.class); } @ParameterizedTest @EnumSource void globalLockComesFirst(LockMode globalLockMode) { Collection<ExclusiveResource> resources = List.of( // new ExclusiveResource("___foo", READ), // new ExclusiveResource("foo", READ_WRITE), // new ExclusiveResource(GLOBAL_KEY, globalLockMode), // new ExclusiveResource("bar", READ_WRITE)); var locks = getLocks(resources, CompositeLock.class); assertThat(locks).hasSize(4); assertThat(locks.get(0)).isEqualTo(getSingleLock(GLOBAL_KEY, globalLockMode)); assertThat(locks.get(1)).isEqualTo(getSingleLock("___foo", READ)); assertThat(locks.get(2)).isEqualTo(getSingleLock("bar", READ_WRITE)); assertThat(locks.get(3)).isEqualTo(getSingleLock("foo", READ_WRITE)); } @Test void usesSingleInstanceForGlobalReadLock() { var lock = lockManager.getLockForResources(List.of(ExclusiveResource.GLOBAL_READ)); assertThat(lock) // .isInstanceOf(SingleLock.class) // .isSameAs(lockManager.getLockForResource(ExclusiveResource.GLOBAL_READ)); } @Test void usesSingleInstanceForGlobalReadWriteLock() { var lock = lockManager.getLockForResources(List.of(ExclusiveResource.GLOBAL_READ_WRITE)); assertThat(lock) // .isInstanceOf(SingleLock.class) // .isSameAs(lockManager.getLockForResource(ExclusiveResource.GLOBAL_READ_WRITE)); } private Lock getSingleLock(String key, LockMode lockMode) { return getLocks(Set.of(new ExclusiveResource(key, lockMode)), SingleLock.class).getFirst(); } private List<Lock> getLocks(Collection<ExclusiveResource> resources, Class<? extends ResourceLock> type) { var lock = lockManager.getLockForResources(resources); assertThat(lock).isInstanceOf(type); return ResourceLockSupport.getLocks(lock); } }
LockManagerTests
java
apache__spark
common/network-common/src/main/java/org/apache/spark/network/protocol/ChunkFetchFailure.java
{ "start": 1011, "end": 2372 }
class ____ extends AbstractMessage implements ResponseMessage { public final StreamChunkId streamChunkId; public final String errorString; public ChunkFetchFailure(StreamChunkId streamChunkId, String errorString) { this.streamChunkId = streamChunkId; this.errorString = errorString; } @Override public Message.Type type() { return Type.ChunkFetchFailure; } @Override public int encodedLength() { return streamChunkId.encodedLength() + Encoders.Strings.encodedLength(errorString); } @Override public void encode(ByteBuf buf) { streamChunkId.encode(buf); Encoders.Strings.encode(buf, errorString); } public static ChunkFetchFailure decode(ByteBuf buf) { StreamChunkId streamChunkId = StreamChunkId.decode(buf); String errorString = Encoders.Strings.decode(buf); return new ChunkFetchFailure(streamChunkId, errorString); } @Override public int hashCode() { return Objects.hash(streamChunkId, errorString); } @Override public boolean equals(Object other) { if (other instanceof ChunkFetchFailure o) { return streamChunkId.equals(o.streamChunkId) && errorString.equals(o.errorString); } return false; } @Override public String toString() { return "ChunkFetchFailure[streamChunkId=" + streamChunkId + ",errorString=" + errorString + "]"; } }
ChunkFetchFailure
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/speculate/forecast/SimpleExponentialSmoothing.java
{ "start": 2000, "end": 7660 }
class ____ { private final double alpha; private final long timeStamp; private final double sample; private final double rawData; private double forecast; private final double sseError; private final long myIndex; private ForecastRecord prevRec; ForecastRecord(final double currForecast, final double currRawData, final long currTimeStamp) { this(0.0, currForecast, currRawData, currForecast, currTimeStamp, 0.0, 0); } ForecastRecord(final double alphaVal, final double currSample, final double currRawData, final double currForecast, final long currTimeStamp, final double accError, final long index) { this.timeStamp = currTimeStamp; this.alpha = alphaVal; this.sample = currSample; this.forecast = currForecast; this.rawData = currRawData; this.sseError = accError; this.myIndex = index; } private ForecastRecord createForecastRecord(final double alphaVal, final double currSample, final double currRawData, final double currForecast, final long currTimeStamp, final double accError, final long index, final ForecastRecord prev) { ForecastRecord forecastRec = new ForecastRecord(alphaVal, currSample, currRawData, currForecast, currTimeStamp, accError, index); forecastRec.prevRec = prev; return forecastRec; } private double preProcessRawData(final double rData, final long newTime) { return processRawData(this.rawData, this.timeStamp, rData, newTime); } public ForecastRecord append(final long newTimeStamp, final double rData) { if (this.timeStamp >= newTimeStamp && Double.compare(this.rawData, rData) >= 0) { // progress reported twice. Do nothing. return this; } ForecastRecord refRecord = this; if (newTimeStamp == this.timeStamp) { // we need to restore old value if possible if (this.prevRec != null) { refRecord = this.prevRec; } } double newSample = refRecord.preProcessRawData(rData, newTimeStamp); long deltaTime = this.timeStamp - newTimeStamp; if (refRecord.myIndex == kMinimumReads) { timeConstant = Math.max(timeConstant, newTimeStamp - startTime); } double smoothFactor = 1 - Math.exp(((double) deltaTime) / timeConstant); double forecastVal = smoothFactor * newSample + (1.0 - smoothFactor) * refRecord.forecast; double newSSEError = refRecord.sseError + Math.pow(newSample - refRecord.forecast, 2); return refRecord .createForecastRecord(smoothFactor, newSample, rData, forecastVal, newTimeStamp, newSSEError, refRecord.myIndex + 1, refRecord); } } /** * checks if the task is hanging up. * @param timeStamp current time of the scan. * @return true if we have number of samples {@literal >} kMinimumReads and the * record timestamp has expired. */ public boolean isDataStagnated(final long timeStamp) { ForecastRecord rec = forecastRefEntry.get(); if (rec != null && rec.myIndex > kMinimumReads) { return (rec.timeStamp + kStagnatedWindow) > timeStamp; } return false; } static double processRawData(final double oldRawData, final long oldTime, final double newRawData, final long newTime) { double rate = (newRawData - oldRawData) / (newTime - oldTime); return rate; } public void incorporateReading(final long timeStamp, final double currRawData) { ForecastRecord oldRec = forecastRefEntry.get(); if (oldRec == null) { double oldForecast = processRawData(0, startTime, currRawData, timeStamp); forecastRefEntry.compareAndSet(null, new ForecastRecord(oldForecast, 0.0, startTime)); incorporateReading(timeStamp, currRawData); return; } while (!forecastRefEntry.compareAndSet(oldRec, oldRec.append(timeStamp, currRawData))) { oldRec = forecastRefEntry.get(); } } public double getForecast() { ForecastRecord rec = forecastRefEntry.get(); if (rec != null && rec.myIndex > kMinimumReads) { return rec.forecast; } return DEFAULT_FORECAST; } public boolean isDefaultForecast(final double value) { return value == DEFAULT_FORECAST; } public double getSSE() { ForecastRecord rec = forecastRefEntry.get(); if (rec != null) { return rec.sseError; } return DEFAULT_FORECAST; } public boolean isErrorWithinBound(final double bound) { double squaredErr = getSSE(); if (squaredErr < 0) { return false; } return bound > squaredErr; } public double getRawData() { ForecastRecord rec = forecastRefEntry.get(); if (rec != null) { return rec.rawData; } return DEFAULT_FORECAST; } public long getTimeStamp() { ForecastRecord rec = forecastRefEntry.get(); if (rec != null) { return rec.timeStamp; } return 0L; } public long getStartTime() { return startTime; } public AtomicReference<ForecastRecord> getForecastRefEntry() { return forecastRefEntry; } @Override public String toString() { String res = "NULL"; ForecastRecord rec = forecastRefEntry.get(); if (rec != null) { res = "rec.index = " + rec.myIndex + ", forecast t: " + rec.timeStamp + ", forecast: " + rec.forecast + ", sample: " + rec.sample + ", raw: " + rec.rawData + ", error: " + rec.sseError + ", alpha: " + rec.alpha; } return res; } }
ForecastRecord
java
spring-projects__spring-boot
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataCollector.java
{ "start": 1299, "end": 3655 }
class ____ { private final Predicate<ItemMetadata> mergeRequired; private final ConfigurationMetadata previousMetadata; private final Set<ItemMetadata> metadataItems = new LinkedHashSet<>(); private final Set<ItemHint> metadataHints = new LinkedHashSet<>(); /** * Creates a new {@code MetadataProcessor} instance. * @param mergeRequired specify whether an item can be merged * @param previousMetadata any previous metadata or {@code null} */ MetadataCollector(Predicate<ItemMetadata> mergeRequired, ConfigurationMetadata previousMetadata) { this.mergeRequired = mergeRequired; this.previousMetadata = previousMetadata; } void add(ItemMetadata metadata) { this.metadataItems.add(metadata); } void add(ItemMetadata metadata, Consumer<ItemMetadata> onConflict) { ItemMetadata existing = find(metadata.getName()); if (existing != null) { onConflict.accept(existing); return; } add(metadata); } boolean addIfAbsent(ItemMetadata metadata) { ItemMetadata existing = find(metadata.getName()); if (existing != null) { return false; } add(metadata); return true; } void add(ItemHint itemHint) { this.metadataHints.add(itemHint); } boolean hasSimilarGroup(ItemMetadata metadata) { if (!metadata.isOfItemType(ItemMetadata.ItemType.GROUP)) { throw new IllegalStateException("item " + metadata + " must be a group"); } for (ItemMetadata existing : this.metadataItems) { if (existing.isOfItemType(ItemMetadata.ItemType.GROUP) && existing.getName().equals(metadata.getName()) && existing.getType().equals(metadata.getType())) { return true; } } return false; } ConfigurationMetadata getMetadata() { ConfigurationMetadata metadata = new ConfigurationMetadata(); for (ItemMetadata item : this.metadataItems) { metadata.add(item); } for (ItemHint metadataHint : this.metadataHints) { metadata.add(metadataHint); } if (this.previousMetadata != null) { List<ItemMetadata> items = this.previousMetadata.getItems(); for (ItemMetadata item : items) { if (this.mergeRequired.test(item)) { metadata.addIfMissing(item); } } } return metadata; } private ItemMetadata find(String name) { return this.metadataItems.stream() .filter((candidate) -> name.equals(candidate.getName())) .findFirst() .orElse(null); } }
MetadataCollector
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/ssl/SslConfiguration.java
{ "start": 17709, "end": 19939 }
class ____ { public static final String PREFIX = "trust-store"; private String path; private String password; private String type; private String provider; /** * The path to the trust store (typically .jks). Can also point to a PEM file containing * one or more X.509 certificates. Can use {@code classpath:}, {@code file:}, * {@code string:} or {@code base64:}. * * @return The resource containing the trust store */ public Optional<String> getPath() { return Optional.ofNullable(path); } /** * @return The password to the keyStore */ public Optional<String> getPassword() { return Optional.ofNullable(password); } /** * @return The key store type */ public Optional<String> getType() { return Optional.ofNullable(type); } /** * @return Provider for the key store. */ public Optional<String> getProvider() { return Optional.ofNullable(provider); } /** * The path to the trust store (typically .jks). Can also point to a PEM file containing * one or more X.509 certificates. Can use {@code classpath:}, {@code file:}, * {@code string:} or {@code base64:}. * * @param path The resource containing the trust store */ public void setPath(String path) { this.path = path; } /** * Sets the password to use for the keystore. * * @param password The password */ public void setPassword(String password) { this.password = password; } /** * Sets the type of keystore. * * @param type The keystore type */ public void setType(String type) { this.type = type; } /** * Sets the keystore provider name. * * @param provider The provider */ public void setProvider(String provider) { this.provider = provider; } } }
TrustStoreConfiguration
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/TaskAttemptUnsuccessfulCompletionEvent.java
{ "start": 1764, "end": 10901 }
class ____ implements HistoryEvent { private TaskAttemptUnsuccessfulCompletion datum = null; private TaskAttemptID attemptId; private TaskType taskType; private String status; private long finishTime; private String hostname; private int port; private String rackName; private String error; private Counters counters; int[][] allSplits; int[] clockSplits; int[] cpuUsages; int[] vMemKbytes; int[] physMemKbytes; private long startTime; private static final Counters EMPTY_COUNTERS = new Counters(); /** * Create an event to record the unsuccessful completion of attempts. * @param id Attempt ID * @param taskType Type of the task * @param status Status of the attempt * @param finishTime Finish time of the attempt * @param hostname Name of the host where the attempt executed * @param port rpc port for for the tracker * @param rackName Name of the rack where the attempt executed * @param error Error string * @param counters Counters for the attempt * @param allSplits the "splits", or a pixelated graph of various * measurable worker node state variables against progress. * Currently there are four; wallclock time, CPU time, * virtual memory and physical memory. * @param startTs Task start time to be used for writing entity to ATSv2. */ public TaskAttemptUnsuccessfulCompletionEvent (TaskAttemptID id, TaskType taskType, String status, long finishTime, String hostname, int port, String rackName, String error, Counters counters, int[][] allSplits, long startTs) { this.attemptId = id; this.taskType = taskType; this.status = status; this.finishTime = finishTime; this.hostname = hostname; this.port = port; this.rackName = rackName; this.error = error; this.counters = counters; this.allSplits = allSplits; this.clockSplits = ProgressSplitsBlock.arrayGetWallclockTime(allSplits); this.cpuUsages = ProgressSplitsBlock.arrayGetCPUTime(allSplits); this.vMemKbytes = ProgressSplitsBlock.arrayGetVMemKbytes(allSplits); this.physMemKbytes = ProgressSplitsBlock.arrayGetPhysMemKbytes(allSplits); this.startTime = startTs; } public TaskAttemptUnsuccessfulCompletionEvent(TaskAttemptID id, TaskType taskType, String status, long finishTime, String hostname, int port, String rackName, String error, Counters counters, int[][] allSplits) { this(id, taskType, status, finishTime, hostname, port, rackName, error, counters, allSplits, SystemClock.getInstance().getTime()); } /** * @deprecated please use the constructor with an additional * argument, an array of splits arrays instead. See * {@link org.apache.hadoop.mapred.ProgressSplitsBlock} * for an explanation of the meaning of that parameter. * * Create an event to record the unsuccessful completion of attempts * @param id Attempt ID * @param taskType Type of the task * @param status Status of the attempt * @param finishTime Finish time of the attempt * @param hostname Name of the host where the attempt executed * @param error Error string */ public TaskAttemptUnsuccessfulCompletionEvent (TaskAttemptID id, TaskType taskType, String status, long finishTime, String hostname, String error) { this(id, taskType, status, finishTime, hostname, -1, "", error, EMPTY_COUNTERS, null); } public TaskAttemptUnsuccessfulCompletionEvent (TaskAttemptID id, TaskType taskType, String status, long finishTime, String hostname, int port, String rackName, String error, int[][] allSplits) { this(id, taskType, status, finishTime, hostname, port, rackName, error, EMPTY_COUNTERS, allSplits); } TaskAttemptUnsuccessfulCompletionEvent() {} public Object getDatum() { if(datum == null) { datum = new TaskAttemptUnsuccessfulCompletion(); datum.setTaskid(new Utf8(attemptId.getTaskID().toString())); datum.setTaskType(new Utf8(taskType.name())); datum.setAttemptId(new Utf8(attemptId.toString())); datum.setFinishTime(finishTime); datum.setHostname(new Utf8(hostname)); if (rackName != null) { datum.setRackname(new Utf8(rackName)); } datum.setPort(port); datum.setError(new Utf8(error)); datum.setStatus(new Utf8(status)); datum.setCounters(EventWriter.toAvro(counters)); datum.setClockSplits(AvroArrayUtils.toAvro(ProgressSplitsBlock .arrayGetWallclockTime(allSplits))); datum.setCpuUsages(AvroArrayUtils.toAvro(ProgressSplitsBlock .arrayGetCPUTime(allSplits))); datum.setVMemKbytes(AvroArrayUtils.toAvro(ProgressSplitsBlock .arrayGetVMemKbytes(allSplits))); datum.setPhysMemKbytes(AvroArrayUtils.toAvro(ProgressSplitsBlock .arrayGetPhysMemKbytes(allSplits))); } return datum; } public void setDatum(Object odatum) { this.datum = (TaskAttemptUnsuccessfulCompletion)odatum; this.attemptId = TaskAttemptID.forName(datum.getAttemptId().toString()); this.taskType = TaskType.valueOf(datum.getTaskType().toString()); this.finishTime = datum.getFinishTime(); this.hostname = datum.getHostname().toString(); this.rackName = datum.getRackname().toString(); this.port = datum.getPort(); this.status = datum.getStatus().toString(); this.error = datum.getError().toString(); this.counters = EventReader.fromAvro(datum.getCounters()); this.clockSplits = AvroArrayUtils.fromAvro(datum.getClockSplits()); this.cpuUsages = AvroArrayUtils.fromAvro(datum.getCpuUsages()); this.vMemKbytes = AvroArrayUtils.fromAvro(datum.getVMemKbytes()); this.physMemKbytes = AvroArrayUtils.fromAvro(datum.getPhysMemKbytes()); } /** Gets the task id. */ public TaskID getTaskId() { return attemptId.getTaskID(); } /** Gets the task type. */ public TaskType getTaskType() { return TaskType.valueOf(taskType.toString()); } /** Gets the attempt id. */ public TaskAttemptID getTaskAttemptId() { return attemptId; } /** Gets the finish time. */ public long getFinishTime() { return finishTime; } /** * Gets the task attempt start time to be used while publishing to ATSv2. * @return task attempt start time. */ public long getStartTime() { return startTime; } /** Gets the name of the host where the attempt executed. */ public String getHostname() { return hostname; } /** Gets the rpc port for the host where the attempt executed. */ public int getPort() { return port; } /** Gets the rack name of the node where the attempt ran. */ public String getRackName() { return rackName == null ? null : rackName.toString(); } /** Gets the error string. */ public String getError() { return error.toString(); } /** * Gets the task attempt status. * @return task attempt status. */ public String getTaskStatus() { return status.toString(); } /** Gets the counters. */ Counters getCounters() { return counters; } /** Gets the event type. */ public EventType getEventType() { // Note that the task type can be setup/map/reduce/cleanup but the // attempt-type can only be map/reduce. // find out if the task failed or got killed boolean failed = TaskStatus.State.FAILED.toString().equals(getTaskStatus()); return getTaskId().getTaskType() == TaskType.MAP ? (failed ? EventType.MAP_ATTEMPT_FAILED : EventType.MAP_ATTEMPT_KILLED) : (failed ? EventType.REDUCE_ATTEMPT_FAILED : EventType.REDUCE_ATTEMPT_KILLED); } public int[] getClockSplits() { return clockSplits; } public int[] getCpuUsages() { return cpuUsages; } public int[] getVMemKbytes() { return vMemKbytes; } public int[] getPhysMemKbytes() { return physMemKbytes; } @Override public TimelineEvent toTimelineEvent() { TimelineEvent tEvent = new TimelineEvent(); tEvent.setId(StringUtils.toUpperCase(getEventType().name())); tEvent.addInfo("TASK_TYPE", getTaskType().toString()); tEvent.addInfo("TASK_ATTEMPT_ID", getTaskAttemptId() == null ? "" : getTaskAttemptId().toString()); tEvent.addInfo("FINISH_TIME", getFinishTime()); tEvent.addInfo("ERROR", getError()); tEvent.addInfo("STATUS", getTaskStatus()); tEvent.addInfo("HOSTNAME", getHostname()); tEvent.addInfo("PORT", getPort()); tEvent.addInfo("RACK_NAME", getRackName()); tEvent.addInfo("SHUFFLE_FINISH_TIME", getFinishTime()); tEvent.addInfo("SORT_FINISH_TIME", getFinishTime()); tEvent.addInfo("MAP_FINISH_TIME", getFinishTime()); return tEvent; } @Override public Set<TimelineMetric> getTimelineMetrics() { Set<TimelineMetric> metrics = JobHistoryEventUtils .countersToTimelineMetric(getCounters(), finishTime); return metrics; } }
TaskAttemptUnsuccessfulCompletionEvent
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/validation/NormalScopedConstructorTest.java
{ "start": 495, "end": 910 }
class ____ { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder().beanClasses(Unproxyable.class).shouldFail() .build(); @Test public void testFailure() { Throwable error = container.getFailure(); assertNotNull(error); assertTrue(error instanceof DeploymentException); } @ApplicationScoped static
NormalScopedConstructorTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/SystemIndices.java
{ "start": 54031, "end": 54353 }
interface ____ { void apply( ClusterService clusterService, ProjectResolver projectResolver, Client client, TimeValue masterNodeTimeout, ActionListener<ResetFeatureStateStatus> listener ); } } }
CleanupFunction
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/socket/server/support/WebSocketUpgradeHandlerPredicate.java
{ "start": 1195, "end": 1662 }
class ____ implements BiPredicate<Object, ServerWebExchange> { @Override public boolean test(Object handler, ServerWebExchange exchange) { if (handler instanceof WebSocketHandler) { HttpMethod method = exchange.getRequest().getMethod(); String header = exchange.getRequest().getHeaders().getUpgrade(); return (HttpMethod.GET.equals(method) && header != null && header.equalsIgnoreCase("websocket")); } return true; } }
WebSocketUpgradeHandlerPredicate
java
grpc__grpc-java
netty/src/main/java/io/grpc/netty/X509AuthorityVerifier.java
{ "start": 1132, "end": 4603 }
class ____ implements AuthorityVerifier { private final SSLEngine sslEngine; private final X509TrustManager x509ExtendedTrustManager; private static final Method checkServerTrustedMethod; static { Method method = null; try { Class<?> x509ExtendedTrustManagerClass = Class.forName("javax.net.ssl.X509ExtendedTrustManager"); method = x509ExtendedTrustManagerClass.getMethod("checkServerTrusted", X509Certificate[].class, String.class, SSLEngine.class); } catch (ClassNotFoundException e) { // Per-rpc authority overriding via call options will be disallowed. } catch (NoSuchMethodException e) { // Should never happen since X509ExtendedTrustManager was introduced in Android API level 24 // along with checkServerTrusted. } checkServerTrustedMethod = method; } public X509AuthorityVerifier(SSLEngine sslEngine, X509TrustManager x509ExtendedTrustManager) { this.sslEngine = checkNotNull(sslEngine, "sslEngine"); this.x509ExtendedTrustManager = x509ExtendedTrustManager; } @Override public Status verifyAuthority(@Nonnull String authority) { if (x509ExtendedTrustManager == null) { return Status.UNAVAILABLE.withDescription( "Can't allow authority override in rpc when X509ExtendedTrustManager" + " is not available"); } Status peerVerificationStatus; try { // Because the authority pseudo-header can contain a port number: // https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.3 verifyAuthorityAllowedForPeerCert(removeAnyPortNumber(authority)); peerVerificationStatus = Status.OK; } catch (SSLPeerUnverifiedException | CertificateException | InvocationTargetException | IllegalAccessException | IllegalStateException e) { peerVerificationStatus = Status.UNAVAILABLE.withDescription( String.format("Peer hostname verification during rpc failed for authority '%s'", authority)).withCause(e); } return peerVerificationStatus; } private String removeAnyPortNumber(String authority) { int closingSquareBracketIndex = authority.lastIndexOf(']'); int portNumberSeperatorColonIndex = authority.lastIndexOf(':'); if (portNumberSeperatorColonIndex > closingSquareBracketIndex) { return authority.substring(0, portNumberSeperatorColonIndex); } return authority; } private void verifyAuthorityAllowedForPeerCert(String authority) throws SSLPeerUnverifiedException, CertificateException, InvocationTargetException, IllegalAccessException { SSLEngine sslEngineWrapper = new ProtocolNegotiators.SslEngineWrapper(sslEngine, authority); // The typecasting of Certificate to X509Certificate should work because this method will only // be called when using TLS and thus X509. Certificate[] peerCertificates = sslEngine.getSession().getPeerCertificates(); X509Certificate[] x509PeerCertificates = new X509Certificate[peerCertificates.length]; for (int i = 0; i < peerCertificates.length; i++) { x509PeerCertificates[i] = (X509Certificate) peerCertificates[i]; } if (checkServerTrustedMethod == null) { throw new IllegalStateException("checkServerTrustedMethod not found"); } checkServerTrustedMethod.invoke( x509ExtendedTrustManager, x509PeerCertificates, "UNKNOWN", sslEngineWrapper); } }
X509AuthorityVerifier
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/TemporalAccessorGetChronoFieldTest.java
{ "start": 886, "end": 1341 }
class ____ { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(TemporalAccessorGetChronoField.class, getClass()); @Test public void temporalAccessor_getLong_noStaticImport() { helper .addSourceLines( "TestClass.java", """ import static java.time.DayOfWeek.MONDAY; import java.time.temporal.ChronoField; public
TemporalAccessorGetChronoFieldTest
java
quarkusio__quarkus
extensions/redis-client/runtime/src/main/java/io/quarkus/redis/runtime/datasource/ReactiveTimeSeriesCommandsImpl.java
{ "start": 1305, "end": 9630 }
class ____<K> extends AbstractTimeSeriesCommands<K> implements ReactiveTimeSeriesCommands<K>, ReactiveRedisCommands { private final ReactiveRedisDataSource reactive; protected final Type keyType; public ReactiveTimeSeriesCommandsImpl(ReactiveRedisDataSourceImpl redis, Type k) { super(redis, k); this.keyType = k; this.reactive = redis; } @Override public ReactiveRedisDataSource getDataSource() { return reactive; } @Override public Uni<Void> tsCreate(K key, CreateArgs args) { return super._tsCreate(key, args) .replaceWithVoid(); } @Override public Uni<Void> tsCreate(K key) { return super._tsCreate(key) .replaceWithVoid(); } @Override public Uni<Void> tsAdd(K key, long timestamp, double value, AddArgs args) { return super._tsAdd(key, timestamp, value, args) .replaceWithVoid(); } @Override public Uni<Void> tsAdd(K key, double value, AddArgs args) { return super._tsAdd(key, value, args) .replaceWithVoid(); } @Override public Uni<Void> tsAdd(K key, long timestamp, double value) { return super._tsAdd(key, timestamp, value) .replaceWithVoid(); } @Override public Uni<Void> tsAdd(K key, double value) { return super._tsAdd(key, value) .replaceWithVoid(); } @Override public Uni<Void> tsAlter(K key, AlterArgs args) { return super._tsAlter(key, args) .replaceWithVoid(); } @Override public Uni<Void> tsCreateRule(K key, K destKey, Aggregation aggregation, Duration bucketDuration) { return super._tsCreateRule(key, destKey, aggregation, bucketDuration) .replaceWithVoid(); } @Override public Uni<Void> tsCreateRule(K key, K destKey, Aggregation aggregation, Duration bucketDuration, long alignTimestamp) { return super._tsCreateRule(key, destKey, aggregation, bucketDuration, alignTimestamp) .replaceWithVoid(); } @Override public Uni<Void> tsDecrBy(K key, double value) { return super._tsDecrBy(key, value) .replaceWithVoid(); } @Override public Uni<Void> tsDecrBy(K key, double value, IncrementArgs args) { return super._tsDecrBy(key, value, args) .replaceWithVoid(); } @Override public Uni<Void> tsDel(K key, long fromTimestamp, long toTimestamp) { return super._tsDel(key, fromTimestamp, toTimestamp) .replaceWithVoid(); } @Override public Uni<Void> tsDeleteRule(K key, K destKey) { return super._tsDeleteRule(key, destKey) .replaceWithVoid(); } @Override public Uni<Sample> tsGet(K key) { return super._tsGet(key) .map(this::decodeSample); } Sample decodeSample(Response response) { if (response == null || response.size() == 0) { return null; } return new Sample(response.get(0).toLong(), response.get(1).toDouble()); } @Override public Uni<Sample> tsGet(K key, boolean latest) { return super._tsGet(key, latest) .map(this::decodeSample); } @Override public Uni<Void> tsIncrBy(K key, double value) { return super._tsIncrBy(key, value) .replaceWithVoid(); } @Override public Uni<Void> tsIncrBy(K key, double value, IncrementArgs args) { return super._tsIncrBy(key, value, args) .replaceWithVoid(); } @Override public Uni<Void> tsMAdd(SeriesSample<K>... samples) { return super._tsMAdd(samples) .replaceWithVoid(); } @Override public Uni<Map<String, SampleGroup>> tsMGet(MGetArgs args, Filter... filters) { return super._tsMGet(args, filters) .map(this::decodeGroup); } @Override public Uni<Map<String, SampleGroup>> tsMGet(Filter... filters) { return super._tsMGet(filters) .map(this::decodeGroup); } Map<String, SampleGroup> decodeGroup(Response response) { if (response == null) { return null; } if (response.size() == 0) { return Collections.emptyMap(); } Map<String, SampleGroup> groups = new HashMap<>(); if (isMap(response)) { for (String group : response.getKeys()) { Map<String, String> labels = new HashMap<>(); List<Sample> samples = new ArrayList<>(); var nested = response.get(group); for (Response label : nested.get(0)) { labels.put(label.get(0).toString(), label.get(1).toString()); } for (Response sample : nested.get(nested.size() - 1)) { // samples are last if (sample.type() == ResponseType.MULTI) { samples.add(decodeSample(sample)); } else { samples.add(new Sample(sample.toLong(), nested.get(nested.size() - 1).get(1).toDouble())); break; } } groups.put(group, new SampleGroup(group, labels, samples)); } return groups; } for (Response nested : response) { // this should be the group String group = nested.get(0).toString(); Map<String, String> labels = new HashMap<>(); List<Sample> samples = new ArrayList<>(); // labels are in 1 for (Response label : nested.get(1)) { labels.put(label.get(0).toString(), label.get(1).toString()); } // samples are in 2, either as a tuple or a list for (Response sample : nested.get(2)) { if (sample.type() == ResponseType.MULTI) { samples.add(decodeSample(sample)); } else { samples.add(new Sample(sample.toLong(), nested.get(2).get(1).toDouble())); break; } } groups.put(group, new SampleGroup(group, labels, samples)); } return groups; } @Override public Uni<Map<String, SampleGroup>> tsMRange(TimeSeriesRange range, Filter... filters) { return super._tsMRange(range, filters) .map(this::decodeGroup); } @Override public Uni<Map<String, SampleGroup>> tsMRange(TimeSeriesRange range, MRangeArgs args, Filter... filters) { return super._tsMRange(range, args, filters) .map(this::decodeGroup); } @Override public Uni<Map<String, SampleGroup>> tsMRevRange(TimeSeriesRange range, Filter... filters) { return super._tsMRevRange(range, filters) .map(this::decodeGroup); } @Override public Uni<Map<String, SampleGroup>> tsMRevRange(TimeSeriesRange range, MRangeArgs args, Filter... filters) { return super._tsMRevRange(range, args, filters) .map(this::decodeGroup); } @Override public Uni<List<K>> tsQueryIndex(Filter... filters) { return super._tsQueryIndex(filters) .map(r -> marshaller.decodeAsList(r, keyType)); } @Override public Uni<List<Sample>> tsRange(K key, TimeSeriesRange range) { return super._tsRange(key, range) .map(r -> marshaller.decodeAsList(r, this::decodeSample)); } @Override public Uni<List<Sample>> tsRange(K key, TimeSeriesRange range, RangeArgs args) { return super._tsRange(key, range, args) .map(r -> marshaller.decodeAsList(r, this::decodeSample)); } @Override public Uni<List<Sample>> tsRevRange(K key, TimeSeriesRange range) { return super._tsRevRange(key, range) .map(r -> marshaller.decodeAsList(r, this::decodeSample)); } @Override public Uni<List<Sample>> tsRevRange(K key, TimeSeriesRange range, RangeArgs args) { return super._tsRevRange(key, range, args) .map(r -> marshaller.decodeAsList(r, this::decodeSample)); } }
ReactiveTimeSeriesCommandsImpl
java
elastic__elasticsearch
x-pack/plugin/mapper-constant-keyword/src/main/java/org/elasticsearch/xpack/constantkeyword/mapper/ConstantKeywordFieldMapper.java
{ "start": 3028, "end": 3546 }
class ____ extends FieldMapper { private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(ConstantKeywordFieldMapper.class); public static final String CONTENT_TYPE = "constant_keyword"; private static ConstantKeywordFieldMapper toType(FieldMapper in) { return (ConstantKeywordFieldMapper) in; } @Override public FieldMapper.Builder getMergeBuilder() { return new Builder(leafName()).init(this); } public static
ConstantKeywordFieldMapper
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/NerConfigTests.java
{ "start": 725, "end": 3009 }
class ____ extends InferenceConfigItemTestCase<NerConfig> { public static NerConfig mutateForVersion(NerConfig instance, TransportVersion version) { return new NerConfig( instance.getVocabularyConfig(), InferenceConfigTestScaffolding.mutateTokenizationForVersion(instance.getTokenization(), version), instance.getClassificationLabels(), instance.getResultsField() ); } @Override protected boolean supportsUnknownFields() { return true; } @Override protected Predicate<String> getRandomFieldsExcludeFilter() { return field -> field.isEmpty() == false; } @Override protected NerConfig doParseInstance(XContentParser parser) throws IOException { return NerConfig.fromXContentLenient(parser); } @Override protected Writeable.Reader<NerConfig> instanceReader() { return NerConfig::new; } @Override protected NerConfig createTestInstance() { return createRandom(); } @Override protected NerConfig mutateInstance(NerConfig instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected NerConfig mutateInstanceForVersion(NerConfig instance, TransportVersion version) { return mutateForVersion(instance, version); } public static NerConfig createRandom() { Set<String> randomClassificationLabels = new HashSet<>( Stream.generate(() -> randomFrom("O", "B_PER", "I_PER", "B_ORG", "I_ORG", "B_LOC", "I_LOC", "B_CUSTOM", "I_CUSTOM")) .limit(10) .toList() ); randomClassificationLabels.add("O"); return new NerConfig( randomBoolean() ? null : VocabularyConfigTests.createRandom(), randomBoolean() ? null : randomFrom( BertTokenizationTests.createRandom(), MPNetTokenizationTests.createRandom(), RobertaTokenizationTests.createRandom() ), randomBoolean() ? null : new ArrayList<>(randomClassificationLabels), randomBoolean() ? null : randomAlphaOfLength(5) ); } }
NerConfigTests
java
apache__flink
flink-tests/src/test/java/org/apache/flink/connector/upserttest/table/UpsertTestDynamicTableSinkITCase.java
{ "start": 1774, "end": 4962 }
class ____ { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @Test void testWritingDocumentsInBatchMode(@TempDir File tempDir) throws Exception { TableEnvironment tEnv = TableEnvironment.create(EnvironmentSettings.inBatchMode()); String format = "json"; File outputFile = new File(tempDir, "records.out"); String outputFilepath = outputFile.toString(); final String createTable = String.format( "CREATE TABLE UpsertFileSinkTable (\n" + " user_id INT,\n" + " user_name STRING,\n" + " user_count BIGINT,\n" + " PRIMARY KEY (user_id) NOT ENFORCED\n" + " ) WITH (\n" + " 'connector' = '%s',\n" + " 'key.format' = '%s',\n" + " 'value.format' = '%s',\n" + " 'output-filepath' = '%s'\n" + " );", UpsertTestDynamicTableSinkFactory.IDENTIFIER, format, format, outputFilepath); tEnv.executeSql(createTable); String insertSql = "INSERT INTO UpsertFileSinkTable\n" + "SELECT user_id, user_name, COUNT(*) AS user_count\n" + "FROM (VALUES (1, 'Bob'), (22, 'Tom'), (42, 'Kim'), (42, 'Kim'), (42, 'Kim'), (1, 'Bob'))\n" + " AS UserCountTable(user_id, user_name)\n" + "GROUP BY user_id, user_name"; tEnv.executeSql(insertSql).await(); /* | user_id | user_name | user_count | | ------- | --------- | ---------- | | 1 | Bob | 2 | | 22 | Tom | 1 | | 42 | Kim | 3 | */ int numberOfResultRecords = UpsertTestFileUtil.getNumberOfRecords(outputFile); assertThat(numberOfResultRecords).isEqualTo(3); DeserializationSchema<String> deserializationSchema = new SimpleStringSchema(); Map<String, String> records = UpsertTestFileUtil.readRecords( outputFile, deserializationSchema, deserializationSchema); Map<String, String> expected = new HashMap<>(); expected.put("{\"user_id\":1}", "{\"user_id\":1,\"user_name\":\"Bob\",\"user_count\":2}"); expected.put("{\"user_id\":22}", "{\"user_id\":22,\"user_name\":\"Tom\",\"user_count\":1}"); expected.put("{\"user_id\":42}", "{\"user_id\":42,\"user_name\":\"Kim\",\"user_count\":3}"); assertThat(records).isEqualTo(expected); } }
UpsertTestDynamicTableSinkITCase
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 21594, "end": 22108 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return dialect instanceof H2Dialect || dialect instanceof PostgreSQLDialect || dialect instanceof HANADialect || dialect instanceof CockroachDialect || dialect instanceof DB2Dialect db2 && db2.getDB2Version().isSameOrAfter( 11 ) || dialect instanceof OracleDialect || dialect instanceof SpannerDialect || dialect instanceof SQLServerDialect; } } public static
SupportsInverseDistributionFunctions
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/MulticastFineGrainedErrorHandlingTest.java
{ "start": 1027, "end": 2958 }
class ____ extends ContextTestSupport { @Test public void testMulticastOk() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { onException(Exception.class).redeliveryDelay(0).maximumRedeliveries(2); from("direct:start").to("mock:a").multicast().stopOnException().to("mock:foo", "mock:bar", "mock:baz"); } }); context.start(); getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:bar").expectedMessageCount(1); getMockEndpoint("mock:baz").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Test public void testMulticastError() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { onException(Exception.class).redeliveryDelay(0).maximumRedeliveries(2); from("direct:start").to("mock:a").multicast().stopOnException().to("mock:foo", "mock:bar") .throwException(new IllegalArgumentException("Damn")).to("mock:baz"); } }); context.start(); getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:bar").expectedMessageCount(1); getMockEndpoint("mock:baz").expectedMessageCount(0); try { template.sendBody("direct:start", "Hello World"); fail("Should throw exception"); } catch (Exception e) { // expected } assertMockEndpointsSatisfied(); } @Override public boolean isUseRouteBuilder() { return false; } }
MulticastFineGrainedErrorHandlingTest
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java
{ "start": 1152, "end": 2559 }
class ____ { @Test void withAutodetection() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); assertThatExceptionOfType(BeansException.class).isThrownBy(() -> reader.loadBeanDefinitions(new ClassPathResource("invalidPerSchema.xml", getClass()))) .withCauseInstanceOf(SAXParseException.class); } @Test void withExplicitValidationMode() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); assertThatExceptionOfType(BeansException.class).isThrownBy(() -> reader.loadBeanDefinitions(new ClassPathResource("invalidPerSchema.xml", getClass()))) .withCauseInstanceOf(SAXParseException.class); } @Test void loadDefinitions() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); reader.loadBeanDefinitions(new ClassPathResource("schemaValidated.xml", getClass())); TestBean foo = (TestBean) bf.getBean("fooBean"); assertThat(foo.getSpouse()).as("Spouse is null").isNotNull(); assertThat(foo.getFriends().size()).as("Incorrect number of friends").isEqualTo(2); } }
SchemaValidationTests
java
elastic__elasticsearch
modules/transport-netty4/src/test/java/org/elasticsearch/http/netty4/Netty4TestUtils.java
{ "start": 846, "end": 1374 }
enum ____ { ; public static ClusterSettings randomClusterSettings() { return new ClusterSettings( Settings.builder().put(HttpTransportSettings.SETTING_HTTP_CLIENT_STATS_ENABLED.getKey(), randomBoolean()).build(), Sets.addToCopy( ClusterSettings.BUILT_IN_CLUSTER_SETTINGS, Netty4Plugin.SETTING_HTTP_NETTY_TLS_HANDSHAKES_MAX_IN_PROGRESS, Netty4Plugin.SETTING_HTTP_NETTY_TLS_HANDSHAKES_MAX_DELAYED ) ); } }
Netty4TestUtils
java
spring-projects__spring-framework
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpLT.java
{ "start": 1227, "end": 4281 }
class ____ extends Operator { public OpLT(int startPos, int endPos, SpelNodeImpl... operands) { super("<", startPos, endPos, operands); this.exitTypeDescriptor = "Z"; } @Override public BooleanTypedValue getValueInternal(ExpressionState state) throws EvaluationException { Object left = getLeftOperand().getValueInternal(state).getValue(); Object right = getRightOperand().getValueInternal(state).getValue(); this.leftActualDescriptor = CodeFlow.toDescriptorFromObject(left); this.rightActualDescriptor = CodeFlow.toDescriptorFromObject(right); if (left instanceof Number leftNumber && right instanceof Number rightNumber) { if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) { BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class); BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class); return BooleanTypedValue.forValue(leftBigDecimal.compareTo(rightBigDecimal) < 0); } else if (leftNumber instanceof Double || rightNumber instanceof Double) { return BooleanTypedValue.forValue(leftNumber.doubleValue() < rightNumber.doubleValue()); } else if (leftNumber instanceof Float || rightNumber instanceof Float) { return BooleanTypedValue.forValue(leftNumber.floatValue() < rightNumber.floatValue()); } else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger) { BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class); BigInteger rightBigInteger = NumberUtils.convertNumberToTargetClass(rightNumber, BigInteger.class); return BooleanTypedValue.forValue(leftBigInteger.compareTo(rightBigInteger) < 0); } else if (leftNumber instanceof Long || rightNumber instanceof Long) { return BooleanTypedValue.forValue(leftNumber.longValue() < rightNumber.longValue()); } else if (leftNumber instanceof Integer || rightNumber instanceof Integer) { return BooleanTypedValue.forValue(leftNumber.intValue() < rightNumber.intValue()); } else if (leftNumber instanceof Short || rightNumber instanceof Short) { return BooleanTypedValue.forValue(leftNumber.shortValue() < rightNumber.shortValue()); } else if (leftNumber instanceof Byte || rightNumber instanceof Byte) { return BooleanTypedValue.forValue(leftNumber.byteValue() < rightNumber.byteValue()); } else { // Unknown Number subtypes -> best guess is double comparison return BooleanTypedValue.forValue(leftNumber.doubleValue() < rightNumber.doubleValue()); } } if (left instanceof CharSequence && right instanceof CharSequence) { left = left.toString(); right = right.toString(); } return BooleanTypedValue.forValue(state.getTypeComparator().compare(left, right) < 0); } @Override public boolean isCompilable() { return isCompilableOperatorUsingNumerics(); } @Override public void generateCode(MethodVisitor mv, CodeFlow cf) { generateComparisonCode(mv, cf, IFGE, IF_ICMPGE); } }
OpLT
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/support/DynamicPropertiesContextCustomizerFactoryTests.java
{ "start": 2894, "end": 2961 }
class ____ { void empty() { } } static
NoDynamicPropertySource
java
grpc__grpc-java
api/src/main/java/io/grpc/SynchronizationContext.java
{ "start": 8436, "end": 9115 }
class ____ implements Runnable { final Runnable task; boolean isCancelled; boolean hasStarted; ManagedRunnable(Runnable task) { this.task = checkNotNull(task, "task"); } @Override public void run() { // The task may have been cancelled after timerService calls SynchronizationContext.execute() // but before the runnable is actually run. We must guarantee that the task will not be run // in this case. if (!isCancelled) { hasStarted = true; task.run(); } } } /** * Allows the user to check the status and/or cancel a task scheduled by {@link #schedule}. * * <p>This
ManagedRunnable
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProtoBufRPCCompatibility.java
{ "start": 2691, "end": 3479 }
class ____ implements OldRpcService { @Override public EmptyResponseProto ping(RpcController unused, EmptyRequestProto request) throws ServiceException { // Ensure clientId is received byte[] clientId = Server.getClientId(); assertNotNull(Server.getClientId()); assertEquals(16, clientId.length); return EmptyResponseProto.newBuilder().build(); } @Override public EmptyResponseProto echo(RpcController unused, EmptyRequestProto request) throws ServiceException { // Ensure clientId is received byte[] clientId = Server.getClientId(); assertNotNull(Server.getClientId()); assertEquals(16, clientId.length); return EmptyResponseProto.newBuilder().build(); } } public static
OldServerImpl
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/builtin/mapper/XmlGregCalToCalendarMapper.java
{ "start": 410, "end": 614 }
interface ____ { XmlGregCalToCalendarMapper INSTANCE = Mappers.getMapper( XmlGregCalToCalendarMapper.class ); CalendarProperty map( XmlGregorianCalendarProperty source); }
XmlGregCalToCalendarMapper
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/predicate/Predicates.java
{ "start": 874, "end": 6261 }
class ____ { public static List<Expression> splitAnd(Expression exp) { if (exp instanceof And and) { List<Expression> list = new ArrayList<>(); list.addAll(splitAnd(and.left())); list.addAll(splitAnd(and.right())); return list; } return singletonList(exp); } public static List<Expression> splitOr(Expression exp) { if (exp instanceof Or or) { List<Expression> list = new ArrayList<>(); list.addAll(splitOr(or.left())); list.addAll(splitOr(or.right())); return list; } return singletonList(exp); } public static Expression combineOr(List<Expression> exps) { return combine(exps, (l, r) -> new Or(l.source(), l, r)); } public static Expression combineAnd(List<Expression> exps) { return combine(exps, (l, r) -> new And(l.source(), l, r)); } public static Expression combineAndWithSource(List<Expression> exps, Source source) { return combine(exps, (l, r) -> new And(source, l, r)); } /** * Build a binary 'pyramid' from the given list: * <pre> * AND * / \ * AND AND * / \ / \ * A B C D * </pre> * * using the given combiner. * * While a bit longer, this method creates a balanced tree as opposed to a plain * recursive approach which creates an unbalanced one (either to the left or right). */ private static Expression combine(List<Expression> exps, BiFunction<Expression, Expression, Expression> combiner) { if (exps.isEmpty()) { return null; } // clone the list (to modify it) List<Expression> result = new ArrayList<>(exps); while (result.size() > 1) { // combine (in place) expressions in pairs // NB: this loop modifies the list (just like an array) for (int i = 0; i < result.size() - 1; i++) { // keep the current element to update it in place Expression l = result.get(i); // remove the next element due to combining Expression r = result.remove(i + 1); result.set(i, combiner.apply(l, r)); } } return result.get(0); } public static List<Expression> inCommon(List<Expression> l, List<Expression> r) { List<Expression> common = new ArrayList<>(Math.min(l.size(), r.size())); for (Expression lExp : l) { for (Expression rExp : r) { if (lExp.semanticEquals(rExp)) { common.add(lExp); } } } return common.isEmpty() ? emptyList() : common; } public static List<Expression> subtract(List<Expression> from, List<Expression> list) { List<Expression> diff = new ArrayList<>(Math.min(from.size(), list.size())); for (Expression f : from) { boolean found = false; for (Expression l : list) { if (f.semanticEquals(l)) { found = true; break; } } if (found == false) { diff.add(f); } } return diff.isEmpty() ? emptyList() : diff; } /** * Given a list of expressions of predicates, extract a new expression of * all the common ones and return it, along the original list with the * common ones removed. * <p> * Example: for ['field1 > 0 AND field2 > 0', 'field1 > 0 AND field3 > 0', * 'field1 > 0'], the function will return 'field1 > 0' as the common * predicate expression and ['field2 > 0', 'field3 > 0', Literal.TRUE] as * the left predicates list. * * @param expressions list of expressions to extract common predicates from. * @return a tuple having as the first element an expression of the common * predicates and as the second element the list of expressions with the * common predicates removed. If there are no common predicates, `null` will * be returned as the first element and the original list as the second. If * for one of the expressions in the input list, nothing is left after * trimming the common predicates, it will be replaced with Literal.TRUE. */ public static Tuple<Expression, List<Expression>> extractCommon(List<Expression> expressions) { List<Expression> common = null; List<List<Expression>> splitAnds = new ArrayList<>(expressions.size()); for (var expression : expressions) { var split = splitAnd(expression); common = common == null ? split : inCommon(split, common); if (common.isEmpty()) { return Tuple.tuple(null, expressions); } splitAnds.add(split); } if (common == null) { common = List.of(); } List<Expression> trimmed = new ArrayList<>(expressions.size()); final List<Expression> finalCommon = common; splitAnds.forEach(split -> { var subtracted = subtract(split, finalCommon); trimmed.add(subtracted.isEmpty() ? Literal.TRUE : combineAnd(subtracted)); }); return Tuple.tuple(combineAnd(common), trimmed); } }
Predicates
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/db2/DB2SelectTest_hierarchical_1.java
{ "start": 948, "end": 3032 }
class ____ extends MysqlTest { protected final DbType dbType = JdbcConstants.DB2; public void test_0() throws Exception { String sql = "SELECT last_name, employee_id, manager_id, LEVEL\n" + " FROM employees\n" + " START WITH employee_id = 100\n" + " CONNECT BY PRIOR employee_id = manager_id\n" + " ORDER SIBLINGS BY last_name;"; List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType); SQLStatement stmt = stmtList.get(0); { String result = SQLUtils.toSQLString(stmt, dbType); assertEquals("SELECT last_name, employee_id, manager_id, LEVEL\n" + "FROM employees\n" + "START WITH employee_id = 100\n" + "CONNECT BY PRIOR employee_id = manager_id\n" + "ORDER SIBLINGS BY last_name;", result); } { String result = SQLUtils.toSQLString(stmt, dbType, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION); assertEquals("select last_name, employee_id, manager_id, LEVEL\n" + "from employees\n" + "start with employee_id = 100\n" + "connect by prior employee_id = manager_id\n" + "order siblings by last_name;", result); } assertEquals(1, stmtList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(dbType); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(3, visitor.getColumns().size()); assertEquals(2, visitor.getConditions().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("t_basic_store"))); } }
DB2SelectTest_hierarchical_1
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/metrics/HttpFSServerMetrics.java
{ "start": 1980, "end": 5119 }
class ____ { private @Metric MutableCounterLong bytesWritten; private @Metric MutableCounterLong bytesRead; // Write ops private @Metric MutableCounterLong opsCreate; private @Metric MutableCounterLong opsAppend; private @Metric MutableCounterLong opsTruncate; private @Metric MutableCounterLong opsDelete; private @Metric MutableCounterLong opsRename; private @Metric MutableCounterLong opsMkdir; // Read ops private @Metric MutableCounterLong opsOpen; private @Metric MutableCounterLong opsListing; private @Metric MutableCounterLong opsStat; private @Metric MutableCounterLong opsCheckAccess; private @Metric MutableCounterLong opsStatus; private @Metric MutableCounterLong opsAllECPolicies; private @Metric MutableCounterLong opsECCodecs; private @Metric MutableCounterLong opsTrashRoots; private final MetricsRegistry registry = new MetricsRegistry("httpfsserver"); private final String name; private JvmMetrics jvmMetrics = null; public HttpFSServerMetrics(String name, String sessionId, final JvmMetrics jvmMetrics) { this.name = name; this.jvmMetrics = jvmMetrics; registry.tag(SessionId, sessionId); } public static HttpFSServerMetrics create(Configuration conf, String serverName) { String sessionId = conf.get(DFSConfigKeys.DFS_METRICS_SESSION_ID_KEY); MetricsSystem ms = DefaultMetricsSystem.instance(); JvmMetrics jm = JvmMetrics.create("HttpFSServer", sessionId, ms); String name = "ServerActivity-"+ (serverName.isEmpty() ? "UndefinedServer"+ ThreadLocalRandom.current().nextInt() : serverName.replace(':', '-')); return ms.register(name, null, new HttpFSServerMetrics(name, sessionId, jm)); } public String name() { return name; } public JvmMetrics getJvmMetrics() { return jvmMetrics; } public void incrBytesWritten(long bytes) { bytesWritten.incr(bytes); } public void incrBytesRead(long bytes) { bytesRead.incr(bytes); } public void incrOpsCreate() { opsCreate.incr(); } public void incrOpsAppend() { opsAppend.incr(); } public void incrOpsTruncate() { opsTruncate.incr(); } public void incrOpsDelete() { opsDelete.incr(); } public void incrOpsRename() { opsRename.incr(); } public void incrOpsMkdir() { opsMkdir.incr(); } public void incrOpsOpen() { opsOpen.incr(); } public void incrOpsListing() { opsListing.incr(); } public void incrOpsStat() { opsStat.incr(); } public void incrOpsCheckAccess() { opsCheckAccess.incr(); } public void shutdown() { DefaultMetricsSystem.shutdown(); } public long getOpsMkdir() { return opsMkdir.value(); } public long getOpsListing() { return opsListing.value(); } public long getOpsStat() { return opsStat.value(); } public void incrOpsStatus() { opsStatus.incr(); } public void incrOpsAllECPolicies() { opsAllECPolicies.incr(); } public void incrOpsECCodecs() { opsECCodecs.incr(); } public void incrOpsTrashRoots() { opsTrashRoots.incr(); } }
HttpFSServerMetrics
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_289/Issue289Mapper.java
{ "start": 309, "end": 713 }
interface ____ { Issue289Mapper INSTANCE = Mappers.getMapper( Issue289Mapper.class ); TargetWithoutSetter sourceToTargetWithoutSetter(Source source); void sourceToTargetWithoutSetter(Source source, @MappingTarget TargetWithoutSetter target); TargetWithSetter sourceToTargetWithSetter(Source source); TargetElement sourceElementToTargetElement(SourceElement source); }
Issue289Mapper
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1590/Book.java
{ "start": 198, "end": 367 }
class ____ { private final String name; public Book(String name) { this.name = name; } public String getName() { return name; } }
Book
java
FasterXML__jackson-core
src/test/java/tools/jackson/core/unittest/testutil/ByteOutputStreamForTesting.java
{ "start": 128, "end": 234 }
class ____ verifying that {@link java.io.OutputStream} is (or is not) * closed and/or flushed. */ public
for
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/query/HbmResultSetMappingDescriptor.java
{ "start": 33369, "end": 34737 }
class ____ implements ResultDescriptor { private final String columnName; private final String hibernateTypeName; public ScalarDescriptor(String columnName, String hibernateTypeName) { this.columnName = columnName; this.hibernateTypeName = hibernateTypeName; BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Creating ScalarDescriptor (%s)", columnName ); } public ScalarDescriptor(JaxbHbmNativeQueryScalarReturnType hbmScalarReturn) { this( hbmScalarReturn.getColumn(), hbmScalarReturn.getType() ); } @Override public ResultMementoBasicStandard resolve(ResultSetMappingResolutionContext resolutionContext) { BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Resolving HBM ScalarDescriptor into memento - %s", columnName ); if ( hibernateTypeName != null ) { final BasicType<?> namedType = resolutionContext.getTypeConfiguration().getBasicTypeRegistry() .getRegisteredType( hibernateTypeName ); if ( namedType == null ) { throw new IllegalArgumentException( "Could not resolve named type : " + hibernateTypeName ); } return new ResultMementoBasicStandard( columnName, namedType, resolutionContext ); } // todo (6.0) : column name may be optional in HBM - double check return new ResultMementoBasicStandard( columnName, null, resolutionContext ); } } }
ScalarDescriptor
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 8489, "end": 8733 }
class ____ { abstract Class<? extends Number> numberClass(); static Builder builder() { return new AutoValue_AutoValueTest_ClassPropertyWithBuilder.Builder(); } @AutoValue.Builder abstract static
ClassPropertyWithBuilder
java
spring-projects__spring-boot
module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/autoconfigure/actuate/web/WebFluxEndpointManagementContextConfiguration.java
{ "start": 4652, "end": 9073 }
class ____ { private static final List<MediaType> MEDIA_TYPES = Collections .unmodifiableList(Arrays.asList(MediaType.APPLICATION_JSON, new MediaType("application", "*+json"))); @Bean @ConditionalOnMissingBean @SuppressWarnings("removal") public WebFluxEndpointHandlerMapping webEndpointReactiveHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) { String basePath = webEndpointProperties.getBasePath(); EndpointMapping endpointMapping = new EndpointMapping(basePath); Collection<ExposableWebEndpoint> endpoints = webEndpointsSupplier.getEndpoints(); List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>(); allEndpoints.addAll(endpoints); allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints()); return new WebFluxEndpointHandlerMapping(endpointMapping, endpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping(webEndpointProperties, environment, basePath)); } private boolean shouldRegisterLinksMapping(WebEndpointProperties properties, Environment environment, String basePath) { return properties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment) == ManagementPortType.DIFFERENT); } @Bean @ConditionalOnManagementPort(ManagementPortType.DIFFERENT) @ConditionalOnAvailableEndpoint(endpoint = HealthEndpoint.class, exposure = EndpointExposure.WEB) @ConditionalOnBean(HealthEndpoint.class) public AdditionalHealthEndpointPathsWebFluxHandlerMapping managementHealthEndpointWebFluxHandlerMapping( WebEndpointsSupplier webEndpointsSupplier, HealthEndpointGroups groups) { Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints(); ExposableWebEndpoint healthEndpoint = webEndpoints.stream() .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) .findFirst() .orElse(null); return new AdditionalHealthEndpointPathsWebFluxHandlerMapping(new EndpointMapping(""), healthEndpoint, groups.getAllWithAdditionalPath(WebServerNamespace.MANAGEMENT)); } @Bean @ConditionalOnMissingBean @SuppressWarnings("removal") @Deprecated(since = "3.3.5", forRemoval = true) public org.springframework.boot.webflux.actuate.endpoint.web.ControllerEndpointHandlerMapping controllerEndpointHandlerMapping( org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier controllerEndpointsSupplier, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, EndpointAccessResolver endpointAccessResolver) { EndpointMapping endpointMapping = new EndpointMapping(webEndpointProperties.getBasePath()); return new org.springframework.boot.webflux.actuate.endpoint.web.ControllerEndpointHandlerMapping( endpointMapping, controllerEndpointsSupplier.getEndpoints(), corsProperties.toCorsConfiguration(), endpointAccessResolver); } @Bean @ConditionalOnBean(EndpointJsonMapper.class) @Role(BeanDefinition.ROLE_INFRASTRUCTURE) static ServerCodecConfigurerEndpointJsonMapperBeanPostProcessor serverCodecConfigurerEndpointJsonMapperBeanPostProcessor( ObjectProvider<EndpointJsonMapper> endpointJsonMapper) { return new ServerCodecConfigurerEndpointJsonMapperBeanPostProcessor( SingletonSupplier.of(endpointJsonMapper::getObject)); } @Bean @SuppressWarnings("removal") @ConditionalOnBean(org.springframework.boot.actuate.endpoint.jackson.EndpointJackson2ObjectMapper.class) @Role(BeanDefinition.ROLE_INFRASTRUCTURE) static ServerCodecConfigurerEndpointJackson2JsonMapperBeanPostProcessor serverCodecConfigurerEndpointJackson2JsonMapperBeanPostProcessor( ObjectProvider<org.springframework.boot.actuate.endpoint.jackson.EndpointJackson2ObjectMapper> endpointJsonMapper) { return new ServerCodecConfigurerEndpointJackson2JsonMapperBeanPostProcessor( SingletonSupplier.of(endpointJsonMapper::getObject)); } /** * {@link BeanPostProcessor} to apply {@link EndpointJsonMapper} for * {@link OperationResponseBody} to {@link JacksonJsonEncoder} instances. */ static
WebFluxEndpointManagementContextConfiguration
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/pool/PSCacheTest1.java
{ "start": 906, "end": 3460 }
class ____ extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mock:x1"); dataSource.setPoolPreparedStatements(true); dataSource.setMaxOpenPreparedStatements(10); } protected void tearDown() throws Exception { JdbcUtils.close(dataSource); } public void test_noTxn() throws Exception { { Connection conn = dataSource.getConnection(); String sql = "select 1"; PreparedStatement stmt0 = conn.prepareStatement(sql); DruidPooledPreparedStatement pooledStmt0 = (DruidPooledPreparedStatement) stmt0; stmt0.close(); PreparedStatement stmt1 = conn.prepareStatement(sql); DruidPooledPreparedStatement pooledStmt1 = (DruidPooledPreparedStatement) stmt1; assertEquals(1, pooledStmt1.getPreparedStatementHolder().getInUseCount()); assertSame(pooledStmt1.getPreparedStatementHolder(), pooledStmt0.getPreparedStatementHolder()); // same PreparedStatement stmt2 = conn.prepareStatement(sql); DruidPooledPreparedStatement pooledStmt2 = (DruidPooledPreparedStatement) stmt2; assertNotSame(pooledStmt1.getPreparedStatementHolder(), pooledStmt2.getPreparedStatementHolder()); // not // same conn.close(); } { Connection conn = dataSource.getConnection(); conn.setAutoCommit(false); String sql = "select 1"; PreparedStatement stmt0 = conn.prepareStatement(sql); DruidPooledPreparedStatement pooledStmt0 = (DruidPooledPreparedStatement) stmt0; stmt0.close(); PreparedStatement stmt1 = conn.prepareStatement(sql); DruidPooledPreparedStatement pooledStmt1 = (DruidPooledPreparedStatement) stmt1; assertEquals(1, pooledStmt1.getPreparedStatementHolder().getInUseCount()); assertSame(pooledStmt1.getPreparedStatementHolder(), pooledStmt0.getPreparedStatementHolder()); // same PreparedStatement stmt2 = conn.prepareStatement(sql); DruidPooledPreparedStatement pooledStmt2 = (DruidPooledPreparedStatement) stmt2; assertNotSame(pooledStmt1.getPreparedStatementHolder(), pooledStmt2.getPreparedStatementHolder()); // not // same stmt1.close(); stmt2.close(); conn.close(); } } }
PSCacheTest1
java
spring-projects__spring-boot
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java
{ "start": 2049, "end": 6989 }
class ____ implements TreeVisitor { private static final Map<String, Class<?>> WRAPPER_TYPES; static { Map<String, Class<?>> types = new HashMap<>(); types.put("boolean", Boolean.class); types.put(Boolean.class.getName(), Boolean.class); types.put("byte", Byte.class); types.put(Byte.class.getName(), Byte.class); types.put("short", Short.class); types.put(Short.class.getName(), Short.class); types.put("int", Integer.class); types.put(Integer.class.getName(), Integer.class); types.put("long", Long.class); types.put(Long.class.getName(), Long.class); WRAPPER_TYPES = Collections.unmodifiableMap(types); } private static final Map<Class<?>, Object> DEFAULT_TYPE_VALUES; static { Map<Class<?>, Object> values = new HashMap<>(); values.put(Boolean.class, false); values.put(Byte.class, (byte) 0); values.put(Short.class, (short) 0); values.put(Integer.class, 0); values.put(Long.class, (long) 0); DEFAULT_TYPE_VALUES = Collections.unmodifiableMap(values); } private static final Map<String, Object> WELL_KNOWN_STATIC_FINALS; static { Map<String, Object> values = new HashMap<>(); values.put("Boolean.TRUE", true); values.put("Boolean.FALSE", false); values.put("StandardCharsets.ISO_8859_1", "ISO-8859-1"); values.put("StandardCharsets.UTF_8", "UTF-8"); values.put("StandardCharsets.UTF_16", "UTF-16"); values.put("StandardCharsets.US_ASCII", "US-ASCII"); values.put("Duration.ZERO", 0); values.put("Period.ZERO", 0); WELL_KNOWN_STATIC_FINALS = Collections.unmodifiableMap(values); } private static final String DURATION_OF = "Duration.of"; private static final Map<String, String> DURATION_SUFFIX; static { Map<String, String> values = new HashMap<>(); values.put("Nanos", "ns"); values.put("Millis", "ms"); values.put("Seconds", "s"); values.put("Minutes", "m"); values.put("Hours", "h"); values.put("Days", "d"); DURATION_SUFFIX = Collections.unmodifiableMap(values); } private static final String PERIOD_OF = "Period.of"; private static final Map<String, String> PERIOD_SUFFIX; static { Map<String, String> values = new HashMap<>(); values.put("Days", "d"); values.put("Weeks", "w"); values.put("Months", "m"); values.put("Years", "y"); PERIOD_SUFFIX = Collections.unmodifiableMap(values); } private static final String DATA_SIZE_OF = "DataSize.of"; private static final Map<String, String> DATA_SIZE_SUFFIX; static { Map<String, String> values = new HashMap<>(); values.put("Bytes", "B"); values.put("Kilobytes", "KB"); values.put("Megabytes", "MB"); values.put("Gigabytes", "GB"); values.put("Terabytes", "TB"); DATA_SIZE_SUFFIX = Collections.unmodifiableMap(values); } private final Map<String, Object> fieldValues = new HashMap<>(); private final Map<String, Object> staticFinals = new HashMap<>(); @Override public void visitVariable(VariableTree variable) throws Exception { Set<Modifier> flags = variable.getModifierFlags(); if (flags.contains(Modifier.STATIC) && flags.contains(Modifier.FINAL)) { this.staticFinals.put(variable.getName(), getValue(variable)); } if (!flags.contains(Modifier.FINAL)) { this.fieldValues.put(variable.getName(), getValue(variable)); } } private Object getValue(VariableTree variable) throws Exception { ExpressionTree initializer = variable.getInitializer(); Class<?> wrapperType = WRAPPER_TYPES.get(variable.getType()); Object defaultValue = DEFAULT_TYPE_VALUES.get(wrapperType); if (initializer != null) { return getValue(variable.getType(), initializer, defaultValue); } return defaultValue; } private Object getValue(String variableType, ExpressionTree expression, Object defaultValue) throws Exception { Object literalValue = expression.getLiteralValue(); if (literalValue != null) { return literalValue; } Object factoryValue = expression.getFactoryValue(); if (factoryValue != null) { return getFactoryValue(expression, factoryValue); } List<? extends ExpressionTree> arrayValues = expression.getArrayExpression(); if (arrayValues != null) { Object[] result = new Object[arrayValues.size()]; for (int i = 0; i < arrayValues.size(); i++) { Object value = getValue(variableType, arrayValues.get(i), null); if (value == null) { // One of the elements could not be resolved return defaultValue; } result[i] = value; } return result; } if (expression.getKind().equals("IDENTIFIER")) { return this.staticFinals.get(expression.toString()); } if (expression.getKind().equals("MEMBER_SELECT")) { Object value = WELL_KNOWN_STATIC_FINALS.get(expression.toString()); if (value != null) { return value; } Member selectedMember = expression.getSelectedMember(); // Type matching the expression, assuming an
FieldCollector
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java
{ "start": 78843, "end": 79458 }
class ____ implements SingleArcTransition<ContainerImpl, ContainerEvent> { @SuppressWarnings("unchecked") @Override public void transition(ContainerImpl container, ContainerEvent event) { // Kill the process/process-grp container.setIsReInitializing(false); container.dispatcher.getEventHandler().handle( new ContainersLauncherEvent(container, ContainersLauncherEventType.CLEANUP_CONTAINER)); } } /** * Transition from KILLING to CONTAINER_CLEANEDUP_AFTER_KILL * upon receiving CONTAINER_KILLED_ON_REQUEST. */ static
KillOnPauseTransition
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/OneToOneMapsIdTest.java
{ "start": 1743, "end": 2133 }
class ____ { @Id private Long id; private String nickName; @OneToOne @MapsId private Person person; public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } } }
PersonDetails
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Country.java
{ "start": 273, "end": 841 }
class ____ implements Serializable { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } Country country = (Country) o; if ( name != null ? !name.equals( country.name ) : country.name != null ) { return false; } return true; } @Override public int hashCode() { return name != null ? name.hashCode() : 0; } }
Country
java
apache__camel
components/camel-sql/src/main/java/org/apache/camel/component/sql/stored/CallableStatementWrapperFactory.java
{ "start": 1147, "end": 1196 }
class ____ cached template functions. */ public
that
java
quarkusio__quarkus
extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CodeFlowRuntimeCredentialsProviderTest.java
{ "start": 1141, "end": 3311 }
class ____ { private static final Class<?>[] TEST_CLASSES = { ProtectedResource.class, RuntimeSecretProvider.class, CodeFlowRuntimeCredentialsProviderTest.class, TestRecorder.class }; @RegisterExtension static final QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(TEST_CLASSES) .addAsResource("application-runtime-cred-provider.properties", "application.properties")) .addBuildChainCustomizer(buildCustomizer()); @Test public void testRuntimeCredentials() throws IOException, InterruptedException { try (final WebClient webClient = createWebClient()) { HtmlPage page = webClient.getPage("http://localhost:8081/protected"); assertEquals("Sign in to quarkus", page.getTitleText()); HtmlForm loginForm = page.getForms().get(0); loginForm.getInputByName("username").setValueAttribute("alice"); loginForm.getInputByName("password").setValueAttribute("alice"); page = loginForm.getButtonByName("login").click(); assertEquals("alice", page.getBody().asNormalizedText()); } } private static Consumer<BuildChainBuilder> buildCustomizer() { // whole purpose of this step is to have a bean recorded during runtime init return new Consumer<BuildChainBuilder>() { @Override public void accept(BuildChainBuilder builder) { builder.addBuildStep(new BuildStep() { @Override public void execute(BuildContext context) { BytecodeRecorderImpl bytecodeRecorder = new BytecodeRecorderImpl(false, TestRecorder.class.getSimpleName(), "createRuntimeSecretProvider", "" + TestRecorder.class.hashCode(), true, s -> null); context.produce(new MainBytecodeRecorderBuildItem(bytecodeRecorder)); // We need to use reflection due to some
CodeFlowRuntimeCredentialsProviderTest
java
google__dagger
javatests/dagger/internal/codegen/ComponentHierarchyValidationTest.java
{ "start": 7081, "end": 7351 }
class ____ {", "}"); Source subcomponent = CompilerTests.javaSource( "test.Sub", "package test;", "", "import dagger.Subcomponent;", "", "@Subcomponent", "
TestModule
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/shortcircuit/DomainSocketFactory.java
{ "start": 2383, "end": 6705 }
class ____ { private final static PathInfo NOT_CONFIGURED = new PathInfo("", PathState.UNUSABLE); final private String path; final private PathState state; PathInfo(String path, PathState state) { this.path = path; this.state = state; } public String getPath() { return path; } public PathState getPathState() { return state; } @Override public String toString() { return "PathInfo{path=" + path + ", state=" + state + "}"; } } /** * Information about domain socket paths. */ private final long pathExpireSeconds; private final Cache<String, PathState> pathMap; public DomainSocketFactory(ShortCircuitConf conf) { final String feature; if (conf.isShortCircuitLocalReads() && (!conf.isUseLegacyBlockReaderLocal())) { feature = "The short-circuit local reads feature"; } else if (conf.isDomainSocketDataTraffic()) { feature = "UNIX domain socket data traffic"; } else { feature = null; } if (feature == null) { PerformanceAdvisory.LOG.debug( "Both short-circuit local reads and UNIX domain socket are disabled."); } else { if (conf.getDomainSocketPath().isEmpty()) { throw new HadoopIllegalArgumentException(feature + " is enabled but " + HdfsClientConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY + " is not set."); } else if (DomainSocket.getLoadingFailureReason() != null) { LOG.warn(feature + " cannot be used because " + DomainSocket.getLoadingFailureReason()); } else { LOG.debug(feature + " is enabled."); } } pathExpireSeconds = conf.getDomainSocketDisableIntervalSeconds(); pathMap = CacheBuilder.newBuilder() .expireAfterWrite(pathExpireSeconds, TimeUnit.SECONDS).build(); } /** * Get information about a domain socket path. * * @param addr The inet address to use. * @param conf The client configuration. * * @return Information about the socket path. */ public PathInfo getPathInfo(InetSocketAddress addr, ShortCircuitConf conf) throws IOException { // If there is no domain socket path configured, we can't use domain // sockets. if (conf.getDomainSocketPath().isEmpty()) return PathInfo.NOT_CONFIGURED; // If we can't do anything with the domain socket, don't create it. if (!conf.isDomainSocketDataTraffic() && (!conf.isShortCircuitLocalReads() || conf.isUseLegacyBlockReaderLocal())) { return PathInfo.NOT_CONFIGURED; } // If the DomainSocket code is not loaded, we can't create // DomainSocket objects. if (DomainSocket.getLoadingFailureReason() != null) { return PathInfo.NOT_CONFIGURED; } // UNIX domain sockets can only be used to talk to local peers if (!DFSUtilClient.isLocalAddress(addr)) return PathInfo.NOT_CONFIGURED; String escapedPath = DomainSocket.getEffectivePath( conf.getDomainSocketPath(), addr.getPort()); PathState status = pathMap.getIfPresent(escapedPath); if (status == null) { return new PathInfo(escapedPath, PathState.VALID); } else { return new PathInfo(escapedPath, status); } } public DomainSocket createSocket(PathInfo info, int socketTimeout) { Preconditions.checkArgument(info.getPathState() != PathState.UNUSABLE); boolean success = false; DomainSocket sock = null; try { sock = DomainSocket.connect(info.getPath()); sock.setAttribute(DomainSocket.RECEIVE_TIMEOUT, socketTimeout); success = true; } catch (IOException e) { LOG.warn("error creating DomainSocket", e); // fall through } finally { if (!success) { if (sock != null) { IOUtils.closeStream(sock); } pathMap.put(info.getPath(), PathState.UNUSABLE); sock = null; } } return sock; } public void disableShortCircuitForPath(String path) { pathMap.put(path, PathState.SHORT_CIRCUIT_DISABLED); } public void disableDomainSocketPath(String path) { pathMap.put(path, PathState.UNUSABLE); } @VisibleForTesting public void clearPathMap() { pathMap.invalidateAll(); } public long getPathExpireSeconds() { return pathExpireSeconds; } }
PathInfo
java
apache__camel
components/camel-dhis2/camel-dhis2-component/src/generated/java/org/apache/camel/component/dhis2/Dhis2EndpointUriFactory.java
{ "start": 515, "end": 3878 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":apiName/methodName"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(41); props.add("apiName"); props.add("arrayName"); props.add("async"); props.add("backoffErrorThreshold"); props.add("backoffIdleThreshold"); props.add("backoffMultiplier"); props.add("baseApiUrl"); props.add("bridgeErrorHandler"); props.add("client"); props.add("delay"); props.add("exceptionHandler"); props.add("exchangePattern"); props.add("fields"); props.add("filter"); props.add("greedy"); props.add("inBody"); props.add("initialDelay"); props.add("interval"); props.add("lastYears"); props.add("lazyStartProducer"); props.add("methodName"); props.add("paging"); props.add("password"); props.add("path"); props.add("personalAccessToken"); props.add("pollStrategy"); props.add("queryParams"); props.add("repeatCount"); props.add("resource"); props.add("rootJunction"); props.add("runLoggingLevel"); props.add("scheduledExecutorService"); props.add("scheduler"); props.add("schedulerProperties"); props.add("sendEmptyMessageWhenIdle"); props.add("skipAggregate"); props.add("skipEvents"); props.add("startScheduler"); props.add("timeUnit"); props.add("useFixedDelay"); props.add("username"); PROPERTY_NAMES = Collections.unmodifiableSet(props); Set<String> secretProps = new HashSet<>(3); secretProps.add("password"); secretProps.add("personalAccessToken"); secretProps.add("username"); SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps); Map<String, String> prefixes = new HashMap<>(1); prefixes.put("schedulerProperties", "scheduler."); MULTI_VALUE_PREFIXES = Collections.unmodifiableMap(prefixes); } @Override public boolean isEnabled(String scheme) { return "dhis2".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "apiName", null, true, copy); uri = buildPathParameter(syntax, uri, "methodName", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
Dhis2EndpointUriFactory
java
apache__avro
lang/java/protobuf/src/main/java/org/apache/avro/protobuf/ProtoConversions.java
{ "start": 1709, "end": 2530 }
class ____ extends Conversion<Timestamp> { @Override public Class<Timestamp> getConvertedType() { return Timestamp.class; } @Override public String getLogicalTypeName() { return "timestamp-millis"; } @Override public Timestamp fromLong(Long millisFromEpoch, Schema schema, LogicalType type) throws IllegalArgumentException { return ProtoConversions.fromLong(millisFromEpoch, TimestampPrecise.Millis); } @Override public Long toLong(Timestamp value, Schema schema, LogicalType type) { return ProtoConversions.toLong(value, TimestampPrecise.Millis); } @Override public Schema getRecommendedSchema() { return LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG)); } } public static
TimestampMillisConversion
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/View.java
{ "start": 1538, "end": 1675 }
class ____ implements Params { public static final Logger LOG = LoggerFactory.getLogger(View.class); @RequestScoped public static
View
java
spring-projects__spring-boot
system-test/spring-boot-image-system-tests/src/systemTest/java/org/springframework/boot/image/assertions/ContainerConfigAssert.java
{ "start": 1369, "end": 2783 }
class ____ extends AbstractAssert<ContainerConfigAssert, ContainerConfig> { private static final String BUILD_METADATA_LABEL = "io.buildpacks.build.metadata"; private static final String LIFECYCLE_METADATA_LABEL = "io.buildpacks.lifecycle.metadata"; ContainerConfigAssert(ContainerConfig containerConfig) { super(containerConfig, ContainerConfigAssert.class); } public void buildMetadata(Consumer<BuildMetadataAssert> assertConsumer) { assertConsumer.accept(new BuildMetadataAssert(jsonLabel(BUILD_METADATA_LABEL))); } public void lifecycleMetadata(Consumer<LifecycleMetadataAssert> assertConsumer) { assertConsumer.accept(new LifecycleMetadataAssert(jsonLabel(LIFECYCLE_METADATA_LABEL))); } public void labels(Consumer<LabelsAssert> assertConsumer) { assertConsumer.accept(new LabelsAssert(this.actual.getLabels())); } private JsonContentAssert jsonLabel(String label) { return new JsonContentAssert(ContainerConfigAssert.class, getLabel(label)); } private String getLabel(String label) { Map<String, String> labels = this.actual.getLabels(); if (labels == null) { failWithMessage("Container config contains no labels"); } if (!labels.containsKey(label)) { failWithActualExpectedAndMessage(labels, label, "Expected label not found in container config"); } return labels.get(label); } /** * Asserts for labels on an image. */ public static
ContainerConfigAssert
java
google__dagger
javatests/dagger/hilt/android/EarlyEntryPointHiltAndroidTestRuntimeClasses.java
{ "start": 2061, "end": 2322 }
interface ____ { @BindsInstance Builder id(int id); MySubcomponent build(); } } // This needs to be defined outside the test so that it gets installed in the early component. @EntryPoint @InstallIn(SingletonComponent.class)
Builder
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/configproperties/MyPrimitiveConfig.java
{ "start": 757, "end": 1187 }
class ____ { int port; int primitiveDefaultValue = 9999; public int getPort() { return port; } public void setPort(int port) { this.port = port; } public int getPrimitiveDefaultValue() { return primitiveDefaultValue; } public void setPrimitiveDefaultValue(int primitiveDefaultValue) { this.primitiveDefaultValue = primitiveDefaultValue; } }
MyPrimitiveConfig
java
apache__flink
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/PredefinedOptions.java
{ "start": 2302, "end": 7895 }
enum ____ { /** * Default options for all settings. * * <p>There are no specified options here. */ DEFAULT(Collections.emptyMap()), /** * Pre-defined options for regular spinning hard disks. * * <p>This constant configures RocksDB with some options that lead empirically to better * performance when the machines executing the system use regular spinning hard disks. * * <p>The following options are set: * * <ul> * <li>setCompactionStyle(CompactionStyle.LEVEL) * <li>setLevelCompactionDynamicLevelBytes(true) * <li>setMaxBackgroundJobs(4) * <li>setMaxOpenFiles(-1) * </ul> */ SPINNING_DISK_OPTIMIZED( new HashMap<ConfigOption<?>, Object>() { private static final long serialVersionUID = 1L; { put(RocksDBConfigurableOptions.COMPACTION_STYLE, CompactionStyle.LEVEL); put(RocksDBConfigurableOptions.USE_DYNAMIC_LEVEL_SIZE, true); put(RocksDBConfigurableOptions.MAX_BACKGROUND_THREADS, 4); put(RocksDBConfigurableOptions.MAX_OPEN_FILES, -1); } }), /** * Pre-defined options for better performance on regular spinning hard disks, at the cost of a * higher memory consumption. * * <p><b>NOTE: These settings will cause RocksDB to consume a lot of memory for block caching * and compactions. If you experience out-of-memory problems related to, RocksDB, consider * switching back to {@link #SPINNING_DISK_OPTIMIZED}.</b> * * <p>The following options are set: * * <ul> * <li>BlockBasedTableConfig.setBlockCacheSize(256 MBytes) * <li>BlockBasedTableConfig.setBlockSize(128 KBytes) * <li>BlockBasedTableConfig.setFilterPolicy(BloomFilter( {@link * RocksDBConfigurableOptions#BLOOM_FILTER_BITS_PER_KEY}, {@link * RocksDBConfigurableOptions#BLOOM_FILTER_BLOCK_BASED_MODE}) * <li>setLevelCompactionDynamicLevelBytes(true) * <li>setMaxBackgroundJobs(4) * <li>setMaxBytesForLevelBase(1 GByte) * <li>setMaxOpenFiles(-1) * <li>setMaxWriteBufferNumber(4) * <li>setMinWriteBufferNumberToMerge(3) * <li>setTargetFileSizeBase(256 MBytes) * <li>setWriteBufferSize(64 MBytes) * </ul> * * <p>Enabling use of a Bloom filter here is equivalent to setting {@link * RocksDBConfigurableOptions#USE_BLOOM_FILTER}. */ SPINNING_DISK_OPTIMIZED_HIGH_MEM( new HashMap<ConfigOption<?>, Object>() { private static final long serialVersionUID = 1L; { put(RocksDBConfigurableOptions.BLOCK_CACHE_SIZE, MemorySize.parse("256mb")); put(RocksDBConfigurableOptions.BLOCK_SIZE, MemorySize.parse("128kb")); put(RocksDBConfigurableOptions.USE_DYNAMIC_LEVEL_SIZE, true); put(RocksDBConfigurableOptions.MAX_BACKGROUND_THREADS, 4); put(RocksDBConfigurableOptions.MAX_SIZE_LEVEL_BASE, MemorySize.parse("1gb")); put(RocksDBConfigurableOptions.MAX_OPEN_FILES, -1); put(RocksDBConfigurableOptions.MAX_WRITE_BUFFER_NUMBER, 4); put(RocksDBConfigurableOptions.MIN_WRITE_BUFFER_NUMBER_TO_MERGE, 3); put( RocksDBConfigurableOptions.TARGET_FILE_SIZE_BASE, MemorySize.parse("256mb")); put(RocksDBConfigurableOptions.WRITE_BUFFER_SIZE, MemorySize.parse("64mb")); put(RocksDBConfigurableOptions.USE_BLOOM_FILTER, true); } }), /** * Pre-defined options for Flash SSDs. * * <p>This constant configures RocksDB with some options that lead empirically to better * performance when the machines executing the system use SSDs. * * <p>The following options are set: * * <ul> * <li>setMaxBackgroundJobs(4) * <li>setMaxOpenFiles(-1) * </ul> */ FLASH_SSD_OPTIMIZED( new HashMap<ConfigOption<?>, Object>() { private static final long serialVersionUID = 1L; { put(RocksDBConfigurableOptions.MAX_BACKGROUND_THREADS, 4); put(RocksDBConfigurableOptions.MAX_OPEN_FILES, -1); } }); // ------------------------------------------------------------------------ /** Settings kept in this pre-defined options. */ private final Map<String, Object> options; PredefinedOptions(Map<ConfigOption<?>, Object> initMap) { options = CollectionUtil.newHashMapWithExpectedSize(initMap.size()); for (Map.Entry<ConfigOption<?>, Object> entry : initMap.entrySet()) { options.put(entry.getKey().key(), entry.getValue()); } } /** * Get a option value according to the pre-defined values. If not defined, return the default * value. * * @param option the option. * @param <T> the option value type. * @return the value if defined, otherwise return the default value. */ @Nullable @SuppressWarnings("unchecked") <T> T getValue(ConfigOption<T> option) { Object value = options.get(option.key()); if (value == null) { value = option.defaultValue(); } if (value == null) { return null; } return (T) value; } }
PredefinedOptions
java
apache__camel
components/camel-rxjava/src/test/java/org/apache/camel/component/rxjava/engine/RxJavaStreamsServiceEventTypeTest.java
{ "start": 1238, "end": 5554 }
class ____ extends RxJavaStreamsServiceTestSupport { @Test public void testOnCompleteHeaderForwarded() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("reactive-streams:numbers?forwardOnComplete=true") .to("mock:endpoint"); } }); Subscriber<Integer> numbers = crs.streamSubscriber("numbers", Integer.class); context.start(); Flowable.<Integer> empty().subscribe(numbers); MockEndpoint endpoint = getMockEndpoint("mock:endpoint"); endpoint.expectedMessageCount(1); endpoint.expectedHeaderReceived(ReactiveStreamsConstants.REACTIVE_STREAMS_EVENT_TYPE, "onComplete"); endpoint.expectedBodiesReceived(new Object[] { null }); endpoint.assertIsSatisfied(); } @Test public void testOnCompleteHeaderNotForwarded() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("reactive-streams:numbers") .to("mock:endpoint"); } }); Subscriber<Integer> numbers = crs.streamSubscriber("numbers", Integer.class); context.start(); Flowable.<Integer> empty().subscribe(numbers); MockEndpoint endpoint = getMockEndpoint("mock:endpoint"); endpoint.expectedMessageCount(0); endpoint.assertIsSatisfied(200); } @Test public void testOnNextHeaderForwarded() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("reactive-streams:numbers") .to("mock:endpoint"); } }); Subscriber<Integer> numbers = crs.streamSubscriber("numbers", Integer.class); context.start(); Flowable.just(1).subscribe(numbers); MockEndpoint endpoint = getMockEndpoint("mock:endpoint"); endpoint.expectedHeaderReceived(ReactiveStreamsConstants.REACTIVE_STREAMS_EVENT_TYPE, "onNext"); endpoint.expectedMessageCount(1); endpoint.assertIsSatisfied(); Exchange ex = endpoint.getExchanges().get(0); assertEquals(1, ex.getIn().getBody()); } @Test public void testOnErrorHeaderForwarded() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("reactive-streams:numbers?forwardOnError=true") .to("mock:endpoint"); } }); Subscriber<Integer> numbers = crs.streamSubscriber("numbers", Integer.class); context.start(); RuntimeException ex = new RuntimeException("1"); Flowable.just(1) .map(n -> { if (n == 1) { throw ex; } return n; }) .subscribe(numbers); MockEndpoint endpoint = getMockEndpoint("mock:endpoint"); endpoint.expectedMessageCount(1); endpoint.expectedHeaderReceived(ReactiveStreamsConstants.REACTIVE_STREAMS_EVENT_TYPE, "onError"); endpoint.assertIsSatisfied(); Exchange exch = endpoint.getExchanges().get(0); assertEquals(ex, exch.getIn().getBody()); } @Test public void testOnErrorHeaderNotForwarded() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("reactive-streams:numbers") .to("mock:endpoint"); } }); Subscriber<Integer> numbers = crs.streamSubscriber("numbers", Integer.class); context.start(); RuntimeException ex = new RuntimeException("1"); Flowable.just(1) .map(n -> { if (n == 1) { throw ex; } return n; }) .subscribe(numbers); MockEndpoint endpoint = getMockEndpoint("mock:endpoint"); endpoint.expectedMessageCount(0); endpoint.assertIsSatisfied(200); } }
RxJavaStreamsServiceEventTypeTest
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/data/conversion/ArrayListConverter.java
{ "start": 1316, "end": 3181 }
class ____<E> implements DataStructureConverter<ArrayData, List<E>> { private static final long serialVersionUID = 1L; private final E[] arrayKind; private final ArrayObjectArrayConverter<E> elementsConverter; private ArrayListConverter(E[] arrayKind, ArrayObjectArrayConverter<E> elementsConverter) { this.arrayKind = arrayKind; this.elementsConverter = elementsConverter; } @Override public void open(ClassLoader classLoader) { elementsConverter.open(classLoader); } @Override public ArrayData toInternal(List<E> external) { return elementsConverter.toInternal(external.toArray(arrayKind)); } @Override public List<E> toExternal(ArrayData internal) { return new ArrayList<>(Arrays.asList(elementsConverter.toExternal(internal))); } // -------------------------------------------------------------------------------------------- // Factory method // -------------------------------------------------------------------------------------------- public static ArrayListConverter<?> create(DataType dataType) { final DataType elementDataType = dataType.getChildren().get(0); return new ArrayListConverter<>( createObjectArrayKind(elementDataType.getConversionClass()), ArrayObjectArrayConverter.createForElement(elementDataType)); } /** Creates the kind of array for {@link List#toArray(Object[])}. */ private static Object[] createObjectArrayKind(Class<?> elementClazz) { // e.g. int[] is not a Object[] if (elementClazz.isPrimitive()) { return (Object[]) Array.newInstance(primitiveToWrapper(elementClazz), 0); } // e.g. int[][] and Integer[] are Object[] return (Object[]) Array.newInstance(elementClazz, 0); } }
ArrayListConverter
java
hibernate__hibernate-orm
hibernate-graalvm/src/test/java/org/hibernate/graalvm/internal/StaticClassListsTest.java
{ "start": 6044, "end": 6795 }
class ____ { @ParameterizedTest @EnumSource(TypesNeedingArrayCopy_Category.class) void containsAllExpectedClasses(TypesNeedingArrayCopy_Category category) { assertThat( StaticClassLists.typesNeedingArrayCopy() ) .containsAll( category.classes().collect( Collectors.toSet() ) ); } @Test void meta_noMissingTestCategory() { assertThat( Arrays.stream( TypesNeedingArrayCopy_Category.values() ).flatMap( TypesNeedingArrayCopy_Category::classes ) ) .as( "If this fails, a category is missing in " + TypesNeedingArrayCopy_Category.class ) .contains( StaticClassLists.typesNeedingArrayCopy() ); } } // TODO ORM 7: Move this inside TypesNeedingArrayCopy (requires JDK 17) and rename to simple Category
TypesNeedingArrayCopy
java
elastic__elasticsearch
x-pack/plugin/ilm/src/main/java/org/elasticsearch/xpack/ilm/history/ILMHistoryStore.java
{ "start": 2382, "end": 10005 }
class ____ implements Closeable { private static final Logger logger = LogManager.getLogger(ILMHistoryStore.class); public static final Setting<ByteSizeValue> MAX_BULK_REQUEST_BYTE_IN_FLIGHT_SETTING = Setting.byteSizeSetting( "es.indices.lifecycle.history.bulk.request.bytes.in.flight", ByteSizeValue.ofMb(100), Setting.Property.NodeScope ); public static final String ILM_HISTORY_DATA_STREAM = "ilm-history-" + INDEX_TEMPLATE_VERSION; private static final int ILM_HISTORY_BULK_SIZE = StrictMath.toIntExact( ByteSizeValue.parseBytesSizeValue( System.getProperty("es.indices.lifecycle.history.bulk.size", "50MB"), "es.indices.lifecycle.history.bulk.size" ).getBytes() ); private volatile boolean ilmHistoryEnabled = true; private final ProjectResolver projectResolver; private final BulkProcessor2 processor; public ILMHistoryStore(Client client, ClusterService clusterService, ThreadPool threadPool, ProjectResolver projectResolver) { this(client, clusterService, threadPool, projectResolver, ActionListener.noop(), TimeValue.timeValueSeconds(5)); } /** * For unit testing, allows a more frequent flushInterval */ ILMHistoryStore( Client client, ClusterService clusterService, ThreadPool threadPool, ProjectResolver projectResolver, ActionListener<BulkResponse> listener, TimeValue flushInterval ) { this.projectResolver = projectResolver; this.setIlmHistoryEnabled(LIFECYCLE_HISTORY_INDEX_ENABLED_SETTING.get(clusterService.getSettings())); clusterService.getClusterSettings().addSettingsUpdateConsumer(LIFECYCLE_HISTORY_INDEX_ENABLED_SETTING, this::setIlmHistoryEnabled); this.processor = BulkProcessor2.builder( new OriginSettingClient(client, INDEX_LIFECYCLE_ORIGIN)::bulk, new BulkProcessor2.Listener() { @Override public void beforeBulk(long executionId, BulkRequest request) { final var project = projectResolver.getProjectMetadata(clusterService.state()); if (project.templatesV2().containsKey(ILM_TEMPLATE_NAME) == false) { ElasticsearchException e = new ElasticsearchException("no ILM history template"); logger.warn( () -> format( "unable to index the following ILM history items:\n%s", request.requests() .stream() .filter(dwr -> (dwr instanceof IndexRequest)) .map(dwr -> ((IndexRequest) dwr)) .map(IndexRequest::sourceAsMap) .map(Object::toString) .collect(joining("\n")) ), e ); throw new ElasticsearchException(e); } if (logger.isTraceEnabled()) { logger.info( "about to index: {}", request.requests() .stream() .map(dwr -> ((IndexRequest) dwr).sourceAsMap()) .map(Objects::toString) .collect(Collectors.joining(",")) ); } } @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { long items = request.numberOfActions(); if (logger.isTraceEnabled()) { logger.trace( "indexed [{}] items into ILM history index [{}]", items, Arrays.stream(response.getItems()).map(BulkItemResponse::getIndex).distinct().collect(Collectors.joining(",")) ); } if (response.hasFailures()) { Map<String, String> failures = Arrays.stream(response.getItems()) .filter(BulkItemResponse::isFailed) .collect( Collectors.toMap( BulkItemResponse::getId, BulkItemResponse::getFailureMessage, (msg1, msg2) -> Objects.equals(msg1, msg2) ? msg1 : msg1 + "," + msg2 ) ); logger.error("failures: [{}]", failures); } listener.onResponse(response); } @Override public void afterBulk(long executionId, BulkRequest request, Exception failure) { long items = request.numberOfActions(); logger.error(() -> "failed to index " + items + " items into ILM history index", failure); listener.onFailure(failure); } }, threadPool ) .setBulkActions(-1) .setBulkSize(ByteSizeValue.ofBytes(ILM_HISTORY_BULK_SIZE)) .setFlushInterval(flushInterval) .setMaxBytesInFlight(MAX_BULK_REQUEST_BYTE_IN_FLIGHT_SETTING.get(clusterService.getSettings())) .setMaxNumberOfRetries(3) .build(); } /** * Attempts to asynchronously index an ILM history entry */ @NotMultiProjectCapable(description = "See comment inside method") public void putAsync(ProjectId projectId, ILMHistoryItem item) { if (ilmHistoryEnabled == false) { logger.trace( "not recording ILM history item because [{}] is [false]: [{}]", LIFECYCLE_HISTORY_INDEX_ENABLED_SETTING.getKey(), item ); return; } logger.trace("queueing ILM history item for indexing [{}]: [{}]", ILM_HISTORY_DATA_STREAM, item); try (XContentBuilder builder = XContentFactory.jsonBuilder()) { item.toXContent(builder, ToXContent.EMPTY_PARAMS); IndexRequest request = new IndexRequest(ILM_HISTORY_DATA_STREAM).source(builder).opType(DocWriteRequest.OpType.CREATE); // Even though this looks project-aware, it's not really. The bulk processor flushes the history items at "arbitrary" moments, // meaning it will send bulk requests with history items of multiple projects, but the _bulk API will index everything into // the project of the last history item that came in. projectResolver.executeOnProject(projectId, () -> processor.add(request)); } catch (Exception e) { logger.error(() -> format("failed to send ILM history item to index [%s]: [%s]", ILM_HISTORY_DATA_STREAM, item), e); } } @Override public void close() { try { processor.awaitClose(10, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.warn("failed to shut down ILM history bulk processor after 10 seconds", e); Thread.currentThread().interrupt(); } } public void setIlmHistoryEnabled(boolean ilmHistoryEnabled) { this.ilmHistoryEnabled = ilmHistoryEnabled; } }
ILMHistoryStore
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryFileManager.java
{ "start": 3513, "end": 3658 }
class ____ a way to interact with history files in a thread safe * manor. */ @InterfaceAudience.Public @InterfaceStability.Unstable public
provides
java
alibaba__nacos
core/src/test/java/com/alibaba/nacos/core/service/NacosClusterOperationServiceTest.java
{ "start": 1717, "end": 4983 }
class ____ { @Mock private final MockEnvironment environment = new MockEnvironment(); private NacosClusterOperationService nacosClusterOperationService; @Mock private ServerMemberManager serverMemberManager; @BeforeEach void setUp() throws Exception { this.nacosClusterOperationService = new NacosClusterOperationService(serverMemberManager); EnvUtil.setEnvironment(environment); } @Test void testSelf() { Member member = new Member(); member.setIp("1.1.1.1"); member.setPort(8848); member.setState(NodeState.UP); when(serverMemberManager.getSelf()).thenReturn(member); Member result = nacosClusterOperationService.self(); assertEquals("1.1.1.1:8848", result.getAddress()); } @Test void testListNodes() throws NacosException { Member member1 = new Member(); member1.setIp("1.1.1.1"); member1.setPort(8848); member1.setState(NodeState.DOWN); Member member2 = new Member(); member2.setIp("2.2.2.2"); member2.setPort(8848); List<Member> members = Arrays.asList(member1, member2); when(serverMemberManager.allMembers()).thenReturn(members); Collection<Member> result1 = nacosClusterOperationService.listNodes("1.1.1.1", null); assertTrue(result1.stream().findFirst().isPresent()); assertEquals("1.1.1.1:8848", result1.stream().findFirst().get().getAddress()); Collection<Member> result2 = nacosClusterOperationService.listNodes(null, NodeState.UP); assertTrue(result2.stream().findFirst().isPresent()); assertEquals("2.2.2.2:8848", result2.stream().findFirst().get().getAddress()); } @Test void testSelfHealth() { Member member = new Member(); member.setIp("1.1.1.1"); member.setPort(8848); member.setState(NodeState.UP); when(serverMemberManager.getSelf()).thenReturn(member); String health = nacosClusterOperationService.selfHealth(); assertEquals(NodeState.UP.name(), health); } @Test void testUpdateNodes() { Member member1 = new Member(); member1.setIp("1.1.1.1"); member1.setAddress("test"); member1.setPort(8848); member1.setState(NodeState.DOWN); Member member2 = new Member(); member2.setIp("2.2.2.2"); member2.setPort(8848); member2.setAddress(null); List<Member> members = Arrays.asList(member1, member2); when(serverMemberManager.update(any())).thenReturn(true); Boolean result = nacosClusterOperationService.updateNodes(members); verify(serverMemberManager, times(1)).update(any()); assertTrue(result); } @Test void testUpdateLookup() throws NacosException { LookupUpdateRequest lookupUpdateRequest = new LookupUpdateRequest(); lookupUpdateRequest.setType("test"); Boolean result = nacosClusterOperationService.updateLookup(lookupUpdateRequest); verify(serverMemberManager).switchLookup("test"); assertTrue(result); } }
NacosClusterOperationServiceTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumeMultipleDirectoriesTest.java
{ "start": 1206, "end": 3212 }
class ____ extends ContextTestSupport { public static final String FILE_QUERY = "?initialDelay=0&delay=10&recursive=true&delete=true&sortBy=file:path"; @SuppressWarnings("unchecked") @Test public void testMultiDir() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Bye World", "Hello World", "Godday World"); String fileUri = fileUri(FILE_QUERY); template.sendBodyAndHeader(fileUri, "Bye World", Exchange.FILE_NAME, "bye.txt"); template.sendBodyAndHeader(fileUri, "Hello World", Exchange.FILE_NAME, "sub/hello.txt"); template.sendBodyAndHeader(fileUri, "Godday World", Exchange.FILE_NAME, "sub/sub2/godday.txt"); assertMockEndpointsSatisfied(); Exchange exchange = mock.getExchanges().get(0); GenericFile<File> gf = (GenericFile<File>) exchange.getProperty(FileComponent.FILE_EXCHANGE_FILE); File file = gf.getFile(); assertDirectoryEquals(testFile("bye.txt").toString(), file.getPath()); assertEquals("bye.txt", file.getName()); exchange = mock.getExchanges().get(1); gf = (GenericFile<File>) exchange.getProperty(FileComponent.FILE_EXCHANGE_FILE); file = gf.getFile(); assertDirectoryEquals(testFile("sub/hello.txt").toString(), file.getPath()); assertEquals("hello.txt", file.getName()); exchange = mock.getExchanges().get(2); gf = (GenericFile<File>) exchange.getProperty(FileComponent.FILE_EXCHANGE_FILE); file = gf.getFile(); assertDirectoryEquals(testFile("sub/sub2/godday.txt").toString(), file.getPath()); assertEquals("godday.txt", file.getName()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(fileUri(FILE_QUERY)).convertBodyTo(String.class).to("mock:result"); } }; } }
FileConsumeMultipleDirectoriesTest
java
elastic__elasticsearch
modules/legacy-geo/src/internalClusterTest/java/org/elasticsearch/legacygeo/search/LegacyGeoShapeIT.java
{ "start": 1269, "end": 2893 }
class ____ extends GeoShapeIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singleton(TestLegacyGeoShapeFieldMapperPlugin.class); } @Override protected void getGeoShapeMapping(XContentBuilder b) throws IOException { b.field("type", "geo_shape"); b.field("strategy", "recursive"); } @Override protected IndexVersion randomSupportedVersion() { return IndexVersionUtils.randomCompatibleWriteVersion(random()); } @Override protected boolean allowExpensiveQueries() { return false; } /** * Test that the circle is still supported for the legacy shapes */ public void testLegacyCircle() throws Exception { // create index assertAcked( prepareCreate("test").setSettings(settings(randomSupportedVersion()).build()) .setMapping("shape", "type=geo_shape,strategy=recursive,tree=geohash") ); ensureGreen(); indexRandom(true, prepareIndex("test").setId("0").setSource("shape", (ToXContent) (builder, params) -> { builder.startObject() .field("type", "circle") .startArray("coordinates") .value(30) .value(50) .endArray() .field("radius", "77km") .endObject(); return builder; })); // test self crossing of circles assertHitCount(prepareSearch("test").setQuery(geoShapeQuery("shape", new Circle(30, 50, 77000))), 1L); } }
LegacyGeoShapeIT
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/DebugAdmin.java
{ "start": 4684, "end": 9196 }
class ____ extends DebugCommand { VerifyMetaCommand() { super("verifyMeta", "verifyMeta -meta <metadata-file> [-block <block-file>]", " Verify HDFS metadata and block files. If a block file is specified, we" + System.lineSeparator() + " will verify that the checksums in the metadata file match the block" + System.lineSeparator() + " file."); } int run(List<String> args) throws IOException { if (args.size() == 0) { System.out.println(usageText); System.out.println(helpText + System.lineSeparator()); return 1; } String blockFile = StringUtils.popOptionWithArgument("-block", args); String metaFile = StringUtils.popOptionWithArgument("-meta", args); if (metaFile == null) { System.err.println("You must specify a meta file with -meta"); return 1; } FileInputStream metaStream = null, dataStream = null; FileChannel metaChannel = null, dataChannel = null; DataInputStream checksumStream = null; try { BlockMetadataHeader header; try { metaStream = new FileInputStream(metaFile); checksumStream = new DataInputStream(metaStream); header = BlockMetadataHeader.readHeader(checksumStream); metaChannel = metaStream.getChannel(); metaChannel.position(HEADER_LEN); } catch (RuntimeException e) { System.err.println("Failed to read HDFS metadata file header for " + metaFile + ": " + StringUtils.stringifyException(e)); return 1; } catch (IOException e) { System.err.println("Failed to read HDFS metadata file header for " + metaFile + ": " + StringUtils.stringifyException(e)); return 1; } DataChecksum checksum = header.getChecksum(); System.out.println("Checksum type: " + checksum.toString()); if (blockFile == null) { return 0; } ByteBuffer metaBuf, dataBuf; try { dataStream = new FileInputStream(blockFile); dataChannel = dataStream.getChannel(); final int CHECKSUMS_PER_BUF = 1024 * 32; metaBuf = ByteBuffer.allocate(checksum. getChecksumSize() * CHECKSUMS_PER_BUF); dataBuf = ByteBuffer.allocate(checksum. getBytesPerChecksum() * CHECKSUMS_PER_BUF); } catch (IOException e) { System.err.println("Failed to open HDFS block file for " + blockFile + ": " + StringUtils.stringifyException(e)); return 1; } long offset = 0; while (true) { dataBuf.clear(); int dataRead = -1; try { dataRead = dataChannel.read(dataBuf); if (dataRead < 0) { break; } } catch (IOException e) { System.err.println("Got I/O error reading block file " + blockFile + "from disk at offset " + dataChannel.position() + ": " + StringUtils.stringifyException(e)); return 1; } try { int csumToRead = (((checksum.getBytesPerChecksum() - 1) + dataRead) / checksum.getBytesPerChecksum()) * checksum.getChecksumSize(); metaBuf.clear(); metaBuf.limit(csumToRead); metaChannel.read(metaBuf); dataBuf.flip(); metaBuf.flip(); } catch (IOException e) { System.err.println("Got I/O error reading metadata file " + metaFile + "from disk at offset " + metaChannel.position() + ": " + StringUtils.stringifyException(e)); return 1; } try { checksum.verifyChunkedSums(dataBuf, metaBuf, blockFile, offset); } catch (IOException e) { System.out.println("verifyChunkedSums error: " + StringUtils.stringifyException(e)); return 1; } offset += dataRead; } System.out.println("Checksum verification succeeded on block file " + blockFile); return 0; } finally { IOUtils.cleanupWithLogger(null, metaStream, dataStream, checksumStream); } } } /** * The command for verifying a block metadata file and possibly block file. */ private static
VerifyMetaCommand
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/PreferJavaTimeOverloadTest.java
{ "start": 2494, "end": 3228 }
class ____ { public CacheBuilder foo(CacheBuilder builder) { Duration duration = Duration.ofMillis(12345); // BUG: Diagnostic contains: builder.expireAfterAccess(duration); return builder.expireAfterAccess(duration.toSeconds(), TimeUnit.SECONDS); } } """) .doTest(); } @Test public void callingLongTimeUnitMethodWithDurationOverload_durationDecompose_getSeconds() { helper .addSourceLines( "TestClass.java", """ import com.google.common.cache.CacheBuilder; import java.time.Duration; import java.util.concurrent.TimeUnit; public
TestClass
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsReportOrdering.java
{ "start": 1031, "end": 1348 }
interface ____ * report the order of data in each partition to Spark. * Global order is part of the partitioning, see {@link SupportsReportPartitioning}. * <p> * Spark uses ordering information to exploit existing order to avoid sorting required by * subsequent operations. * * @since 3.4.0 */ @Evolving public
to
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SagaEndpointBuilderFactory.java
{ "start": 6479, "end": 7189 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final SagaHeaderNameBuilder INSTANCE = new SagaHeaderNameBuilder(); /** * The long running action. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code Long-Running-Action}. */ public String longRunningAction() { return "Long-Running-Action"; } } static SagaEndpointBuilder endpointBuilder(String componentName, String path) {
SagaHeaderNameBuilder
java
google__guava
android/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java
{ "start": 3464, "end": 3507 }
class ____<T> {} private abstract static
Bar
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/odps/OdpsDropViewTest.java
{ "start": 737, "end": 981 }
class ____ extends TestCase { public void test_column_comment() throws Exception { String sql = "drop view if exists view_name;"; assertEquals("DROP VIEW IF EXISTS view_name;", SQLUtils.formatOdps(sql)); } }
OdpsDropViewTest
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/security/ContextEncryptionAdapter.java
{ "start": 960, "end": 1507 }
class ____ { /** * @return computed encryptionKey from server provided encryptionContext */ public abstract String getEncodedKey(); /** * @return computed encryptionKeySHA from server provided encryptionContext */ public abstract String getEncodedKeySHA(); /** * @return encryptionContext to be supplied in createPath API */ public abstract String getEncodedContext(); /** * Destroys all the encapsulated fields which are used for creating keys. */ public abstract void destroy(); }
ContextEncryptionAdapter
java
google__dagger
javatests/dagger/internal/codegen/ComponentProcessorTest.java
{ "start": 27810, "end": 28067 }
class ____ {", " @Inject B(Provider<String> a) {}", "}"); Source nullableStringComponentFile = CompilerTests.javaSource( "test.NullableStringComponent", "package test;", "", "
B
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/base/DaggerSuperficialValidation.java
{ "start": 24411, "end": 24805 }
class ____ extends ValidationException { private final ValidationReport report; public JavaKeywordErrorType(ValidationReport report) { this.report = report; } public ValidationReport getReport() { return report; } } /** A {@link ValidationException} that originated from an unknown error type. */ public static final
JavaKeywordErrorType
java
netty__netty
codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpDataTest.java
{ "start": 1404, "end": 1635 }
class ____ { private static final byte[] BYTES = new byte[64]; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @ParameterizedTest(name = "{displayName}({0})") @MethodSource("data") @
HttpDataTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/metadata/MetadataIndexAliasesService.java
{ "start": 2444, "end": 14520 }
class ____ { private final IndicesService indicesService; private final NamedXContentRegistry xContentRegistry; private final ClusterStateTaskExecutor<ApplyAliasesTask> executor; private final MasterServiceTaskQueue<ApplyAliasesTask> taskQueue; private final ClusterService clusterService; @Inject public MetadataIndexAliasesService( ClusterService clusterService, IndicesService indicesService, NamedXContentRegistry xContentRegistry ) { this.clusterService = clusterService; this.indicesService = indicesService; this.xContentRegistry = xContentRegistry; this.executor = new SimpleBatchedAckListenerTaskExecutor<>() { @Override public Tuple<ClusterState, ClusterStateAckListener> executeTask(ApplyAliasesTask applyAliasesTask, ClusterState clusterState) { return new Tuple<>( applyAliasActions( clusterState.projectState(applyAliasesTask.request().projectId()), applyAliasesTask.request().actions() ), applyAliasesTask ); } }; this.taskQueue = clusterService.createTaskQueue("index-aliases", Priority.URGENT, this.executor); } public void indicesAliases( final IndicesAliasesClusterStateUpdateRequest request, final ActionListener<IndicesAliasesResponse> listener ) { taskQueue.submitTask("index-aliases", new ApplyAliasesTask(request, listener), request.masterNodeTimeout()); } /** * Handles the cluster state transition to a version that reflects the provided {@link AliasAction}s. */ public ClusterState applyAliasActions(ProjectState projectState, Iterable<AliasAction> actions) { ClusterState currentState = projectState.cluster(); ProjectId projectId = projectState.projectId(); List<Index> indicesToClose = new ArrayList<>(); Map<String, IndexService> indices = new HashMap<>(); ProjectMetadata currentProjectMetadata = projectState.metadata(); try { boolean changed = false; // Gather all the indexes that must be removed first so: // 1. We don't cause error when attempting to replace an index with a alias of the same name. // 2. We don't allow removal of aliases from indexes that we're just going to delete anyway. That'd be silly. Set<Index> indicesToDelete = new HashSet<>(); for (AliasAction action : actions) { if (action.removeIndex()) { IndexMetadata index = currentProjectMetadata.indices().get(action.getIndex()); if (index == null) { throw new IndexNotFoundException(action.getIndex()); } validateAliasTargetIsNotDSBackingIndex(currentProjectMetadata, action); indicesToDelete.add(index.getIndex()); changed = true; } } // Remove the indexes if there are any to remove if (changed) { currentState = MetadataDeleteIndexService.deleteIndices(projectState, indicesToDelete, clusterService.getSettings()); currentProjectMetadata = currentState.metadata().getProject(projectId); } ProjectMetadata.Builder metadata = ProjectMetadata.builder(currentProjectMetadata); // Run the remaining alias actions final Set<String> maybeModifiedIndices = new HashSet<>(); for (AliasAction action : actions) { if (action.removeIndex()) { // Handled above continue; } /* It is important that we look up the index using the metadata builder we are modifying so we can remove an * index and replace it with an alias. */ Function<String, String> lookup = name -> { IndexMetadata imd = metadata.get(name); if (imd != null) { return imd.getIndex().getName(); } DataStream dataStream = metadata.dataStream(name); if (dataStream != null) { return dataStream.getName(); } return null; }; // Handle the actions that do data streams aliases separately: DataStream dataStream = metadata.dataStream(action.getIndex()); if (dataStream != null) { NewAliasValidator newAliasValidator = (alias, indexRouting, searchRouting, filter, writeIndex) -> { AliasValidator.validateAlias(alias, action.getIndex(), indexRouting, lookup); if (Strings.hasLength(filter)) { for (Index index : dataStream.getIndices()) { IndexMetadata imd = metadata.get(index.getName()); if (imd == null) { throw new IndexNotFoundException(action.getIndex()); } IndexSettings.MODE.get(imd.getSettings()).validateAlias(indexRouting, searchRouting); validateFilter(indicesToClose, indices, action, imd, alias, filter); } } }; if (action.apply(newAliasValidator, metadata, null)) { changed = true; } continue; } IndexMetadata index = metadata.get(action.getIndex()); if (index == null) { throw new IndexNotFoundException(action.getIndex()); } validateAliasTargetIsNotDSBackingIndex(currentProjectMetadata, action); NewAliasValidator newAliasValidator = (alias, indexRouting, searchRouting, filter, writeIndex) -> { AliasValidator.validateAlias(alias, action.getIndex(), indexRouting, lookup); IndexSettings.MODE.get(index.getSettings()).validateAlias(indexRouting, searchRouting); if (Strings.hasLength(filter)) { validateFilter(indicesToClose, indices, action, index, alias, filter); } }; if (action.apply(newAliasValidator, metadata, index)) { changed = true; maybeModifiedIndices.add(index.getIndex().getName()); } } for (final String maybeModifiedIndex : maybeModifiedIndices) { final IndexMetadata currentIndexMetadata = currentProjectMetadata.index(maybeModifiedIndex); final IndexMetadata newIndexMetadata = metadata.get(maybeModifiedIndex); // only increment the aliases version if the aliases actually changed for this index if (currentIndexMetadata.getAliases().equals(newIndexMetadata.getAliases()) == false) { assert currentIndexMetadata.getAliasesVersion() == newIndexMetadata.getAliasesVersion(); metadata.put(new IndexMetadata.Builder(newIndexMetadata).aliasesVersion(1 + currentIndexMetadata.getAliasesVersion())); } } if (changed) { ProjectMetadata updatedMetadata = metadata.build(); // even though changes happened, they resulted in 0 actual changes to metadata // i.e. remove and add the same alias to the same index if (updatedMetadata.equalsAliases(currentProjectMetadata) == false) { return ClusterState.builder(currentState).putProjectMetadata(updatedMetadata).build(); } } return currentState; } finally { for (Index index : indicesToClose) { indicesService.removeIndex( index, NO_LONGER_ASSIGNED, "created for alias processing", CloseUtils.NO_SHARDS_CREATED_EXECUTOR, ActionListener.noop() ); } } } // Visible for testing purposes ClusterStateTaskExecutor<ApplyAliasesTask> getExecutor() { return executor; } private void validateFilter( List<Index> indicesToClose, Map<String, IndexService> indices, AliasAction action, IndexMetadata index, String alias, String filter ) { IndexService indexService = indices.get(index.getIndex().getName()); if (indexService == null) { indexService = indicesService.indexService(index.getIndex()); if (indexService == null) { // temporarily create the index and add mappings so we can parse the filter try { indexService = indicesService.createIndex(index, emptyList(), false); indicesToClose.add(index.getIndex()); } catch (IOException e) { throw new ElasticsearchException("Failed to create temporary index for parsing the alias", e); } indexService.mapperService().merge(index, MapperService.MergeReason.MAPPING_RECOVERY); } indices.put(action.getIndex(), indexService); } // the context is only used for validation so it's fine to pass fake values for the shard id, // but the current timestamp should be set to real value as we may use `now` in a filtered alias AliasValidator.validateAliasFilter( alias, filter, indexService.newSearchExecutionContext(0, 0, null, System::currentTimeMillis, null, emptyMap()), xContentRegistry ); } private static void validateAliasTargetIsNotDSBackingIndex(ProjectMetadata projectMetadata, AliasAction action) { IndexAbstraction indexAbstraction = projectMetadata.getIndicesLookup().get(action.getIndex()); assert indexAbstraction != null : "invalid cluster metadata. index [" + action.getIndex() + "] was not found"; if (indexAbstraction.getParentDataStream() != null) { throw new IllegalArgumentException( "The provided index [" + action.getIndex() + "] is a backing index belonging to data stream [" + indexAbstraction.getParentDataStream().getName() + "]. Data stream backing indices don't support alias operations." ); } } /** * A cluster state update task that consists of the cluster state request and the listeners that need to be notified upon completion. */ record ApplyAliasesTask(IndicesAliasesClusterStateUpdateRequest request, ActionListener<IndicesAliasesResponse> listener) implements ClusterStateTaskListener, ClusterStateAckListener { @Override public void onFailure(Exception e) { listener.onFailure(e); } @Override public boolean mustAck(DiscoveryNode discoveryNode) { return true; } @Override public void onAllNodesAcked() { listener.onResponse(IndicesAliasesResponse.build(request.actionResults())); } @Override public void onAckFailure(Exception e) { listener.onResponse(IndicesAliasesResponse.NOT_ACKNOWLEDGED); } @Override public void onAckTimeout() { listener.onResponse(IndicesAliasesResponse.NOT_ACKNOWLEDGED); } @Override public TimeValue ackTimeout() { return request.ackTimeout(); } } }
MetadataIndexAliasesService