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
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/LazyAutowiredAnnotationBeanPostProcessorTests.java
{ "start": 10416, "end": 10779 }
class ____ implements TestBeanHolder { private final TestBean testBean; @Autowired @Lazy public ConstructorResourceInjectionBeanWithConstructorLevelLazy(TestBean testBean) { this.testBean = testBean; } @Override public TestBean getTestBean() { return this.testBean; } } public static
ConstructorResourceInjectionBeanWithConstructorLevelLazy
java
spring-projects__spring-boot
module/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java
{ "start": 4856, "end": 5181 }
class ____ extends AbstractAuthenticationAuditListener { @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { } @Override public void onApplicationEvent(AbstractAuthenticationEvent event) { } } @Configuration(proxyBeanMethods = false) static
TestAuthenticationAuditListener
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/hash/HashPartition.java
{ "start": 25158, "end": 26986 }
class ____ implements MutableObjectIterator<BT> { private final TypeComparator<BT> comparator; private long currentPointer; private int currentHashCode; private PartitionIterator(final TypeComparator<BT> comparator) throws IOException { this.comparator = comparator; setReadPosition(0); } public final BT next(BT reuse) throws IOException { final int pos = getCurrentPositionInSegment(); final int buffer = HashPartition.this.currentBufferNum; this.currentPointer = (((long) buffer) << HashPartition.this.segmentSizeBits) + pos; try { reuse = HashPartition.this.buildSideSerializer.deserialize( reuse, HashPartition.this); this.currentHashCode = this.comparator.hash(reuse); return reuse; } catch (EOFException eofex) { return null; } } public final BT next() throws IOException { final int pos = getCurrentPositionInSegment(); final int buffer = HashPartition.this.currentBufferNum; this.currentPointer = (((long) buffer) << HashPartition.this.segmentSizeBits) + pos; try { BT result = HashPartition.this.buildSideSerializer.deserialize(HashPartition.this); this.currentHashCode = this.comparator.hash(result); return result; } catch (EOFException eofex) { return null; } } protected final long getPointer() { return this.currentPointer; } protected final int getCurrentHashCode() { return this.currentHashCode; } } }
PartitionIterator
java
elastic__elasticsearch
distribution/tools/server-cli/src/main/java/org/elasticsearch/server/cli/ServerProcessBuilder.java
{ "start": 1234, "end": 1850 }
class ____ used to create a {@link ServerProcess}. * Each ServerProcessBuilder instance manages a collection of process attributes. The {@link ServerProcessBuilder#start()} method creates * a new {@link ServerProcess} instance with those attributes. * * Each process builder manages these process attributes: * - a temporary directory * - process info to pass through to the new Java subprocess * - the command line arguments to run Elasticsearch * - a list of JVM options to be passed to the Elasticsearch Java process * - a {@link Terminal} to read input and write output from/to the cli console */ public
is
java
square__javapoet
src/test/java/com/squareup/javapoet/TypeSpecTest.java
{ "start": 63068, "end": 63893 }
interface ____ {\n" + "}\n"); } private String toString(TypeSpec typeSpec) { return JavaFile.builder(tacosPackage, typeSpec).build().toString(); } @Test public void multilineStatement() throws Exception { TypeSpec taco = TypeSpec.classBuilder("Taco") .addMethod(MethodSpec.methodBuilder("toString") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(String.class) .addStatement("return $S\n+ $S\n+ $S\n+ $S\n+ $S", "Taco(", "beef,", "lettuce,", "cheese", ")") .build()) .build(); assertThat(toString(taco)).isEqualTo("" + "package com.squareup.tacos;\n" + "\n" + "import java.lang.Override;\n" + "import java.lang.String;\n" + "\n" + "
Taco
java
spring-projects__spring-framework
spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/JCacheInterceptor.java
{ "start": 1754, "end": 3028 }
class ____ extends JCacheAspectSupport implements MethodInterceptor, Serializable { /** * Construct a new {@code JCacheInterceptor} with the default error handler. */ public JCacheInterceptor() { } /** * Construct a new {@code JCacheInterceptor} with the given error handler. * @param errorHandler a supplier for the error handler to use, * applying the default error handler if the supplier is not resolvable * @since 5.1 */ public JCacheInterceptor(@Nullable Supplier<? extends @Nullable CacheErrorHandler> errorHandler) { this.errorHandler = new SingletonSupplier<>(errorHandler, SimpleCacheErrorHandler::new); } @Override public @Nullable Object invoke(final MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); CacheOperationInvoker aopAllianceInvoker = () -> { try { return invocation.proceed(); } catch (Throwable ex) { throw new CacheOperationInvoker.ThrowableWrapper(ex); } }; Object target = invocation.getThis(); Assert.state(target != null, "Target must not be null"); try { return execute(aopAllianceInvoker, target, method, invocation.getArguments()); } catch (CacheOperationInvoker.ThrowableWrapper th) { throw th.getOriginal(); } } }
JCacheInterceptor
java
quarkusio__quarkus
extensions/security/spi/src/main/java/io/quarkus/security/spi/AdditionalSecuredMethodsBuildItem.java
{ "start": 388, "end": 1118 }
class ____ extends MultiBuildItem { public final Collection<MethodInfo> additionalSecuredMethods; public final Optional<List<String>> rolesAllowed; public AdditionalSecuredMethodsBuildItem(Collection<MethodInfo> additionalSecuredMethods) { this.additionalSecuredMethods = Collections.unmodifiableCollection(additionalSecuredMethods); rolesAllowed = Optional.empty(); } public AdditionalSecuredMethodsBuildItem(Collection<MethodInfo> additionalSecuredMethods, Optional<List<String>> rolesAllowed) { this.additionalSecuredMethods = Collections.unmodifiableCollection(additionalSecuredMethods); this.rolesAllowed = rolesAllowed; } }
AdditionalSecuredMethodsBuildItem
java
apache__thrift
lib/javame/src/org/apache/thrift/meta_data/SetMetaData.java
{ "start": 1654, "end": 1877 }
class ____ extends FieldValueMetaData { public final FieldValueMetaData elemMetaData; public SetMetaData(byte type, FieldValueMetaData eMetaData){ super(type); this.elemMetaData = eMetaData; } }
SetMetaData
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/health/GetHealthActionIT.java
{ "start": 1561, "end": 2879 }
class ____ extends ESIntegTestCase { private static final String ILM_INDICATOR_NAME = "ilm"; private static final String SLM_INDICATOR_NAME = "slm"; private static final String INSTANCE_HAS_MASTER_INDICATOR_NAME = "instance_has_master"; private static final String NONEXISTENT_INDICATOR_NAME = "test_nonexistent_indicator"; @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return appendToCopy(super.nodePlugins(), TestHealthPlugin.class); } public static final Setting<HealthStatus> ILM_HEALTH_STATUS_SETTING = new Setting<>( "test.health.status.ilm", "GREEN", HealthStatus::valueOf, Setting.Property.NodeScope, Setting.Property.Dynamic ); public static final Setting<HealthStatus> SLM_HEALTH_STATUS_SETTING = new Setting<>( "test.health.status.slm", "GREEN", HealthStatus::valueOf, Setting.Property.NodeScope, Setting.Property.Dynamic ); public static final Setting<HealthStatus> CLUSTER_COORDINATION_HEALTH_STATUS_SETTING = new Setting<>( "test.health.status.cluster.coordination", "GREEN", HealthStatus::valueOf, Setting.Property.NodeScope, Setting.Property.Dynamic ); public static final
GetHealthActionIT
java
elastic__elasticsearch
x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/action/TransportFollowInfoActionTests.java
{ "start": 1191, "end": 3463 }
class ____ extends ESTestCase { public void testGetFollowInfos() { ClusterState state = createCS( new String[] { "follower1", "follower2", "follower3", "index4" }, new boolean[] { true, true, true, false }, new boolean[] { true, true, false, false } ); List<String> concreteIndices = Arrays.asList("follower1", "follower3"); List<FollowerInfo> result = TransportFollowInfoAction.getFollowInfos(concreteIndices, state); assertThat(result.size(), equalTo(2)); assertThat(result.get(0).getFollowerIndex(), equalTo("follower1")); assertThat(result.get(0).getStatus(), equalTo(Response.Status.ACTIVE)); assertThat(result.get(1).getFollowerIndex(), equalTo("follower3")); assertThat(result.get(1).getStatus(), equalTo(Response.Status.PAUSED)); } private static ClusterState createCS(String[] indices, boolean[] followerIndices, boolean[] statuses) { PersistentTasksCustomMetadata.Builder persistentTasks = PersistentTasksCustomMetadata.builder(); Metadata.Builder mdBuilder = Metadata.builder(); for (int i = 0; i < indices.length; i++) { String index = indices[i]; boolean isFollowIndex = followerIndices[i]; boolean active = statuses[i]; IndexMetadata.Builder imdBuilder = IndexMetadata.builder(index) .settings(settings(IndexVersion.current())) .numberOfShards(1) .numberOfReplicas(0); if (isFollowIndex) { imdBuilder.putCustom(Ccr.CCR_CUSTOM_METADATA_KEY, new HashMap<>()); if (active) { persistentTasks.addTask( Integer.toString(i), ShardFollowTask.NAME, createShardFollowTask(new Index(index, IndexMetadata.INDEX_UUID_NA_VALUE)), null ); } } mdBuilder.put(imdBuilder); } mdBuilder.putCustom(PersistentTasksCustomMetadata.TYPE, persistentTasks.build()); return ClusterState.builder(new ClusterName("_cluster")).metadata(mdBuilder.build()).build(); } }
TransportFollowInfoActionTests
java
spring-projects__spring-security
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson2/Saml2AssertionAuthenticationMixin.java
{ "start": 1351, "end": 2157 }
class ____ in serialize/deserialize * {@link Saml2AssertionAuthentication}. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new Saml2Jackson2Module()); * </pre> * * @author Josh Cummings * @since 7.0 * @see Saml2Jackson2Module * @see SecurityJackson2Modules * @deprecated as of 7.0 in favor of * {@code org.springframework.security.saml2.jackson.Saml2AssertionAuthenticationMixin} * based on Jackson 3 */ @SuppressWarnings("removal") @Deprecated(forRemoval = true) @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(value = { "authenticated" }, ignoreUnknown = true)
helps
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/inject/generics/V6.java
{ "start": 67, "end": 194 }
class ____ implements CylinderProvider { @Override public int getCylinders() { return 6; } } // end::class[]
V6
java
grpc__grpc-java
s2a/src/test/java/io/grpc/s2a/internal/handshaker/GetAuthenticationMechanismsTest.java
{ "start": 1254, "end": 2735 }
class ____ { @Rule public final Expect expect = Expect.create(); private static final String TOKEN = "access_token"; private static String originalAccessToken; private Optional<AccessTokenManager> tokenManager; @BeforeClass public static void setUpClass() { originalAccessToken = SingleTokenFetcher.getAccessToken(); // Set the token that the client will use to authenticate to the S2A. SingleTokenFetcher.setAccessToken(TOKEN); } @Before public void setUp() { tokenManager = AccessTokenManager.create(); } @AfterClass public static void tearDownClass() { SingleTokenFetcher.setAccessToken(originalAccessToken); } @Test public void getAuthMechanisms_emptyIdentity_success() { expect .that(GetAuthenticationMechanisms.getAuthMechanism(Optional.empty(), tokenManager)) .isEqualTo( Optional.of(AuthenticationMechanism.newBuilder().setToken("access_token").build())); } @Test public void getAuthMechanisms_nonEmptyIdentity_success() { S2AIdentity fakeIdentity = S2AIdentity.fromSpiffeId("fake-spiffe-id"); expect .that(GetAuthenticationMechanisms.getAuthMechanism(Optional.of(fakeIdentity), tokenManager)) .isEqualTo( Optional.of( AuthenticationMechanism.newBuilder() .setIdentity(fakeIdentity.getIdentity()) .setToken("access_token") .build())); } }
GetAuthenticationMechanismsTest
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredArguments.java
{ "start": 1015, "end": 2619 }
interface ____ { /** * Return the resolved argument at the specified index. * @param <T> the type of the argument * @param index the argument index * @param requiredType the required argument type * @return the argument */ @SuppressWarnings("unchecked") default <T> @Nullable T get(int index, Class<T> requiredType) { Object value = getObject(index); if (!ClassUtils.isAssignableValue(requiredType, value)) { throw new IllegalArgumentException("Argument type mismatch: expected '" + ClassUtils.getQualifiedName(requiredType) + "' for value [" + value + "]"); } return (T) value; } /** * Return the resolved argument at the specified index. * @param <T> the type of the argument * @param index the argument index * @return the argument */ @SuppressWarnings("unchecked") default <T> @Nullable T get(int index) { return (T) getObject(index); } /** * Return the resolved argument at the specified index. * @param index the argument index * @return the argument */ default @Nullable Object getObject(int index) { return toArray()[index]; } /** * Return the arguments as an object array. * @return the arguments as an object array */ @Nullable Object[] toArray(); /** * Factory method to create a new {@link AutowiredArguments} instance from * the given object array. * @param arguments the arguments * @return a new {@link AutowiredArguments} instance */ static AutowiredArguments of(@Nullable Object[] arguments) { Assert.notNull(arguments, "'arguments' must not be null"); return () -> arguments; } }
AutowiredArguments
java
spring-projects__spring-boot
module/spring-boot-data-mongodb/src/main/java/org/springframework/boot/data/mongodb/autoconfigure/DataMongoRepositoriesRegistrar.java
{ "start": 1299, "end": 1814 }
class ____ extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class<? extends Annotation> getAnnotation() { return EnableMongoRepositories.class; } @Override protected Class<?> getConfiguration() { return EnableMongoRepositoriesConfiguration.class; } @Override protected RepositoryConfigurationExtension getRepositoryConfigurationExtension() { return new MongoRepositoryConfigurationExtension(); } @EnableMongoRepositories private static final
DataMongoRepositoriesRegistrar
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MilvusComponentBuilderFactory.java
{ "start": 1834, "end": 6258 }
interface ____ extends ComponentBuilder<MilvusComponent> { /** * The configuration;. * * The option is a: * &lt;code&gt;org.apache.camel.component.milvus.MilvusConfiguration&lt;/code&gt; type. * * Group: producer * * @param configuration the value to set * @return the dsl builder */ default MilvusComponentBuilder configuration(org.apache.camel.component.milvus.MilvusConfiguration configuration) { doSetProperty("configuration", configuration); return this; } /** * The host to connect to. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: localhost * Group: producer * * @param host the value to set * @return the dsl builder */ default MilvusComponentBuilder host(java.lang.String host) { doSetProperty("host", host); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default MilvusComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * The port to connect to. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 19530 * Group: producer * * @param port the value to set * @return the dsl builder */ default MilvusComponentBuilder port(int port) { doSetProperty("port", port); return this; } /** * Sets a default timeout for all requests. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Group: producer * * @param timeout the value to set * @return the dsl builder */ default MilvusComponentBuilder timeout(long timeout) { doSetProperty("timeout", timeout); return this; } /** * Sets the API key to use for authentication. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param token the value to set * @return the dsl builder */ default MilvusComponentBuilder token(java.lang.String token) { doSetProperty("token", token); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default MilvusComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } }
MilvusComponentBuilder
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlSetTest_3.java
{ "start": 989, "end": 2376 }
class ____ extends TestCase { public void test_0() throws Exception { String sql = "SET sql_mode=?,NAMES ?,CHARACTER SET utf8,CHARACTER_SET_RESULTS=utf8,COLLATION_CONNECTION=?"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); SQLStatement stmt = stmtList.get(0); // print(stmtList); assertEquals(1, stmtList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); 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(0, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); String text = SQLUtils.toMySqlString(stmt); assertEquals("SET sql_mode = ?, NAMES ?, CHARACTER SET utf8, CHARACTER_SET_RESULTS = utf8, COLLATION_CONNECTION = ?", text); } public void test_1() throws Exception { SQLUtils.parseSingleStatement("set names utf8mb4", "mysql"); SQLUtils.parseSingleStatement("set names utf8mb4", (DbType) null); } }
MySqlSetTest_3
java
apache__flink
flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderRetrievalDriverTest.java
{ "start": 1301, "end": 4306 }
class ____ extends KubernetesHighAvailabilityTestBase { @Test void testErrorForwarding() throws Exception { new Context() { { runTest( () -> { leaderCallbackGrantLeadership(); final FlinkKubeClient.WatchCallbackHandler<KubernetesConfigMap> callbackHandler = getLeaderRetrievalConfigMapCallback(); callbackHandler.onError( Collections.singletonList(getLeaderConfigMap())); final String errMsg = "Error while watching the ConfigMap " + LEADER_CONFIGMAP_NAME; retrievalEventHandler.waitForError(); assertThatChainOfCauses(retrievalEventHandler.getError()) .anySatisfy(t -> assertThat(t).hasMessageContaining(errMsg)); }); } }; } @Test void testKubernetesLeaderRetrievalOnModified() throws Exception { new Context() { { runTest( () -> { leaderCallbackGrantLeadership(); final FlinkKubeClient.WatchCallbackHandler<KubernetesConfigMap> callbackHandler = getLeaderRetrievalConfigMapCallback(); // Leader changed final String newLeader = LEADER_ADDRESS + "_" + 2; putLeaderInformationIntoConfigMap(UUID.randomUUID(), newLeader); callbackHandler.onModified( Collections.singletonList(getLeaderConfigMap())); assertThat(retrievalEventHandler.waitForNewLeader()) .isEqualTo(newLeader); }); } }; } @Test void testKubernetesLeaderRetrievalOnModifiedWithEmpty() throws Exception { new Context() { { runTest( () -> { leaderCallbackGrantLeadership(); final FlinkKubeClient.WatchCallbackHandler<KubernetesConfigMap> callbackHandler = getLeaderRetrievalConfigMapCallback(); // Leader information is cleared getLeaderConfigMap().getData().clear(); callbackHandler.onModified( Collections.singletonList(getLeaderConfigMap())); retrievalEventHandler.waitForEmptyLeaderInformation(); assertThat(retrievalEventHandler.getAddress()).isNull(); }); } }; } }
KubernetesLeaderRetrievalDriverTest
java
apache__flink
flink-core-api/src/main/java/org/apache/flink/util/function/LongFunctionWithException.java
{ "start": 1019, "end": 1270 }
interface ____<R, E extends Throwable> { /** * Applies this function to the given argument. * * @param value the function argument * @return the function result */ R apply(long value) throws E; }
LongFunctionWithException
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/selection/qualifier/errors/ErroneousMessageByNamedMapper.java
{ "start": 440, "end": 685 }
interface ____ { @Mapping(target = "nested", source = "value", qualifiedByName = "SelectMe") Target map(Source source); default Nested map(String in) { return null; } // CHECKSTYLE:OFF
ErroneousMessageByNamedMapper
java
google__dagger
javatests/dagger/functional/guava/OptionalBindingComponents.java
{ "start": 4199, "end": 4420 }
interface ____ extends OptionalBindingComponent { PresentOptionalBindingSubcomponent presentChild(); } @Component(modules = {OptionalBindingModule.class, ConcreteBindingModule.class})
AbsentOptionalBindingComponent
java
square__retrofit
retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/ObservableThrowingSafeSubscriberTest.java
{ "start": 1647, "end": 11600 }
interface ____ { @GET("/") Observable<String> body(); @GET("/") Observable<Response<String>> response(); @GET("/") Observable<Result<String>> result(); } private Service service; @Before public void setUp() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new StringConverterFactory()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); service = retrofit.create(Service.class); } @Test public void bodyThrowingInOnNextDeliveredToError() { server.enqueue(new MockResponse()); RecordingSubscriber<String> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .body() .subscribe( new ForwardingSubscriber<String>(observer) { @Override public void onNext(String value) { throw e; } }); observer.assertError(e); } @Test public void bodyThrowingInOnCompleteDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> pluginRef = new AtomicReference<>(); RxJavaPlugins.getInstance() .registerErrorHandler( new RxJavaErrorHandler() { @Override public void handleError(Throwable throwable) { if (throwable instanceof OnCompletedFailedException) { if (!pluginRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); // Don't swallow secondary errors! } } } }); RecordingSubscriber<String> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .body() .subscribe( new ForwardingSubscriber<String>(observer) { @Override public void onCompleted() { throw e; } }); observer.assertAnyValue(); assertThat(pluginRef.get()).hasCauseThat().isSameInstanceAs(e); } @Test public void bodyThrowingInOnErrorDeliveredToPlugin() { server.enqueue(new MockResponse().setResponseCode(404)); final AtomicReference<Throwable> pluginRef = new AtomicReference<>(); RxJavaPlugins.getInstance() .registerErrorHandler( new RxJavaErrorHandler() { @Override public void handleError(Throwable throwable) { if (throwable instanceof OnErrorFailedException) { if (!pluginRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); // Don't swallow secondary errors! } } } }); RecordingSubscriber<String> observer = subscriberRule.create(); final AtomicReference<Throwable> errorRef = new AtomicReference<>(); final RuntimeException e = new RuntimeException(); service .body() .subscribe( new ForwardingSubscriber<String>(observer) { @Override public void onError(Throwable throwable) { if (!errorRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } throw e; } }); CompositeException composite = (CompositeException) pluginRef.get().getCause(); assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e); } @Test public void responseThrowingInOnNextDeliveredToError() { server.enqueue(new MockResponse()); RecordingSubscriber<Response<String>> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .response() .subscribe( new ForwardingSubscriber<Response<String>>(observer) { @Override public void onNext(Response<String> value) { throw e; } }); observer.assertError(e); } @Test public void responseThrowingInOnCompleteDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> pluginRef = new AtomicReference<>(); RxJavaPlugins.getInstance() .registerErrorHandler( new RxJavaErrorHandler() { @Override public void handleError(Throwable throwable) { if (throwable instanceof OnCompletedFailedException) { if (!pluginRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); // Don't swallow secondary errors! } } } }); RecordingSubscriber<Response<String>> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .response() .subscribe( new ForwardingSubscriber<Response<String>>(observer) { @Override public void onCompleted() { throw e; } }); observer.assertAnyValue(); assertThat(pluginRef.get()).hasCauseThat().isSameInstanceAs(e); } @Test public void responseThrowingInOnErrorDeliveredToPlugin() { server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST)); final AtomicReference<Throwable> pluginRef = new AtomicReference<>(); RxJavaPlugins.getInstance() .registerErrorHandler( new RxJavaErrorHandler() { @Override public void handleError(Throwable throwable) { if (throwable instanceof OnErrorFailedException) { if (!pluginRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); // Don't swallow secondary errors! } } } }); RecordingSubscriber<Response<String>> observer = subscriberRule.create(); final AtomicReference<Throwable> errorRef = new AtomicReference<>(); final RuntimeException e = new RuntimeException(); service .response() .subscribe( new ForwardingSubscriber<Response<String>>(observer) { @Override public void onError(Throwable throwable) { if (!errorRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } throw e; } }); CompositeException composite = (CompositeException) pluginRef.get().getCause(); assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e); } @Test public void resultThrowingInOnNextDeliveredToError() { server.enqueue(new MockResponse()); RecordingSubscriber<Result<String>> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .result() .subscribe( new ForwardingSubscriber<Result<String>>(observer) { @Override public void onNext(Result<String> value) { throw e; } }); observer.assertError(e); } @Test public void resultThrowingInOnCompletedDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> pluginRef = new AtomicReference<>(); RxJavaPlugins.getInstance() .registerErrorHandler( new RxJavaErrorHandler() { @Override public void handleError(Throwable throwable) { if (throwable instanceof OnCompletedFailedException) { if (!pluginRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); // Don't swallow secondary errors! } } } }); RecordingSubscriber<Result<String>> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .result() .subscribe( new ForwardingSubscriber<Result<String>>(observer) { @Override public void onCompleted() { throw e; } }); observer.assertAnyValue(); assertThat(pluginRef.get()).hasCauseThat().isSameInstanceAs(e); } @Test public void resultThrowingInOnErrorDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> pluginRef = new AtomicReference<>(); RxJavaPlugins.getInstance() .registerErrorHandler( new RxJavaErrorHandler() { @Override public void handleError(Throwable throwable) { if (throwable instanceof OnErrorFailedException) { if (!pluginRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); // Don't swallow secondary errors! } } } }); RecordingSubscriber<Result<String>> observer = subscriberRule.create(); final RuntimeException first = new RuntimeException(); final RuntimeException second = new RuntimeException(); service .result() .subscribe( new ForwardingSubscriber<Result<String>>(observer) { @Override public void onNext(Result<String> value) { // The only way to trigger onError for a result is if onNext throws. throw first; } @Override public void onError(Throwable throwable) { throw second; } }); CompositeException composite = (CompositeException) pluginRef.get().getCause(); assertThat(composite.getExceptions()).containsExactly(first, second); } }
Service
java
junit-team__junit5
junit-platform-reporting/src/main/java/org/junit/platform/reporting/legacy/LegacyReportingUtils.java
{ "start": 882, "end": 1080 }
class ____ formerly from {@code junit-platform-launcher} in the * {@link org.junit.platform.launcher.listeners} package. * * @since 1.0.3 */ @API(status = MAINTAINED, since = "1.6") public final
was
java
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/spring/tx/JmsTXForceShutdownIssueManualIT.java
{ "start": 1347, "end": 2589 }
class ____ extends CamelSpringTestSupport { @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext( "org/apache/camel/component/jms/integration/spring/tx/JmsTXForceShutdownIssueTest.xml"); } @Override protected int getShutdownTimeout() { // force a bit faster forced shutdown return 5; } @Test @Disabled("This is a manual test, start Apache ActiveMQ broker manually first, using bin/activemq console") // and make sure to setup tcp transport connector on the remote AMQ broker in the conf/activemq.xml file // <transportConnectors> // <transportConnector name="openwire" uri="tcp://0.0.0.0:61616"/> // </transportConnectors> // the ActiveMQ web console can be used to browse the queue: http://0.0.0.0:8161/admin/ public void testTXForceShutdown() throws Exception { MockEndpoint mock = getMockEndpoint("mock:inflight"); mock.expectedMessageCount(1); template.sendBody("activemq:queue:inbox", "Hello World"); MockEndpoint.assertIsSatisfied(context); // will complete the test and force a shutdown ... } }
JmsTXForceShutdownIssueManualIT
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/TwoColumnLayout.java
{ "start": 1324, "end": 2927 }
class ____ extends HtmlPage { /* * (non-Javadoc) * @see org.apache.hadoop.yarn.webapp.view.HtmlPage#render(org.apache.hadoop.yarn.webapp.hamlet.Hamlet.HTML) */ @Override protected void render(Page.HTML<__> html) { preHead(html); html. title($(TITLE)). link(root_url("static", "yarn.css")). style("#layout { height: 100%; }", "#layout thead td { height: 3em; }", "#layout #navcell { width: 11em; padding: 0 1em; }", "#layout td.content { padding-top: 0 }", "#layout tbody { vertical-align: top; }", "#layout tfoot td { height: 4em; }"). __(JQueryUI.class); postHead(html); JQueryUI.jsnotice(html); html. table("#layout.ui-widget-content"). thead(). tr(). td().$colspan(2). __(header()).__().__().__(). tfoot(). tr(). td().$colspan(2). __(footer()).__().__().__(). tbody(). tr(). td().$id("navcell"). __(nav()).__(). td().$class("content"). __(content()).__().__().__().__().__(); } /** * Do what needs to be done before the header is rendered. This usually * involves setting page variables for Javascript and CSS rendering. * @param html the html to use to render. */ protected void preHead(Page.HTML<__> html) { } /** * Do what needs to be done after the header is rendered. * @param html the html to use to render. */ protected void postHead(Page.HTML<__> html) { } /** * @return the
TwoColumnLayout
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/util/JavaScriptUtils.java
{ "start": 1067, "end": 2593 }
class ____ { /** * Turn JavaScript special characters into escaped characters. * @param input the input string * @return the string with escaped characters */ public static String javaScriptEscape(String input) { StringBuilder filtered = new StringBuilder(input.length()); char prevChar = '\u0000'; char c; for (int i = 0; i < input.length(); i++) { c = input.charAt(i); if (c == '"') { filtered.append("\\\""); } else if (c == '\'') { filtered.append("\\'"); } else if (c == '\\') { filtered.append("\\\\"); } else if (c == '/') { filtered.append("\\/"); } else if (c == '\t') { filtered.append("\\t"); } else if (c == '\n') { if (prevChar != '\r') { filtered.append("\\n"); } } else if (c == '\r') { filtered.append("\\n"); } else if (c == '\f') { filtered.append("\\f"); } else if (c == '\b') { filtered.append("\\b"); } // No '\v' in Java, use octal value for VT ascii char else if (c == '\013') { filtered.append("\\v"); } else if (c == '<') { filtered.append("\\u003C"); } else if (c == '>') { filtered.append("\\u003E"); } // Unicode for PS (line terminator in ECMA-262) else if (c == '\u2028') { filtered.append("\\u2028"); } // Unicode for LS (line terminator in ECMA-262) else if (c == '\u2029') { filtered.append("\\u2029"); } else { filtered.append(c); } prevChar = c; } return filtered.toString(); } }
JavaScriptUtils
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/starters/StarterMetadata.java
{ "start": 1469, "end": 2852 }
class ____ extends DefaultTask { private Configuration dependencies; public StarterMetadata() { Project project = getProject(); getStarterName().convention(project.provider(project::getName)); getStarterDescription().convention(project.provider(project::getDescription)); } @Input public abstract Property<String> getStarterName(); @Input public abstract Property<String> getStarterDescription(); @Classpath public FileCollection getDependencies() { return this.dependencies; } public void setDependencies(Configuration dependencies) { this.dependencies = dependencies; } @OutputFile public abstract RegularFileProperty getDestination(); @TaskAction void generateMetadata() throws IOException { Properties properties = CollectionFactory.createSortedProperties(true); properties.setProperty("name", getStarterName().get()); properties.setProperty("description", getStarterDescription().get()); properties.setProperty("dependencies", String.join(",", this.dependencies.getResolvedConfiguration() .getResolvedArtifacts() .stream() .map(ResolvedArtifact::getName) .collect(Collectors.toSet()))); File destination = getDestination().getAsFile().get(); destination.getParentFile().mkdirs(); try (FileWriter writer = new FileWriter(destination)) { properties.store(writer, null); } } }
StarterMetadata
java
apache__dubbo
dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MethodDefinitionBuilder.java
{ "start": 1595, "end": 2550 }
interface ____ { static MethodDefinition build( ProcessingEnvironment processingEnv, ExecutableElement method, Map<String, TypeDefinition> typeCache) { MethodDefinition methodDefinition = new MethodDefinition(); methodDefinition.setName(getMethodName(method)); methodDefinition.setReturnType(getReturnType(method)); methodDefinition.setParameterTypes(getMethodParameterTypes(method)); methodDefinition.setParameters(getMethodParameters(processingEnv, method, typeCache)); return methodDefinition; } static List<TypeDefinition> getMethodParameters( ProcessingEnvironment processingEnv, ExecutableElement method, Map<String, TypeDefinition> typeCache) { return method.getParameters().stream() .map(element -> TypeDefinitionBuilder.build(processingEnv, element, typeCache)) .collect(Collectors.toList()); } }
MethodDefinitionBuilder
java
spring-projects__spring-framework
spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/factory/generator/InnerComponentConfiguration.java
{ "start": 882, "end": 1064 }
class ____ { final Environment environment; public EnvironmentAwareComponent(Environment environment) { this.environment = environment; } } public
EnvironmentAwareComponent
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/ClassificationConfigUpdate.java
{ "start": 9138, "end": 10883 }
class ____ implements InferenceConfigUpdate.Builder<Builder, ClassificationConfigUpdate> { private Integer numTopClasses; private String topClassesResultsField; private String resultsField; private Integer numTopFeatureImportanceValues; private PredictionFieldType predictionFieldType; public Builder setNumTopClasses(Integer numTopClasses) { this.numTopClasses = numTopClasses; return this; } public Builder setTopClassesResultsField(String topClassesResultsField) { this.topClassesResultsField = topClassesResultsField; return this; } @Override public Builder setResultsField(String resultsField) { this.resultsField = resultsField; return this; } public Builder setNumTopFeatureImportanceValues(Integer numTopFeatureImportanceValues) { this.numTopFeatureImportanceValues = numTopFeatureImportanceValues; return this; } public Builder setPredictionFieldType(PredictionFieldType predictionFieldtype) { this.predictionFieldType = predictionFieldtype; return this; } private Builder setPredictionFieldType(String predictionFieldType) { return setPredictionFieldType(PredictionFieldType.fromString(predictionFieldType)); } @Override public ClassificationConfigUpdate build() { return new ClassificationConfigUpdate( numTopClasses, resultsField, topClassesResultsField, numTopFeatureImportanceValues, predictionFieldType ); } } }
Builder
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/aggregate/LastValueAggFunction.java
{ "start": 1472, "end": 4199 }
class ____<T> extends BuiltInAggregateFunction<T, RowData> { private final transient DataType valueDataType; public LastValueAggFunction(LogicalType valueType) { this.valueDataType = toInternalDataType(valueType); } // -------------------------------------------------------------------------------------------- // Planning // -------------------------------------------------------------------------------------------- @Override public List<DataType> getArgumentDataTypes() { return Collections.singletonList(valueDataType); } @Override public DataType getAccumulatorDataType() { return DataTypes.ROW( DataTypes.FIELD("lastValue", valueDataType.nullable()), DataTypes.FIELD("lastOrder", DataTypes.BIGINT())) .bridgedTo(RowData.class); } @Override public DataType getOutputDataType() { return valueDataType; } @Override public boolean isDeterministic() { return false; } // -------------------------------------------------------------------------------------------- // Runtime // -------------------------------------------------------------------------------------------- @Override public RowData createAccumulator() { GenericRowData acc = new GenericRowData(2); acc.setField(0, null); acc.setField(1, Long.MIN_VALUE); return acc; } public void accumulate(RowData rowData, Object value) { GenericRowData acc = (GenericRowData) rowData; if (value != null) { acc.setField(0, value); } } public void accumulate(RowData rowData, Object value, Long order) { GenericRowData acc = (GenericRowData) rowData; if (value != null && acc.getLong(1) < order) { acc.setField(0, value); acc.setField(1, order); } } public void accumulate(GenericRowData acc, StringData value) { if (value != null) { accumulate(acc, (Object) ((BinaryStringData) value).copy()); } } public void accumulate(GenericRowData acc, StringData value, Long order) { if (value != null) { accumulate(acc, (Object) ((BinaryStringData) value).copy(), order); } } public void resetAccumulator(RowData rowData) { GenericRowData acc = (GenericRowData) rowData; acc.setField(0, null); acc.setField(1, Long.MIN_VALUE); } @SuppressWarnings("unchecked") @Override public T getValue(RowData rowData) { GenericRowData acc = (GenericRowData) rowData; return (T) acc.getField(0); } }
LastValueAggFunction
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/IdFieldMapper.java
{ "start": 3003, "end": 4669 }
class ____ extends TermBasedFieldType { public AbstractIdFieldType() { super(NAME, IndexType.terms(true, false), true, TextSearchInfo.SIMPLE_MATCH_ONLY, Collections.emptyMap()); } @Override public String typeName() { return CONTENT_TYPE; } @Override public boolean isSearchable() { // The _id field is always searchable. return true; } @Override public Query termsQuery(Collection<?> values, SearchExecutionContext context) { failIfNotIndexed(); List<BytesRef> bytesRefs = values.stream().map(v -> { Object idObject = v; if (idObject instanceof BytesRef) { idObject = ((BytesRef) idObject).utf8ToString(); } return Uid.encodeId(idObject.toString()); }).toList(); return new TermInSetQuery(name(), bytesRefs); } @Override public Query termQuery(Object value, SearchExecutionContext context) { return termsQuery(Arrays.asList(value), context); } @Override public Query existsQuery(SearchExecutionContext context) { return new MatchAllDocsQuery(); } @Override public BlockLoader blockLoader(BlockLoaderContext blContext) { return new BlockStoredFieldsReader.IdBlockLoader(); } @Override public ValueFetcher valueFetcher(SearchExecutionContext context, String format) { return new StoredValueFetcher(context.lookup(), NAME); } } }
AbstractIdFieldType
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/grant/MySqlGrantTest_21.java
{ "start": 969, "end": 2354 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "GRANT INDEX ON mydb.* TO 'someuser'@'somehost';"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); // print(statementList); assertEquals(1, statementList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); String output = SQLUtils.toMySqlString(stmt); assertEquals("GRANT INDEX ON mydb.* TO 'someuser'@'somehost';", // output); // 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(0, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("City"))); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("t2"))); // assertTrue(visitor.getColumns().contains(new Column("t2", "id"))); } }
MySqlGrantTest_21
java
quarkusio__quarkus
extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/traces/NonAppEndpointsDisabledTest.java
{ "start": 631, "end": 2024 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClass(TracerRouter.class) .addClasses(TestSpanExporter.class, TestSpanExporterProvider.class) .addAsResource(new StringAsset(TestSpanExporterProvider.class.getCanonicalName()), "META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider")) .withConfigurationResource("resource-config/application-no-metrics.properties"); @Inject TestSpanExporter testSpanExporter; @Test void testHealthEndpointNotTraced() throws InterruptedException { RestAssured.when().get("/q/health").then() .statusCode(200) .body(containsString("\"status\": \"UP\"")); RestAssured.when().get("/q/health/live").then() .statusCode(200) .body(containsString("\"status\": \"UP\"")); RestAssured.when().get("/q/health/ready").then() .statusCode(200) .body(containsString("\"status\": \"UP\"")); RestAssured.when().get("/tracer").then() .statusCode(200) .body(is("Hello Tracer!")); testSpanExporter.assertSpanCount(2); } }
NonAppEndpointsDisabledTest
java
elastic__elasticsearch
x-pack/plugin/shutdown/qa/multi-node/src/javaRestTest/java/org/elasticsearch/xpack/shutdown/NodeShutdownIT.java
{ "start": 1566, "end": 24455 }
class ____ extends ESRestTestCase { public void testRestartCRUD() throws Exception { checkCRUD(randomFrom("restart", "RESTART"), randomPositiveTimeValue(), null, null); } public void testRemoveCRUD() throws Exception { checkCRUD(randomFrom("remove", "REMOVE"), null, null, null); } public void testReplaceCRUD() throws Exception { checkCRUD(randomFrom("replace", "REPLACE"), null, randomAlphaOfLength(10), null); } public void testSigtermCRUD() throws Exception { checkCRUD(randomFrom("sigterm", "SIGTERM"), null, null, randomPositiveTimeValue()); } public void checkCRUD(String type, @Nullable TimeValue allocationDelay, @Nullable String targetNodeName, @Nullable TimeValue grace) throws Exception { String nodeIdToShutdown = getRandomNodeId(); checkCRUD(nodeIdToShutdown, type, allocationDelay, targetNodeName, true, grace); } @SuppressWarnings("unchecked") public void checkCRUD( String nodeIdToShutdown, String type, @Nullable TimeValue allocationDelay, @Nullable String targetNodeName, boolean delete, @Nullable TimeValue grace ) throws Exception { // Ensure if we do a GET before the cluster metadata is set up, we don't get an error assertNoShuttingDownNodes(nodeIdToShutdown); putNodeShutdown(nodeIdToShutdown, type, allocationDelay, targetNodeName, grace); // Ensure we can read it back { Request getShutdownStatus = new Request("GET", "_nodes/" + nodeIdToShutdown + "/shutdown"); Map<String, Object> statusResponse = responseAsMap(client().performRequest(getShutdownStatus)); List<Map<String, Object>> nodesArray = (List<Map<String, Object>>) statusResponse.get("nodes"); assertThat(nodesArray, hasSize(1)); assertThat(nodesArray.get(0).get("node_id"), equalTo(nodeIdToShutdown)); assertThat((String) nodesArray.get(0).get("type"), equalToIgnoringCase(type)); assertThat(nodesArray.get(0).get("reason"), equalTo(this.getTestName())); assertThat(nodesArray.get(0).get("allocation_delay"), equalsOptionalTimeValue(allocationDelay)); assertThat(nodesArray.get(0).get("target_node_name"), equalTo(targetNodeName)); assertThat(nodesArray.get(0).get("grace_period"), equalsOptionalTimeValue(grace)); } if (delete) { // Delete it and make sure it's deleted Request deleteRequest = new Request("DELETE", "_nodes/" + nodeIdToShutdown + "/shutdown"); assertOK(client().performRequest(deleteRequest)); assertNoShuttingDownNodes(nodeIdToShutdown); } } private static Matcher<Object> equalsOptionalTimeValue(TimeValue timeValue) { return timeValue == null ? nullValue() : equalTo(timeValue.getStringRep()); } public void testPutShutdownIsIdempotentForRestart() throws Exception { checkPutShutdownIdempotency("RESTART"); } public void testPutShutdownIsIdempotentForRemove() throws Exception { checkPutShutdownIdempotency("REMOVE"); } private static void maybeAddMasterNodeTimeout(Request request) { if (randomBoolean()) { request.addParameter(RestUtils.REST_MASTER_TIMEOUT_PARAM, TEST_REQUEST_TIMEOUT.getStringRep()); } } @SuppressWarnings("unchecked") private void checkPutShutdownIdempotency(String type) throws Exception { String nodeIdToShutdown = getRandomNodeId(); // PUT the shutdown once putNodeShutdown(nodeIdToShutdown, type); // now PUT it again, the same and we shouldn't get an error String newReason = "this reason is different"; // Put a shutdown request Request putShutdown = new Request("PUT", "_nodes/" + nodeIdToShutdown + "/shutdown"); maybeAddMasterNodeTimeout(putShutdown); putShutdown.setJsonEntity("{\"type\": \"" + type + "\", \"reason\": \"" + newReason + "\"}"); assertOK(client().performRequest(putShutdown)); // Ensure we can read it back and it has the new reason { Request getShutdownStatus = new Request("GET", "_nodes/" + nodeIdToShutdown + "/shutdown"); maybeAddMasterNodeTimeout(getShutdownStatus); Map<String, Object> statusResponse = responseAsMap(client().performRequest(getShutdownStatus)); List<Map<String, Object>> nodesArray = (List<Map<String, Object>>) statusResponse.get("nodes"); assertThat(nodesArray, hasSize(1)); assertThat(nodesArray.get(0).get("node_id"), equalTo(nodeIdToShutdown)); assertThat(nodesArray.get(0).get("type"), equalTo(type)); assertThat(nodesArray.get(0).get("reason"), equalTo(newReason)); } } public void testPutShutdownCanChangeTypeFromRestartToRemove() throws Exception { checkTypeChange("RESTART", "REMOVE"); } public void testPutShutdownCanChangeTypeFromRemoveToRestart() throws Exception { checkTypeChange("REMOVE", "RESTART"); } @SuppressWarnings("unchecked") public void checkTypeChange(String fromType, String toType) throws Exception { String nodeIdToShutdown = getRandomNodeId(); String type = fromType; // PUT the shutdown once putNodeShutdown(nodeIdToShutdown, type); // now PUT it again, the same and we shouldn't get an error String newReason = "this reason is different"; String newType = toType; // Put a shutdown request Request putShutdown = new Request("PUT", "_nodes/" + nodeIdToShutdown + "/shutdown"); putShutdown.setJsonEntity("{\"type\": \"" + newType + "\", \"reason\": \"" + newReason + "\"}"); assertOK(client().performRequest(putShutdown)); // Ensure we can read it back and it has the new reason { Request getShutdownStatus = new Request("GET", "_nodes/" + nodeIdToShutdown + "/shutdown"); Map<String, Object> statusResponse = responseAsMap(client().performRequest(getShutdownStatus)); List<Map<String, Object>> nodesArray = (List<Map<String, Object>>) statusResponse.get("nodes"); assertThat(nodesArray, hasSize(1)); assertThat(nodesArray.get(0).get("node_id"), equalTo(nodeIdToShutdown)); assertThat(nodesArray.get(0).get("type"), equalTo(newType)); assertThat(nodesArray.get(0).get("reason"), equalTo(newReason)); } } /** * A very basic smoke test to make sure the allocation decider is working. */ @SuppressWarnings("unchecked") public void testAllocationPreventedForRemoval() throws Exception { String nodeIdToShutdown = getRandomNodeId(); putNodeShutdown(nodeIdToShutdown, "REMOVE"); // Create an index with enough replicas to ensure one would normally be allocated to each node final String indexName = "test-idx"; Request createIndexRequest = new Request("PUT", indexName); createIndexRequest.setJsonEntity("{\"settings\": {\"number_of_shards\": 1, \"number_of_replicas\": 3}}"); assertOK(client().performRequest(createIndexRequest)); // Watch to ensure no shards gets allocated to the node that's shutting down assertUnassignedShard(nodeIdToShutdown, indexName); // Now that we know all shards of the test index are assigned except one, // make sure it's unassigned because of the allocation decider. Request allocationExplainRequest = new Request("GET", "_cluster/allocation/explain"); allocationExplainRequest.setJsonEntity("{\"index\": \"" + indexName + "\", \"shard\": 0, \"primary\": false}"); Map<String, Object> allocationExplainMap = entityAsMap(client().performRequest(allocationExplainRequest)); List<Map<String, Object>> decisions = (List<Map<String, Object>>) allocationExplainMap.get("node_allocation_decisions"); assertThat(decisions, notNullValue()); Optional<Map<String, Object>> maybeDecision = decisions.stream() .filter(decision -> nodeIdToShutdown.equals(decision.get("node_id"))) .findFirst(); assertThat("expected decisions for node, but not found", maybeDecision.isPresent(), is(true)); Map<String, Object> decision = maybeDecision.get(); assertThat("node should have deciders", decision.containsKey("deciders"), is(true)); List<Map<String, Object>> deciders = (List<Map<String, Object>>) decision.get("deciders"); assertThat( "the node_shutdown allocation decider should have decided NO", deciders.stream() .filter(decider -> "node_shutdown".equals(decider.get("decider"))) .allMatch(decider -> "NO".equals(decider.get("decision"))), is(true) ); } /** * Checks that shards properly move off of a node that's marked for removal, including: * 1) A reroute needs to be triggered automatically when the node is registered for shutdown, otherwise shards won't start moving * immediately. * 2) Ensures the status properly comes to rest at COMPLETE after the shards have moved. */ @SuppressWarnings("unchecked") public void testShardsMoveOffRemovingNode() throws Exception { String nodeIdToShutdown = getRandomNodeId(); final String indexName = "test-idx"; Request createIndexRequest = new Request("PUT", indexName); createIndexRequest.setJsonEntity("{\"settings\": {\"number_of_shards\": 4, \"number_of_replicas\": 0}}"); assertOK(client().performRequest(createIndexRequest)); ensureGreen(indexName); // Check to ensure there's a shard on the node we want to shut down Request checkShardsRequest = new Request("GET", "_cat/shards/" + indexName); checkShardsRequest.addParameter("format", "json"); checkShardsRequest.addParameter("h", "index,shard,prirep,id,state"); // Double check that there's actually a shard on the node we want to shut down { List<Object> shardsResponse = entityAsList(client().performRequest(checkShardsRequest)); final long shardsOnNodeToShutDown = shardsResponse.stream() .map(shard -> (Map<String, Object>) shard) .filter(shard -> nodeIdToShutdown.equals(shard.get("id"))) .filter(shard -> "STARTED".equals(shard.get("state"))) .count(); assertThat(shardsOnNodeToShutDown, is(1L)); } // Register the shutdown putNodeShutdown(nodeIdToShutdown, "REMOVE"); // assertBusy waiting for the shard to no longer be on that node assertBusy(() -> { List<Object> shardsResponse = entityAsList(client().performRequest(checkShardsRequest)); final long shardsOnNodeToShutDown = shardsResponse.stream() .map(shard -> (Map<String, Object>) shard) .filter(shard -> nodeIdToShutdown.equals(shard.get("id"))) .filter(shard -> "STARTED".equals(shard.get("state")) || "RELOCATING".equals(shard.get("state"))) .count(); assertThat(shardsOnNodeToShutDown, is(0L)); }); assertBusy(() -> { // Now check the shard migration status Request getStatusRequest = new Request("GET", "_nodes/" + nodeIdToShutdown + "/shutdown"); Response statusResponse = client().performRequest(getStatusRequest); Map<String, Object> status = entityAsMap(statusResponse); assertThat(ObjectPath.eval("nodes.0.shard_migration.status", status), equalTo("COMPLETE")); assertThat(ObjectPath.eval("nodes.0.shard_migration.shard_migrations_remaining", status), equalTo(0)); assertThat(ObjectPath.eval("nodes.0.shard_migration.explanation", status), nullValue()); }); } public void testShardsCanBeAllocatedAfterShutdownDeleted() throws Exception { String nodeIdToShutdown = getRandomNodeId(); putNodeShutdown(nodeIdToShutdown, "REMOVE"); // Create an index with enough replicas to ensure one would normally be allocated to each node final String indexName = "test-idx"; Request createIndexRequest = new Request("PUT", indexName); createIndexRequest.setJsonEntity("{\"settings\": {\"number_of_shards\": 1, \"number_of_replicas\": 3}}"); assertOK(client().performRequest(createIndexRequest)); // Watch to ensure no shards gets allocated to the node that's shutting down assertUnassignedShard(nodeIdToShutdown, indexName); // Delete the shutdown Request deleteRequest = new Request("DELETE", "_nodes/" + nodeIdToShutdown + "/shutdown"); assertOK(client().performRequest(deleteRequest)); assertNoShuttingDownNodes(nodeIdToShutdown); // Check that the shard is assigned now ensureGreen(indexName); } public void testStalledShardMigrationProperlyDetected() throws Exception { String nodeIdToShutdown = getRandomNodeId(); int numberOfShards = randomIntBetween(1, 5); // Create an index, pin the allocation to the node we're about to shut down final String indexName = "test-idx"; Request createIndexRequest = new Request("PUT", indexName); createIndexRequest.setJsonEntity(Strings.format(""" { "settings": { "number_of_shards": %s, "number_of_replicas": 0, "index.routing.allocation.require._id": "%s" } }""", numberOfShards, nodeIdToShutdown)); assertOK(client().performRequest(createIndexRequest)); // Mark the node for shutdown putNodeShutdown(nodeIdToShutdown, "remove"); { // Now check the shard migration status Request getStatusRequest = new Request("GET", "_nodes/" + nodeIdToShutdown + "/shutdown"); Response statusResponse = client().performRequest(getStatusRequest); Map<String, Object> status = entityAsMap(statusResponse); assertThat(ObjectPath.eval("nodes.0.shard_migration.status", status), equalTo("STALLED")); assertThat(ObjectPath.eval("nodes.0.shard_migration.shard_migrations_remaining", status), equalTo(numberOfShards)); assertThat( ObjectPath.eval("nodes.0.shard_migration.explanation", status), allOf( containsString(indexName), containsString("cannot move, see [node_allocation_decision] for details or use the cluster allocation explain API") ) ); assertThat(ObjectPath.eval("nodes.0.shard_migration.node_allocation_decision", status), notNullValue()); } // Now update the allocation requirements to unblock shard relocation Request updateSettingsRequest = new Request("PUT", indexName + "/_settings"); updateSettingsRequest.setJsonEntity("{\"index.routing.allocation.require._id\": null}"); assertOK(client().performRequest(updateSettingsRequest)); assertBusy(() -> { Request getStatusRequest = new Request("GET", "_nodes/" + nodeIdToShutdown + "/shutdown"); Response statusResponse = client().performRequest(getStatusRequest); Map<String, Object> status = entityAsMap(statusResponse); assertThat(ObjectPath.eval("nodes.0.shard_migration.status", status), equalTo("COMPLETE")); assertThat(ObjectPath.eval("nodes.0.shard_migration.shard_migrations_remaining", status), equalTo(0)); assertThat(ObjectPath.eval("nodes.0.shard_migration.explanation", status), nullValue()); }); } /** * Ensures that attempting to delete the status of a node that is not registered for shutdown gives a 404 response code. */ public void testDeleteNodeNotRegisteredForShutdown() throws Exception { Request deleteReq = new Request("DELETE", "_nodes/this-node-doesnt-exist/shutdown"); ResponseException ex = expectThrows(ResponseException.class, () -> client().performRequest(deleteReq)); assertThat(ex.getResponse().getStatusLine().getStatusCode(), is(404)); } @SuppressWarnings("unchecked") private void assertNoShuttingDownNodes(String nodeIdToShutdown) throws IOException { Request getShutdownStatus = new Request("GET", "_nodes/" + nodeIdToShutdown + "/shutdown"); Map<String, Object> statusResponse = responseAsMap(client().performRequest(getShutdownStatus)); List<Map<String, Object>> nodesArray = (List<Map<String, Object>>) statusResponse.get("nodes"); assertThat(nodesArray, empty()); } @SuppressWarnings("unchecked") private void assertUnassignedShard(String nodeIdToShutdown, String indexName) throws Exception { Request checkShardsRequest = new Request("GET", "_cat/shards/" + indexName); checkShardsRequest.addParameter("format", "json"); checkShardsRequest.addParameter("h", "index,shard,prirep,id,state"); assertBusy(() -> { List<Object> shardsResponse = entityAsList(client().performRequest(checkShardsRequest)); int startedShards = 0; int unassignedShards = 0; for (Object shard : shardsResponse) { Map<String, Object> shardMap = (Map<String, Object>) shard; assertThat( "no shards should be assigned to a node shutting down for removal", shardMap.get("id"), not(equalTo(nodeIdToShutdown)) ); if (shardMap.get("id") == null) { unassignedShards++; } else if (nodeIdToShutdown.equals(shardMap.get("id")) == false) { assertThat("all other shards should be started", shardMap.get("state"), equalTo("STARTED")); startedShards++; } } assertThat(unassignedShards, equalTo(1)); assertThat(startedShards, equalTo(3)); }); } private void putNodeShutdown(String nodeIdToShutdown, String type) throws IOException { putNodeShutdown(nodeIdToShutdown, type, null, null, null); } private void putNodeShutdown( String nodeIdToShutdown, String type, @Nullable TimeValue allocationDelay, @Nullable String targetNodeName, @Nullable TimeValue grace ) throws IOException { String reason = this.getTestName(); // Put a shutdown request Request putShutdown = new Request("PUT", "_nodes/" + nodeIdToShutdown + "/shutdown"); maybeAddMasterNodeTimeout(putShutdown); try (XContentBuilder putBody = JsonXContent.contentBuilder()) { putBody.startObject(); { putBody.field("type", type); putBody.field("reason", reason); if (allocationDelay != null) { assertThat("allocation delay parameter is only valid for RESTART-type shutdowns", type, equalToIgnoringCase("restart")); putBody.field("allocation_delay", allocationDelay.getStringRep()); } if (targetNodeName != null) { assertThat("target node name parameter is only valid for REPLACE-type shutdowns", type, equalToIgnoringCase("replace")); putBody.field("target_node_name", targetNodeName); } else { assertThat("target node name is required for REPLACE-type shutdowns", type, not(equalToIgnoringCase("replace"))); } if (grace != null) { assertThat("grace only valid for SIGTERM-type shutdowns", type, equalToIgnoringCase("sigterm")); putBody.field("grace_period", grace.getStringRep()); } } putBody.endObject(); putShutdown.setJsonEntity(Strings.toString(putBody)); } if (type.equalsIgnoreCase("restart") && allocationDelay != null) { assertNull("target node name parameter is only valid for REPLACE-type shutdowns", targetNodeName); try (XContentBuilder putBody = JsonXContent.contentBuilder()) { putBody.startObject(); { putBody.field("type", type); putBody.field("reason", reason); putBody.field("allocation_delay", allocationDelay.getStringRep()); } putBody.endObject(); putShutdown.setJsonEntity(Strings.toString(putBody)); } } else { assertNull("allocation delay parameter is only valid for RESTART-type shutdowns", allocationDelay); try (XContentBuilder putBody = JsonXContent.contentBuilder()) { putBody.startObject(); { putBody.field("type", type); putBody.field("reason", reason); if (targetNodeName != null) { assertThat( "target node name parameter is only valid for REPLACE-type shutdowns", type, equalToIgnoringCase("replace") ); putBody.field("target_node_name", targetNodeName); } if (grace != null) { assertThat("grace only valid for SIGTERM-type shutdowns", type, equalToIgnoringCase("sigterm")); putBody.field("grace_period", grace.getStringRep()); } } putBody.endObject(); putShutdown.setJsonEntity(Strings.toString(putBody)); } } assertOK(client().performRequest(putShutdown)); } @SuppressWarnings("unchecked") private String getRandomNodeId() throws IOException { Request nodesRequest = new Request("GET", "_nodes"); Map<String, Object> nodesResponse = responseAsMap(client().performRequest(nodesRequest)); Map<String, Object> nodesObject = (Map<String, Object>) nodesResponse.get("nodes"); return randomFrom(nodesObject.keySet()); } @Override protected Settings restClientSettings() { String token = basicAuthHeaderValue( System.getProperty("tests.rest.cluster.username"), new SecureString(System.getProperty("tests.rest.cluster.password").toCharArray()) ); return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build(); } }
NodeShutdownIT
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/FirstFloatByTimestampAggregatorFunctionSupplier.java
{ "start": 660, "end": 1730 }
class ____ implements AggregatorFunctionSupplier { public FirstFloatByTimestampAggregatorFunctionSupplier() { } @Override public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() { return FirstFloatByTimestampAggregatorFunction.intermediateStateDesc(); } @Override public List<IntermediateStateDesc> groupingIntermediateStateDesc() { return FirstFloatByTimestampGroupingAggregatorFunction.intermediateStateDesc(); } @Override public FirstFloatByTimestampAggregatorFunction aggregator(DriverContext driverContext, List<Integer> channels) { return FirstFloatByTimestampAggregatorFunction.create(driverContext, channels); } @Override public FirstFloatByTimestampGroupingAggregatorFunction groupingAggregator( DriverContext driverContext, List<Integer> channels) { return FirstFloatByTimestampGroupingAggregatorFunction.create(channels, driverContext); } @Override public String describe() { return FirstFloatByTimestampAggregator.describe(); } }
FirstFloatByTimestampAggregatorFunctionSupplier
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/PrimaryKeyInformation.java
{ "start": 311, "end": 633 }
interface ____ { /** * Obtain the identifier for this PK. * * @return The PK identifier. */ Identifier getPrimaryKeyIdentifier(); /** * Obtain the columns making up the primary key. Returned in sequential order. * * @return The columns */ Iterable<ColumnInformation> getColumns(); }
PrimaryKeyInformation
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/softdelete/ValidationTests.java
{ "start": 1891, "end": 2143 }
class ____ { @Id private Integer id; private String name; } @Entity(name="NoNo") @Table(name="nonos") @SoftDelete(converter = YesNoConverter.class, strategy = SoftDeleteType.ACTIVE) @SQLDelete( sql = "delete from nonos" ) public static
Address
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/function/FailableSupplier.java
{ "start": 906, "end": 1137 }
interface ____ {@link Supplier} that declares a {@link Throwable}. * * @param <T> The type of results supplied by this supplier. * @param <E> The kind of thrown exception or error. * @since 3.11 */ @FunctionalInterface public
like
java
apache__rocketmq
store/src/main/java/org/apache/rocketmq/store/RocksDBMessageStore.java
{ "start": 1263, "end": 1883 }
class ____ extends DefaultMessageStore { public RocksDBMessageStore(final MessageStoreConfig messageStoreConfig, final BrokerStatsManager brokerStatsManager, final MessageArrivingListener messageArrivingListener, final BrokerConfig brokerConfig, final ConcurrentMap<String, TopicConfig> topicConfigTable) throws IOException { super(messageStoreConfig, brokerStatsManager, messageArrivingListener, brokerConfig, topicConfigTable); } @Override public ConsumeQueueStoreInterface createConsumeQueueStore() { return new RocksDBConsumeQueueStore(this); } }
RocksDBMessageStore
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/kstream/Grouped.java
{ "start": 906, "end": 1359 }
class ____ is used to capture the key and value {@link Serde}s and set the part of name used for * repartition topics when performing {@link KStream#groupBy(KeyValueMapper, Grouped)}, {@link * KStream#groupByKey(Grouped)}, or {@link KTable#groupBy(KeyValueMapper, Grouped)} operations. Note * that Kafka Streams does not always create repartition topics for grouping operations. * * @param <K> the key type * @param <V> the value type */ public
that
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/convert/support/IntegerToEnumConverterFactory.java
{ "start": 1035, "end": 1301 }
class ____ implements ConverterFactory<Integer, Enum> { @Override public <T extends Enum> Converter<Integer, T> getConverter(Class<T> targetType) { return new IntegerToEnum(ConversionUtils.getEnumType(targetType)); } private static
IntegerToEnumConverterFactory
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java
{ "start": 26647, "end": 26891 }
interface ____ { @AliasFor(annotation = ControllerAdvice.class) String value() default ""; @AliasFor(annotation = ControllerAdvice.class) String basePackage() default ""; } @ControllerAdvice("com.example") static
RestControllerAdvice
java
apache__camel
components/camel-saga/src/main/java/org/apache/camel/component/saga/SagaConstants.java
{ "start": 931, "end": 1163 }
class ____ { @Metadata(description = "The long running action", javaType = "String") public static final String SAGA_LONG_RUNNING_ACTION = Exchange.SAGA_LONG_RUNNING_ACTION; private SagaConstants() { } }
SagaConstants
java
apache__camel
components/camel-servicenow/camel-servicenow-component/src/main/java/org/apache/camel/component/servicenow/releases/helsinki/HelsinkiServiceNowServiceCatalogCategoriesProcessor.java
{ "start": 1379, "end": 2641 }
class ____ extends AbstractServiceNowProcessor { HelsinkiServiceNowServiceCatalogCategoriesProcessor(ServiceNowEndpoint endpoint) { super(endpoint); addDispatcher(ACTION_RETRIEVE, this::retrieveCategory); } /* * This method retrieves all the information about a requested category. * * Method: * - GET * * URL Format: * - /sn_sc/servicecatalog/categories/{sys_id} */ private void retrieveCategory(Exchange exchange) throws Exception { final Message in = exchange.getIn(); final Class<?> responseModel = getResponseModel(in); final String sysId = getSysID(in); final String apiVersion = getApiVersion(in); Response response = client.reset() .types(MediaType.APPLICATION_JSON_TYPE) .path("sn_sc") .path(apiVersion) .path("servicecatalog") .path("categories") .path(ObjectHelper.notNull(sysId, "sysId")) .query(ServiceNowParams.SYSPARM_VIEW, in) .query(responseModel) .invoke(HttpMethod.GET); setBodyAndHeaders(in, responseModel, response); } }
HelsinkiServiceNowServiceCatalogCategoriesProcessor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/MultipleInheritanceTest.java
{ "start": 2879, "end": 2987 }
class ____ { @EmbeddedId private CarPK id; String name; } @Entity(name = "Car") public static
CarPart
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/accesscontrol/IndicesAccessControl.java
{ "start": 6066, "end": 12064 }
class ____ implements CacheKey { public static final IndexAccessControl ALLOW_ALL = new IndexAccessControl(null, null); private final FieldPermissions fieldPermissions; private final DocumentPermissions documentPermissions; public IndexAccessControl(FieldPermissions fieldPermissions, DocumentPermissions documentPermissions) { this.fieldPermissions = (fieldPermissions == null) ? FieldPermissions.DEFAULT : fieldPermissions; this.documentPermissions = (documentPermissions == null) ? DocumentPermissions.allowAll() : documentPermissions; } /** * @return The allowed fields for this index permissions. */ public FieldPermissions getFieldPermissions() { return fieldPermissions; } /** * @return The allowed documents expressed as a query for this index permission. If <code>null</code> is returned * then this means that there are no document level restrictions */ public DocumentPermissions getDocumentPermissions() { return documentPermissions; } /** * Returns an instance of {@link IndexAccessControl}, where the privileges for {@code this} object are constrained by the privileges * contained in the provided parameter.<br> * Allowed fields for this index permission would be an intersection of allowed fields.<br> * Allowed documents for this index permission would be an intersection of allowed documents.<br> * * @param limitedByIndexAccessControl {@link IndexAccessControl} * @return {@link IndexAccessControl} * @see FieldPermissions#limitFieldPermissions(FieldPermissions) * @see DocumentPermissions#limitDocumentPermissions(DocumentPermissions) */ public IndexAccessControl limitIndexAccessControl(IndexAccessControl limitedByIndexAccessControl) { FieldPermissions constrainedFieldPermissions = getFieldPermissions().limitFieldPermissions( limitedByIndexAccessControl.fieldPermissions ); DocumentPermissions constrainedDocumentPermissions = getDocumentPermissions().limitDocumentPermissions( limitedByIndexAccessControl.getDocumentPermissions() ); return new IndexAccessControl(constrainedFieldPermissions, constrainedDocumentPermissions); } @Override public String toString() { return "IndexAccessControl{" + "fieldPermissions=" + fieldPermissions + ", documentPermissions=" + documentPermissions + '}'; } @Override public void buildCacheKey(StreamOutput out, DlsQueryEvaluationContext context) throws IOException { if (documentPermissions.hasDocumentLevelPermissions()) { out.writeBoolean(true); documentPermissions.buildCacheKey(out, context); } else { out.writeBoolean(false); } if (fieldPermissions.hasFieldLevelSecurity()) { out.writeBoolean(true); fieldPermissions.buildCacheKey(out, context); } else { out.writeBoolean(false); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IndexAccessControl that = (IndexAccessControl) o; return Objects.equals(fieldPermissions, that.fieldPermissions) && Objects.equals(documentPermissions, that.documentPermissions); } @Override public int hashCode() { return Objects.hash(fieldPermissions, documentPermissions); } } /** * Returns a instance of {@link IndicesAccessControl}, where the privileges for {@code this} * object are constrained by the privileges contained in the provided parameter.<br> * * @param limitedByIndicesAccessControl {@link IndicesAccessControl} * @return {@link IndicesAccessControl} */ public IndicesAccessControl limitIndicesAccessControl(IndicesAccessControl limitedByIndicesAccessControl) { if (this instanceof AllowAllIndicesAccessControl) { return limitedByIndicesAccessControl; } else if (limitedByIndicesAccessControl instanceof AllowAllIndicesAccessControl) { return this; } final boolean isGranted; if (this.granted == limitedByIndicesAccessControl.granted) { isGranted = this.granted; } else { isGranted = false; } final Supplier<Map<String, IndexAccessControl>> limitedIndexPermissions = () -> { Set<String> indexes = this.getAllIndexPermissions().keySet(); Set<String> otherIndexes = limitedByIndicesAccessControl.getAllIndexPermissions().keySet(); Set<String> commonIndexes = Sets.intersection(indexes, otherIndexes); Map<String, IndexAccessControl> indexPermissionsMap = Maps.newMapWithExpectedSize(commonIndexes.size()); for (String index : commonIndexes) { IndexAccessControl indexAccessControl = getIndexPermissions(index); IndexAccessControl limitedByIndexAccessControl = limitedByIndicesAccessControl.getIndexPermissions(index); indexPermissionsMap.put(index, indexAccessControl.limitIndexAccessControl(limitedByIndexAccessControl)); } return indexPermissionsMap; }; return new IndicesAccessControl(isGranted, limitedIndexPermissions); } @Override public String toString() { return "IndicesAccessControl{" + "granted=" + granted + ", indexPermissions=" + indexPermissionsSupplier.get() + '}'; } public static IndicesAccessControl allowAll() { return AllowAllIndicesAccessControl.INSTANCE; } private static
IndexAccessControl
java
google__guice
core/test/com/google/inject/example/ClientServiceWithDependencyInjection.java
{ "start": 804, "end": 860 }
interface ____ { void go(); } public static
Service
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 32612, "end": 32977 }
class ____ an abstract one. @Test public void testInheritedAbstractToString() throws Exception { SubAbstractToString instance = SubAbstractToString.create("foo"); String expectedString = omitIdentifiers ? "{foo}" : "SubAbstractToString{string=foo}"; assertThat(instance.toString()).isEqualTo(expectedString); } @AutoValue abstract static
inherits
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/recovery/RecoveryTranslogOperationsRequest.java
{ "start": 903, "end": 3965 }
class ____ extends RecoveryTransportRequest implements RawIndexingDataTransportRequest { private final List<Translog.Operation> operations; private final int totalTranslogOps; private final long maxSeenAutoIdTimestampOnPrimary; private final long maxSeqNoOfUpdatesOrDeletesOnPrimary; private final RetentionLeases retentionLeases; private final long mappingVersionOnPrimary; RecoveryTranslogOperationsRequest( final long recoveryId, final long requestSeqNo, final ShardId shardId, final List<Translog.Operation> operations, final int totalTranslogOps, final long maxSeenAutoIdTimestampOnPrimary, final long maxSeqNoOfUpdatesOrDeletesOnPrimary, final RetentionLeases retentionLeases, final long mappingVersionOnPrimary ) { super(requestSeqNo, recoveryId, shardId); this.operations = operations; this.totalTranslogOps = totalTranslogOps; this.maxSeenAutoIdTimestampOnPrimary = maxSeenAutoIdTimestampOnPrimary; this.maxSeqNoOfUpdatesOrDeletesOnPrimary = maxSeqNoOfUpdatesOrDeletesOnPrimary; this.retentionLeases = retentionLeases; this.mappingVersionOnPrimary = mappingVersionOnPrimary; } public List<Translog.Operation> operations() { return operations; } public int totalTranslogOps() { return totalTranslogOps; } public long maxSeenAutoIdTimestampOnPrimary() { return maxSeenAutoIdTimestampOnPrimary; } public long maxSeqNoOfUpdatesOrDeletesOnPrimary() { return maxSeqNoOfUpdatesOrDeletesOnPrimary; } public RetentionLeases retentionLeases() { return retentionLeases; } /** * Returns the mapping version which is at least as up to date as the mapping version that the primary used to index * the translog operations in this request. If the mapping version on the replica is not older this version, we should not * retry on {@link org.elasticsearch.index.mapper.MapperException}; otherwise we should wait for a new mapping then retry. */ long mappingVersionOnPrimary() { return mappingVersionOnPrimary; } RecoveryTranslogOperationsRequest(StreamInput in) throws IOException { super(in); operations = Translog.readOperations(in, "recovery"); totalTranslogOps = in.readVInt(); maxSeenAutoIdTimestampOnPrimary = in.readZLong(); maxSeqNoOfUpdatesOrDeletesOnPrimary = in.readZLong(); retentionLeases = new RetentionLeases(in); mappingVersionOnPrimary = in.readVLong(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); Translog.writeOperations(out, operations); out.writeVInt(totalTranslogOps); out.writeZLong(maxSeenAutoIdTimestampOnPrimary); out.writeZLong(maxSeqNoOfUpdatesOrDeletesOnPrimary); retentionLeases.writeTo(out); out.writeVLong(mappingVersionOnPrimary); } }
RecoveryTranslogOperationsRequest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/TryProcessorHandleWrappedExceptionTest.java
{ "start": 2186, "end": 2387 }
class ____ implements Processor { @Override public void process(Exchange exchange) { throw new IllegalStateException("Force to fail"); } } private
ProcessorFail
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/Matchers.java
{ "start": 2025, "end": 2224 }
class ____ that * {@code ArgumentSelectionDefectChecker} can avoid reporting duplicate findings that the other * checkers would have found * * @author andrewrice@google.com (Andrew Rice) */ final
so
java
apache__kafka
test-common/test-common-internal-api/src/main/java/org/apache/kafka/common/test/api/Type.java
{ "start": 993, "end": 1028 }
enum ____ { KRAFT, CO_KRAFT; }
Type
java
hibernate__hibernate-orm
hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/oracle/OracleSTNativeSqlTemplates.java
{ "start": 2000, "end": 5165 }
class ____ extends NativeSQLTemplates { public OracleSTNativeSqlTemplates() { sqls.clear(); sqls.put( ST_ASTEXT, "select t.ID, t.GEOM.GET_WKT() as result from %s t" ); sqls.put( ST_GEOMETRYTYPE, "select t.ID, ST_GEOMETRY(t.GEOM).ST_GEOMETRYTYPE() as result from %s t" ); sqls.put( ST_DIMENSION, "select id, ST_GEOMETRY(t.GEOM).ST_DIMENSION() as result from %s t" ); sqls.put( ST_ENVELOPE, "select id, ST_GEOMETRY(t.GEOM).ST_ENVELOPE().geom as result from %s t" ); sqls.put( ST_ASBINARY, "select id, ST_GEOMETRY(t.GEOM).GET_WKB() as result from %s t" ); sqls.put( ST_SRID, "select t.id, ST_GEOMETRY(t.GEOM).ST_SRID() as result from %s t" ); sqls.put( ST_ISEMPTY, "select id, ST_GEOMETRY(t.GEOM).ST_ISEMPTY() as result from %s t" ); sqls.put( ST_ISSIMPLE, "select id, ST_GEOMETRY(t.GEOM).ST_ISSIMPLE() as result from %s t" ); sqls.put( ST_BOUNDARY, "select id, ST_GEOMETRY(t.GEOM).ST_BOUNDARY().Geom as result from %s t" ); sqls.put( ST_OVERLAPS, "select id, ST_GEOMETRY(t.GEOM).ST_OVERLAP(ST_Geometry.FROM_WKT(:filter, 4326)) as result from %s t" ); sqls.put( ST_INTERSECTS, "select id, ST_GEOMETRY(t.GEOM).st_intersects(ST_Geometry.From_WKT(:filter, 4326)) as result from %s t" ); sqls.put( ST_CROSSES, "select id, ST_GEOMETRY(t.GEOM).st_crosses(ST_GEOMETRY.FROM_WKT(:filter, 4326)) as result from %s t" ); sqls.put( ST_CONTAINS, "select id, ST_GEOMETRY(t.GEOM).ST_CONTAINS(ST_GEOMETRY.FROM_WKT(:filter, 4326)) as result from %s t" ); sqls.put( ST_DISJOINT, "select id, ST_GEOMETRY(t.GEOM).ST_DISJOINT(ST_GEOMETRY.FROM_WKT(:filter, 4326)) as result from %s t" ); sqls.put( ST_RELATE, "select id, ST_GEOMETRY(t.GEOM).st_relate(st_geometry.from_wkt(:filter, 4326), 'DETERMINE') as result from %s t" ); sqls.put( ST_TOUCHES, "select id, ST_GEOMETRY(t.GEOM).ST_TOUCHES(ST_GEOMETRY.FROM_WKT(:filter, 4326)) as result from %s t" ); sqls.put( ST_WITHIN, "select id, ST_GEOMETRY(t.GEOM).ST_WITHIN(ST_GEOMETRY.FROM_WKT(:filter, 4326)) as result from %s t" ); sqls.put( ST_EQUALS, "select id, ST_GEOMETRY(t.GEOM).ST_EQUALS( ST_GEOMETRY.FROM_WKT(:filter, 4326)) as result from %s t" ); sqls.put( ST_DISTANCE, "select id, ST_GEOMETRY(t.GEOM).st_distance(ST_Geometry.FROM_WKT(:filter, 4326)) as result from %s t" ); sqls.put( ST_BUFFER, "select id,ST_GEOMETRY(t.GEOM).ST_BUFFER( 2 ).Geom as result from %s t" ); sqls.put( ST_CONVEXHULL, "select id, ST_GEOMETRY(t.GEOM).st_convexhull().Geom as result from %s t" ); sqls.put( ST_DIFFERENCE, "select id, ST_GEOMETRY(t.GEOM).st_difference(ST_GEOMETRY.FROM_WKT(:filter, 4326)).Geom as result from %s t" ); sqls.put( ST_INTERSECTION, "select id, ST_GEOMETRY(t.geom).st_intersection(ST_GEOMETRY.FROM_WKT(:filter, 4326)).Geom as result from %s t" ); sqls.put( ST_SYMDIFFERENCE, "select id, ST_GEOMETRY(t.GEOM).st_symdifference(ST_GEOMETRY.FROM_WKT(:filter, 4326)).Geom as result from %s t" ); sqls.put( ST_UNION, "select id, ST_GEOMETRY(t.geom).st_union(ST_GEOMETRY.FROM_WKT(:filter, 4326)).Geom as result from %s t" ); } }
OracleSTNativeSqlTemplates
java
apache__camel
components/camel-jgroups/src/main/java/org/apache/camel/component/jgroups/JGroupsExpressions.java
{ "start": 983, "end": 1362 }
class ____ { private JGroupsExpressions() { } public static Expression delayIfContextNotStarted(final long delay) { return new ExpressionAdapter() { @Override public Object evaluate(Exchange exchange) { return exchange.getContext().getStatus().isStarted() ? 0 : delay; } }; } }
JGroupsExpressions
java
spring-projects__spring-boot
module/spring-boot-tomcat/src/main/java/org/springframework/boot/tomcat/DisableReferenceClearingContextCustomizer.java
{ "start": 969, "end": 1454 }
class ____ implements TomcatContextCustomizer { @Override public void customize(Context context) { if (!(context instanceof StandardContext standardContext)) { return; } try { standardContext.setClearReferencesRmiTargets(false); standardContext.setClearReferencesThreadLocals(false); } catch (NoSuchMethodError ex) { // Earlier version of Tomcat (probably without // setClearReferencesThreadLocals). Continue. } } }
DisableReferenceClearingContextCustomizer
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/properties/PropertiesComponentOverridePropertiesNonStringTest.java
{ "start": 1052, "end": 2331 }
class ____ extends ContextTestSupport { @Override public boolean isUseRouteBuilder() { return false; } @Test public void testPropertiesComponentEndpoint() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start").to("{{hey}}").to("mock:{{cool.result}}"); } }); context.start(); getMockEndpoint("mock:123").expectedMessageCount(1); getMockEndpoint("mock:hey").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(0); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); context.getPropertiesComponent().setLocation("classpath:org/apache/camel/component/properties/myproperties.properties"); Properties extra = new Properties(); extra.put("cool.result", 123); extra.put("hey", "mock:hey"); context.getPropertiesComponent().setOverrideProperties(extra); return context; } }
PropertiesComponentOverridePropertiesNonStringTest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/data/BooleanVectorFixedBuilder.java
{ "start": 610, "end": 2868 }
class ____ implements BooleanVector.FixedBuilder { private final BlockFactory blockFactory; private final boolean[] values; private final long preAdjustedBytes; /** * The next value to write into. {@code -1} means the vector has already * been built. */ private int nextIndex; private boolean closed; BooleanVectorFixedBuilder(int size, BlockFactory blockFactory) { preAdjustedBytes = ramBytesUsed(size); blockFactory.adjustBreaker(preAdjustedBytes); this.blockFactory = blockFactory; this.values = new boolean[size]; } @Override public BooleanVectorFixedBuilder appendBoolean(boolean value) { values[nextIndex++] = value; return this; } @Override public BooleanVectorFixedBuilder appendBoolean(int idx, boolean value) { values[idx] = value; return this; } private static long ramBytesUsed(int size) { return size == 1 ? ConstantBooleanVector.RAM_BYTES_USED : BooleanArrayVector.BASE_RAM_BYTES_USED + RamUsageEstimator.alignObjectSize( (long) RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + (long) size * Byte.BYTES ); } @Override public long estimatedBytes() { return ramBytesUsed(values.length); } @Override public BooleanVector build() { if (closed) { throw new IllegalStateException("already closed"); } closed = true; BooleanVector vector; if (values.length == 1) { vector = blockFactory.newConstantBooleanBlockWith(values[0], 1, preAdjustedBytes).asVector(); } else { vector = blockFactory.newBooleanArrayVector(values, values.length, preAdjustedBytes); } assert vector.ramBytesUsed() == preAdjustedBytes : "fixed Builders should estimate the exact ram bytes used"; return vector; } @Override public void close() { if (closed == false) { // If nextIndex < 0 we've already built the vector closed = true; blockFactory.adjustBreaker(-preAdjustedBytes); } } public boolean isReleased() { return closed; } }
BooleanVectorFixedBuilder
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigureBefore.java
{ "start": 1640, "end": 1957 }
interface ____ { /** * The auto-configuration classes that should have not yet been applied. * @return the classes */ Class<?>[] value() default {}; /** * The names of the auto-configuration classes that should have not yet been applied. * In the unusual case that an auto-configuration
AutoConfigureBefore
java
apache__camel
components/camel-schematron/src/main/java/org/apache/camel/component/schematron/processor/TemplatesFactory.java
{ "start": 1437, "end": 3028 }
class ____ { private static final TemplatesFactory INSTANCE = new TemplatesFactory(); private static final String[] PIPELINE = new String[] { "iso_dsdl_include.xsl", "iso_abstract_expand.xsl", "iso_svrl_for_xslt2.xsl" }; /** * Singleton constructor */ public static TemplatesFactory newInstance() { return INSTANCE; } /** * Generate the schematron template for given rule. * * @param rules the schematron rules * @param fac the transformer factory. * @return schematron template. */ public Templates getTemplates(final InputStream rules, final TransformerFactory fac) { Node node = null; Source source = new StreamSource(rules); try { for (String template : PIPELINE) { String path = Constants.SCHEMATRON_TEMPLATES_ROOT_DIR .concat("/").concat(template); InputStream xsl = org.apache.camel.util.ObjectHelper.loadResourceAsStream(path); if (xsl == null) { xsl = this.getClass().getClassLoader().getResourceAsStream(path); } Transformer t = fac.newTransformer(new StreamSource(xsl)); DOMResult result = new DOMResult(); t.transform(source, result); source = new DOMSource(node = result.getNode()); } return fac.newTemplates(new DOMSource(node)); } catch (Exception e) { throw new SchematronConfigException(e); } } }
TemplatesFactory
java
dropwizard__dropwizard
dropwizard-jersey/src/main/java/io/dropwizard/jersey/filter/RequestIdFilter.java
{ "start": 532, "end": 874 }
class ____ an "X-Request-Id" HTTP response header and logs the following * information: request method, request path, request ID, response status, * response length (or -1 if not known). * * @see <a href="https://devcenter.heroku.com/articles/http-request-id">Heroku - HTTP Request IDs</a> */ @Provider @Priority(Priorities.USER) public
adds
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintValidationTest.java
{ "start": 858, "end": 1911 }
class ____ { @Test @JiraKey(value = "HHH-4084") public void testUniqueConstraintWithEmptyColumnName() { assertThrows( AnnotationException.class, () -> buildSessionFactory( EmptyColumnNameEntity.class ) ); } @Test public void testUniqueConstraintWithEmptyColumnNameList() { assertThrows( AnnotationException.class, () -> buildSessionFactory( EmptyColumnNameListEntity.class ) ); } @Test public void testUniqueConstraintWithNotExistsColumnName() { buildSessionFactory(NotExistsColumnEntity.class); } private void buildSessionFactory(Class<?> entity) { StandardServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistry(); try { new MetadataSources( serviceRegistry ) .addAnnotatedClass( entity ) .buildMetadata() .buildSessionFactory() .close(); } finally { StandardServiceRegistryBuilder.destroy( serviceRegistry ); } } @Entity @Table(name = "tbl_emptycolumnnameentity", uniqueConstraints = @UniqueConstraint(columnNames = "")) public static
UniqueConstraintValidationTest
java
quarkusio__quarkus
integration-tests/mongodb-client/src/main/java/io/quarkus/it/mongodb/BookCodec.java
{ "start": 303, "end": 2443 }
class ____ implements CollectibleCodec<Book> { private final Codec<Document> documentCodec; public BookCodec() { this.documentCodec = MongoClientSettings.getDefaultCodecRegistry().get(Document.class); } @Override public void encode(BsonWriter writer, Book book, EncoderContext encoderContext) { Document doc = new Document(); doc.put("author", book.getAuthor()); doc.put("title", book.getTitle()); doc.put("categories", book.getCategories()); Document details = new Document(); details.put("summary", book.getDetails().getSummary()); details.put("rating", book.getDetails().getRating()); doc.put("details", details); documentCodec.encode(writer, doc, encoderContext); } @Override public Class<Book> getEncoderClass() { return Book.class; } @Override public Book generateIdIfAbsentFromDocument(Book document) { if (!documentHasId(document)) { document.setId(UUID.randomUUID().toString()); } return document; } @Override public boolean documentHasId(Book document) { return document.getId() != null; } @Override public BsonValue getDocumentId(Book document) { return new BsonString(document.getId()); } @Override public Book decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); Book book = new Book(); if (document.getString("id") != null) { book.setId(document.getString("id")); } book.setTitle(document.getString("title")); book.setAuthor(document.getString("author")); book.setCategories(document.getList("categories", String.class)); BookDetail details = new BookDetail(); Document embedded = document.getEmbedded(Collections.singletonList("details"), Document.class); details.setRating(embedded.getInteger("rating")); details.setSummary(embedded.getString("summary")); book.setDetails(details); return book; } }
BookCodec
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/util/MockUtil.java
{ "start": 2031, "end": 8702 }
class ____ is a good choice in either // of these cases. ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } try { type = loader.loadClass(typeName).asSubclass(MockMaker.class); } catch (Exception e) { throw new IllegalStateException("Failed to load MockMaker: " + mockMaker, e); } return mockMakers.computeIfAbsent( type, t -> { try { return t.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new IllegalStateException( "Failed to construct MockMaker: " + t.getName(), e); } }); } public static TypeMockability typeMockabilityOf(Class<?> type, String mockMaker) { return getMockMaker(mockMaker).isTypeMockable(type); } public static <T> T createMock(MockCreationSettings<T> settings) { MockMaker mockMaker = getMockMaker(settings.getMockMaker()); MockHandler mockHandler = createMockHandler(settings); Object spiedInstance = settings.getSpiedInstance(); T mock; if (spiedInstance != null) { mock = mockMaker .createSpy(settings, mockHandler, (T) spiedInstance) .orElseGet( () -> { T instance = mockMaker.createMock(settings, mockHandler); new LenientCopyTool().copyToMock(spiedInstance, instance); return instance; }); } else { mock = mockMaker.createMock(settings, mockHandler); } return mock; } public static void resetMock(Object mock) { MockHandler oldHandler = getMockHandler(mock); MockCreationSettings settings = oldHandler.getMockSettings(); MockHandler newHandler = createMockHandler(settings); mock = resolve(mock); getMockMaker(settings.getMockMaker()).resetMock(mock, newHandler, settings); } public static MockHandler<?> getMockHandler(Object mock) { MockHandler handler = getMockHandlerOrNull(mock); if (handler != null) { return handler; } else { throw new NotAMockException("Argument should be a mock, but is: " + mock.getClass()); } } public static InvocationContainerImpl getInvocationContainer(Object mock) { return (InvocationContainerImpl) getMockHandler(mock).getInvocationContainer(); } public static boolean isSpy(Object mock) { return isMock(mock) && getMockSettings(mock).getDefaultAnswer() == Mockito.CALLS_REAL_METHODS; } public static boolean isMock(Object mock) { // TODO SF (perf tweak) in our codebase we call mockMaker.getHandler() multiple times // unnecessarily // This is not ideal because getHandler() can be expensive (reflective calls inside mock // maker) // The frequent pattern in the codebase are separate calls to: 1) isMock(mock) then 2) // getMockHandler(mock) // We could replace it with using mockingDetails().isMock() // Let's refactor the codebase and use new mockingDetails() in all relevant places. // Potentially we could also move other methods to MockitoMock, some other candidates: // getInvocationContainer, isSpy, etc. // This also allows us to reuse our public API MockingDetails if (mock == null) { return false; } return getMockHandlerOrNull(mock) != null; } private static MockHandler<?> getMockHandlerOrNull(Object mock) { if (mock == null) { throw new NotAMockException("Argument should be a mock, but is null!"); } mock = resolve(mock); for (MockMaker mockMaker : mockMakers.values()) { MockHandler<?> handler = mockMaker.getHandler(mock); if (handler != null) { assert getMockMaker(handler.getMockSettings().getMockMaker()) == mockMaker; return handler; } } return null; } private static Object resolve(Object mock) { if (mock instanceof Class<?>) { // static mocks are resolved by definition return mock; } for (MockResolver mockResolver : Plugins.getMockResolvers()) { mock = mockResolver.resolve(mock); } return mock; } public static boolean areSameMocks(Object mockA, Object mockB) { return mockA == mockB || resolve(mockA) == resolve(mockB); } public static MockName getMockName(Object mock) { return getMockHandler(mock).getMockSettings().getMockName(); } public static void maybeRedefineMockName(Object mock, String newName) { MockName mockName = getMockName(mock); // TODO SF hacky... MockCreationSettings mockSettings = getMockHandler(mock).getMockSettings(); if (mockName.isDefault() && mockSettings instanceof CreationSettings) { ((CreationSettings) mockSettings).setMockName(new MockNameImpl(newName)); } } public static MockCreationSettings getMockSettings(Object mock) { return getMockHandler(mock).getMockSettings(); } public static <T> MockMaker.StaticMockControl<T> createStaticMock( Class<T> type, MockCreationSettings<T> settings) { MockMaker mockMaker = getMockMaker(settings.getMockMaker()); MockHandler<T> handler = createMockHandler(settings); return mockMaker.createStaticMock(type, settings, handler); } public static <T> MockMaker.ConstructionMockControl<T> createConstructionMock( Class<T> type, Function<MockedConstruction.Context, MockCreationSettings<T>> settingsFactory, MockedConstruction.MockInitializer<T> mockInitializer) { Function<MockedConstruction.Context, MockHandler<T>> handlerFactory = context -> createMockHandler(settingsFactory.apply(context)); return defaultMockMaker.createConstructionMock( type, settingsFactory, handlerFactory, mockInitializer); } public static void clearAllCaches() { for (MockMaker mockMaker : mockMakers.values()) { mockMaker.clearAllCaches(); } } }
loader
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/core/ObservableConverter.java
{ "start": 982, "end": 1318 }
interface ____<@NonNull T, @NonNull R> { /** * Applies a function to the upstream {@link Observable} and returns a converted value of type {@code R}. * * @param upstream the upstream {@code Observable} instance * @return the converted value */ R apply(@NonNull Observable<T> upstream); }
ObservableConverter
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableTakeWhileTest.java
{ "start": 6087, "end": 9428 }
class ____ implements ObservableSource<String> { final Disposable upstream; final String[] values; Thread t; TestObservable(Disposable upstream, String... values) { this.upstream = upstream; this.values = values; } @Override public void subscribe(final Observer<? super String> observer) { System.out.println("TestObservable subscribed to ..."); observer.onSubscribe(upstream); t = new Thread(new Runnable() { @Override public void run() { try { System.out.println("running TestObservable thread"); for (String s : values) { System.out.println("TestObservable onNext: " + s); observer.onNext(s); } observer.onComplete(); } catch (Throwable e) { throw new RuntimeException(e); } } }); System.out.println("starting TestObservable thread"); t.start(); System.out.println("done starting TestObservable thread"); } } @Test public void noUnsubscribeDownstream() { Observable<Integer> source = Observable.range(1, 1000).takeWhile(new Predicate<Integer>() { @Override public boolean test(Integer t1) { return t1 < 2; } }); TestObserver<Integer> to = new TestObserver<>(); source.subscribe(to); to.assertNoErrors(); to.assertValue(1); // 2.0.2 - not anymore // Assert.assertTrue("Not cancelled!", ts.isCancelled()); } @Test public void errorCauseIncludesLastValue() { TestObserverEx<String> to = new TestObserverEx<>(); Observable.just("abc").takeWhile(new Predicate<String>() { @Override public boolean test(String t1) { throw new TestException(); } }).subscribe(to); to.assertTerminated(); to.assertNoValues(); to.assertError(TestException.class); // FIXME last cause value not recorded // assertTrue(ts.getOnErrorEvents().get(0).getCause().getMessage().contains("abc")); } @Test public void dispose() { TestHelper.checkDisposed(PublishSubject.create().takeWhile(Functions.alwaysTrue())); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, ObservableSource<Object>>() { @Override public ObservableSource<Object> apply(Observable<Object> o) throws Exception { return o.takeWhile(Functions.alwaysTrue()); } }); } @Test public void badSource() { new Observable<Integer>() { @Override protected void subscribeActual(Observer<? super Integer> observer) { observer.onSubscribe(Disposable.empty()); observer.onComplete(); observer.onComplete(); } } .takeWhile(Functions.alwaysTrue()) .test() .assertResult(); } }
TestObservable
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cdi/general/hibernatesearch/TheNestedDependentBean.java
{ "start": 551, "end": 1014 }
class ____ { public TheNestedDependentBean() { Monitor.theNestedDependentBean().instantiated(); } public void ensureInitialized() { // Nothing to do: if this method is called, all surrounding proxies have been initialized } @PostConstruct public void postConstruct() { Monitor.theNestedDependentBean().postConstructCalled(); } @PreDestroy public void preDestroy() { Monitor.theNestedDependentBean().preDestroyCalled(); } }
TheNestedDependentBean
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactoryTest.java
{ "start": 956, "end": 2151 }
class ____ { @Test void test() { Assertions.assertInstanceOf( DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("dubbo://"))); Assertions.assertInstanceOf( DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("empty://"))); Assertions.assertInstanceOf( DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("exchange://"))); Assertions.assertInstanceOf( Mock1ExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock1://"))); Assertions.assertInstanceOf( Mock2ExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock2://"))); Assertions.assertInstanceOf( DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock3://"))); } }
IsolationExecutorSupportFactoryTest
java
spring-projects__spring-boot
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Libraries.java
{ "start": 863, "end": 1186 }
interface ____ { /** * Represents no libraries. */ Libraries NONE = (callback) -> { }; /** * Iterate all relevant libraries. * @param callback a callback for each relevant library. * @throws IOException if the operation fails */ void doWithLibraries(LibraryCallback callback) throws IOException; }
Libraries
java
apache__camel
components/camel-aws/camel-aws2-iam/src/generated/java/org/apache/camel/component/aws2/iam/IAM2EndpointConfigurer.java
{ "start": 735, "end": 8595 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { IAM2Endpoint target = (IAM2Endpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": target.getConfiguration().setAccessKey(property(camelContext, java.lang.String.class, value)); return true; case "iamclient": case "iamClient": target.getConfiguration().setIamClient(property(camelContext, software.amazon.awssdk.services.iam.IamClient.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "operation": target.getConfiguration().setOperation(property(camelContext, org.apache.camel.component.aws2.iam.IAM2Operations.class, value)); return true; case "overrideendpoint": case "overrideEndpoint": target.getConfiguration().setOverrideEndpoint(property(camelContext, boolean.class, value)); return true; case "pojorequest": case "pojoRequest": target.getConfiguration().setPojoRequest(property(camelContext, boolean.class, value)); return true; case "profilecredentialsname": case "profileCredentialsName": target.getConfiguration().setProfileCredentialsName(property(camelContext, java.lang.String.class, value)); return true; case "proxyhost": case "proxyHost": target.getConfiguration().setProxyHost(property(camelContext, java.lang.String.class, value)); return true; case "proxyport": case "proxyPort": target.getConfiguration().setProxyPort(property(camelContext, java.lang.Integer.class, value)); return true; case "proxyprotocol": case "proxyProtocol": target.getConfiguration().setProxyProtocol(property(camelContext, software.amazon.awssdk.core.Protocol.class, value)); return true; case "region": target.getConfiguration().setRegion(property(camelContext, java.lang.String.class, value)); return true; case "secretkey": case "secretKey": target.getConfiguration().setSecretKey(property(camelContext, java.lang.String.class, value)); return true; case "sessiontoken": case "sessionToken": target.getConfiguration().setSessionToken(property(camelContext, java.lang.String.class, value)); return true; case "trustallcertificates": case "trustAllCertificates": target.getConfiguration().setTrustAllCertificates(property(camelContext, boolean.class, value)); return true; case "uriendpointoverride": case "uriEndpointOverride": target.getConfiguration().setUriEndpointOverride(property(camelContext, java.lang.String.class, value)); return true; case "usedefaultcredentialsprovider": case "useDefaultCredentialsProvider": target.getConfiguration().setUseDefaultCredentialsProvider(property(camelContext, boolean.class, value)); return true; case "useprofilecredentialsprovider": case "useProfileCredentialsProvider": target.getConfiguration().setUseProfileCredentialsProvider(property(camelContext, boolean.class, value)); return true; case "usesessioncredentials": case "useSessionCredentials": target.getConfiguration().setUseSessionCredentials(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public String[] getAutowiredNames() { return new String[]{"iamClient"}; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": return java.lang.String.class; case "iamclient": case "iamClient": return software.amazon.awssdk.services.iam.IamClient.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "operation": return org.apache.camel.component.aws2.iam.IAM2Operations.class; case "overrideendpoint": case "overrideEndpoint": return boolean.class; case "pojorequest": case "pojoRequest": return boolean.class; case "profilecredentialsname": case "profileCredentialsName": return java.lang.String.class; case "proxyhost": case "proxyHost": return java.lang.String.class; case "proxyport": case "proxyPort": return java.lang.Integer.class; case "proxyprotocol": case "proxyProtocol": return software.amazon.awssdk.core.Protocol.class; case "region": return java.lang.String.class; case "secretkey": case "secretKey": return java.lang.String.class; case "sessiontoken": case "sessionToken": return java.lang.String.class; case "trustallcertificates": case "trustAllCertificates": return boolean.class; case "uriendpointoverride": case "uriEndpointOverride": return java.lang.String.class; case "usedefaultcredentialsprovider": case "useDefaultCredentialsProvider": return boolean.class; case "useprofilecredentialsprovider": case "useProfileCredentialsProvider": return boolean.class; case "usesessioncredentials": case "useSessionCredentials": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { IAM2Endpoint target = (IAM2Endpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": return target.getConfiguration().getAccessKey(); case "iamclient": case "iamClient": return target.getConfiguration().getIamClient(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "operation": return target.getConfiguration().getOperation(); case "overrideendpoint": case "overrideEndpoint": return target.getConfiguration().isOverrideEndpoint(); case "pojorequest": case "pojoRequest": return target.getConfiguration().isPojoRequest(); case "profilecredentialsname": case "profileCredentialsName": return target.getConfiguration().getProfileCredentialsName(); case "proxyhost": case "proxyHost": return target.getConfiguration().getProxyHost(); case "proxyport": case "proxyPort": return target.getConfiguration().getProxyPort(); case "proxyprotocol": case "proxyProtocol": return target.getConfiguration().getProxyProtocol(); case "region": return target.getConfiguration().getRegion(); case "secretkey": case "secretKey": return target.getConfiguration().getSecretKey(); case "sessiontoken": case "sessionToken": return target.getConfiguration().getSessionToken(); case "trustallcertificates": case "trustAllCertificates": return target.getConfiguration().isTrustAllCertificates(); case "uriendpointoverride": case "uriEndpointOverride": return target.getConfiguration().getUriEndpointOverride(); case "usedefaultcredentialsprovider": case "useDefaultCredentialsProvider": return target.getConfiguration().isUseDefaultCredentialsProvider(); case "useprofilecredentialsprovider": case "useProfileCredentialsProvider": return target.getConfiguration().isUseProfileCredentialsProvider(); case "usesessioncredentials": case "useSessionCredentials": return target.getConfiguration().isUseSessionCredentials(); default: return null; } } }
IAM2EndpointConfigurer
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateFunctionTest_2.java
{ "start": 1021, "end": 2565 }
class ____ extends OracleTest { public void test_types() throws Exception { String sql = // "CREATE FUNCTION StockPivot(p refcur_pkg.refcur_t) \n" + " RETURN TickerTypeSet PIPELINED USING StockPivotImpl;\n"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); assertEquals("CREATE FUNCTION StockPivot (\n" + "\tp refcur_pkg.refcur_t\n" + ")\n" + "RETURN TickerTypeSetPIPELINED \n" + "USING StockPivotImpl;", SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE)); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(0, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); // assertTrue(visitor.getColumns().contains(new TableStat.Column("orders", "order_total"))); } }
OracleCreateFunctionTest_2
java
quarkusio__quarkus
extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/DefaultP12TrustStoreWithCredentialsProviderTest.java
{ "start": 974, "end": 2306 }
class ____ { private static final String configuration = """ quarkus.tls.trust-store.p12.path=target/certs/test-credentials-provider-truststore.p12 quarkus.tls.trust-store.credentials-provider.name=tls """; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addClass(MyCredentialProvider.class) .add(new StringAsset(configuration), "application.properties")); @Inject TlsConfigurationRegistry certificates; @Test void test() throws KeyStoreException, CertificateParsingException { TlsConfiguration def = certificates.getDefault().orElseThrow(); assertThat(def.getTrustStoreOptions()).isNotNull(); assertThat(def.getTrustStore()).isNotNull(); X509Certificate certificate = (X509Certificate) def.getTrustStore().getCertificate("test-credentials-provider"); assertThat(certificate).isNotNull(); assertThat(certificate.getSubjectAlternativeNames()).anySatisfy(l -> { assertThat(l.get(0)).isEqualTo(2); assertThat(l.get(1)).isEqualTo("localhost"); }); } @ApplicationScoped public static
DefaultP12TrustStoreWithCredentialsProviderTest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/MaxBooleanAggregator.java
{ "start": 606, "end": 801 }
class ____ { public static boolean init() { return false; } public static boolean combine(boolean current, boolean v) { return current || v; } }
MaxBooleanAggregator
java
quarkusio__quarkus
extensions/elasticsearch-java-client/runtime/src/main/java/io/quarkus/elasticsearch/javaclient/runtime/graalvm/ElasticsearchJavaClientFeature.java
{ "start": 903, "end": 3599 }
class ____ implements Feature { private static final String BUILDER_BASE_CLASS_NAME = "co.elastic.clients.util.WithJsonObjectBuilderBase"; /** * To set this, add `-J-Dio.quarkus.elasticsearch.javaclient.graalvm.diagnostics=true` to the native-image parameters, * e.g. pass this to Maven: * -Dquarkus.native.additional-build-args=-J-Dio.quarkus.elasticsearch.javaclient.graalvm.diagnostics=true */ private static final boolean log = Boolean.getBoolean("io.quarkus.elasticsearch.javaclient.graalvm.diagnostics"); @Override public void beforeAnalysis(BeforeAnalysisAccess access) { Class<?> builderClass = access.findClassByName(BUILDER_BASE_CLASS_NAME); Executable withJsonMethod; try { withJsonMethod = builderClass.getMethod("withJson", JsonParser.class, JsonpMapper.class); } catch (NoSuchMethodException e) { throw new RuntimeException("Could not find " + BUILDER_BASE_CLASS_NAME + "#withJson(...);" + " does the version of Elasticsearch Java Client match the version specified in the Quarkus BOM?"); } access.registerReachabilityHandler(this::onWithJsonReachable, withJsonMethod); } private void onWithJsonReachable(DuringAnalysisAccess access) { // The builder base class' withJson(...) method is reachable. logf("%s#withJson(...) is reachable", BUILDER_BASE_CLASS_NAME); // We don't know on which builder subclass the withJson(...) method is called, // so to be safe we consider every reachable builder subclass. for (Class<?> builderSubClass : access.reachableSubtypes(WithJsonObjectBuilderBase.class)) { enableBuilderWithJson(builderSubClass, access); } } private void enableBuilderWithJson(Class<?> builderSubClass, DuringAnalysisAccess access) { // We don't care about abstract builder classes if (Modifier.isAbstract(builderSubClass.getModifiers())) { // Abstract builder classes may be top-level classes. return; } // When a builder's withJson() method is called, // the implementation will (indirectly) access the enclosing class' // _DESERIALIZER constant field through reflection, // so we need to let GraalVM know. // Best-guess of the built class, given the coding coventions in Elasticsearch Java Client; // ideally we'd resolve generics but it's hard and we don't have the right utils in our dependencies. var builtClass = builderSubClass.getEnclosingClass(); if (builtClass == null) { logf("Could not guess the
ElasticsearchJavaClientFeature
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/QueryTransformers.java
{ "start": 979, "end": 2144 }
class ____ implements QueryTokenStream { private final List<QueryToken> tokens; private final boolean requiresPrimaryAlias; CountSelectionTokenStream(List<QueryToken> tokens, boolean requiresPrimaryAlias) { this.tokens = tokens; this.requiresPrimaryAlias = requiresPrimaryAlias; } static CountSelectionTokenStream create(QueryTokenStream selection) { List<QueryToken> target = new ArrayList<>(selection.size()); boolean skipNext = false; boolean containsNew = false; for (QueryToken token : selection) { if (skipNext) { skipNext = false; continue; } if (token.equals(TOKEN_AS)) { skipNext = true; continue; } if (!token.equals(TOKEN_COMMA) && token.isExpression()) { token = QueryTokens.token(token.value()); } if (!containsNew && token.equals(TOKEN_NEW)) { containsNew = true; } target.add(token); } return new CountSelectionTokenStream(target, containsNew); } /** * Filter constructor expression and return the selection list of the constructor. * * @return the selection list of the constructor without {@code NEW},
CountSelectionTokenStream
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/converter/JacksonJsonMessageConverter.java
{ "start": 7988, "end": 8629 }
class ____: " + conversionHint); } return classes[0]; } /** * Determine the JSON encoding to use for the given content type. * @param contentType the MIME type from the MessageHeaders, if any * @return the JSON encoding to use (never {@code null}) */ protected JsonEncoding getJsonEncoding(@Nullable MimeType contentType) { if (contentType != null && contentType.getCharset() != null) { Charset charset = contentType.getCharset(); for (JsonEncoding encoding : JsonEncoding.values()) { if (charset.name().equals(encoding.getJavaName())) { return encoding; } } } return JsonEncoding.UTF8; } }
argument
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/XjComponentBuilderFactory.java
{ "start": 1364, "end": 1787 }
interface ____ { /** * XJ (camel-xj) * Transform JSON and XML message using a XSLT. * * Category: transformation * Since: 3.0 * Maven coordinates: org.apache.camel:camel-xj * * @return the dsl builder */ static XjComponentBuilder xj() { return new XjComponentBuilderImpl(); } /** * Builder for the XJ component. */
XjComponentBuilderFactory
java
spring-projects__spring-security
itest/misc/src/integration-test/java/org/springframework/security/context/SecurityContextHolderMTTests.java
{ "start": 972, "end": 9554 }
class ____ extends TestCase{ private int errors = 0; private static final int NUM_OPS = 25; private static final int NUM_THREADS = 25; public final void setUp() throws Exception { SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL); } public void testSynchronizationCustomStrategyLoading() { SecurityContextHolder.setStrategyName(InheritableThreadLocalSecurityContextHolderStrategy.class.getName()); assertThat(new SecurityContextHolder().toString().isTrue() .lastIndexOf("SecurityContextHolder[strategy='org.springframework.security.context.InheritableThreadLocalSecurityContextHolderStrategy'") != -1); loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, false, true); assertThat(errors).as("Thread errors detected; review log output for details").isZero(); } public void testSynchronizationGlobal() throws Exception { SecurityContextHolder.clearContext(); SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL); loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, true, false); assertThat(errors).as("Thread errors detected; review log output for details").isZero(); } public void testSynchronizationInheritableThreadLocal() throws Exception { SecurityContextHolder.clearContext(); SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL); loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, false, true); assertThat(errors).as("Thread errors detected; review log output for details").isZero(); } public void testSynchronizationThreadLocal() throws Exception { SecurityContextHolder.clearContext(); SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_THREADLOCAL); loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, false, false); assertThat(errors).as("Thread errors detected; review log output for details").isZero(); } private void startAndRun(Thread[] threads) { // Start them up for (int i = 0; i < threads.length; i++) { threads[i].start(); } // Wait for them to finish while (stillRunning(threads)) { try { Thread.sleep(250); } catch (InterruptedException ignore) {} } } private boolean stillRunning(Thread[] threads) { for (int i = 0; i < threads.length; i++) { if (threads[i].isAlive()) { return true; } } return false; } private void loadStartAndWaitForThreads(boolean topLevelThread, String prefix, int createThreads, boolean expectAllThreadsToUseIdenticalAuthentication, boolean expectChildrenToShareAuthenticationWithParent) { Thread[] threads = new Thread[createThreads]; errors = 0; if (topLevelThread) { // PARENT (TOP-LEVEL) THREAD CREATION if (expectChildrenToShareAuthenticationWithParent) { // An InheritableThreadLocal for (int i = 0; i < threads.length; i++) { if ((i % 2) == 0) { // Don't inject auth into current thread; neither current thread or child will have authentication threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, false, true, null); } else { // Inject auth into current thread, but not child; current thread will have auth, child will also have auth threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, false, true, prefix + "Auth_Parent_" + i); } } } else if (expectAllThreadsToUseIdenticalAuthentication) { // A global SecurityContextHolder.getContext() .setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("GLOBAL_USERNAME", "pass")); for (int i = 0; i < threads.length; i++) { if ((i % 2) == 0) { // Don't inject auth into current thread;both current thread and child will have same authentication threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, true, true, "GLOBAL_USERNAME"); } else { // Inject auth into current thread; current thread will have auth, child will also have auth threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, true, true, "GLOBAL_USERNAME"); } } } else { // A standard ThreadLocal for (int i = 0; i < threads.length; i++) { if ((i % 2) == 0) { // Don't inject auth into current thread; neither current thread or child will have authentication threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, false, false, null); } else { // Inject auth into current thread, but not child; current thread will have auth, child will not have auth threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, false, false, prefix + "Auth_Parent_" + i); } } } } else { // CHILD THREAD CREATION if (expectChildrenToShareAuthenticationWithParent || expectAllThreadsToUseIdenticalAuthentication) { // The children being created are all expected to have security (ie an InheritableThreadLocal/global AND auth was injected into parent) for (int i = 0; i < threads.length; i++) { String expectedUsername = prefix; if (expectAllThreadsToUseIdenticalAuthentication) { expectedUsername = "GLOBAL_USERNAME"; } // Don't inject auth into current thread; the current thread will obtain auth from its parent // NB: As topLevelThread = true, no further child threads will be created threads[i] = makeThread(prefix + "->child->Inherited_Auth_Child_" + i, false, false, expectAllThreadsToUseIdenticalAuthentication, false, expectedUsername); } } else { // The children being created are NOT expected to have security (ie not an InheritableThreadLocal OR auth was not injected into parent) for (int i = 0; i < threads.length; i++) { // Don't inject auth into current thread; neither current thread or child will have authentication // NB: As topLevelThread = true, no further child threads will be created threads[i] = makeThread(prefix + "->child->Unauth_Child_" + i, false, false, false, false, null); } } } // Start and execute the threads startAndRun(threads); } private Thread makeThread(final String threadIdentifier, final boolean topLevelThread, final boolean injectAuthIntoCurrentThread, final boolean expectAllThreadsToUseIdenticalAuthentication, final boolean expectChildrenToShareAuthenticationWithParent, final String expectedUsername) { final Random rnd = new Random(); Thread t = new Thread(new Runnable() { public void run() { if (injectAuthIntoCurrentThread) { // Set authentication in this thread SecurityContextHolder.getContext().setAuthentication(UsernamePasswordAuthenticationToken.authenticated( expectedUsername, "pass")); //System.out.println(threadIdentifier + " - set to " + SecurityContextHolder.getContext().getAuthentication()); } else { //System.out.println(threadIdentifier + " - not set (currently " + SecurityContextHolder.getContext().getAuthentication() + ")"); } // Do some operations in current thread, checking authentication is as expected in the current thread (ie another thread doesn't change it) for (int i = 0; i < NUM_OPS; i++) { String currentUsername = (SecurityContextHolder.getContext().getAuthentication() == null) ? null : SecurityContextHolder.getContext().getAuthentication().getName(); if ((i % 7) == 0) { System.out.println(threadIdentifier + " at " + i + " username " + currentUsername); } try { assertEquals("Failed on iteration " + i + "; Authentication was '" + currentUsername + "' but principal was expected to contain username '" + expectedUsername + "'", expectedUsername, currentUsername); } catch (ComparisonFailure err) { errors++; throw err; } try { Thread.sleep(rnd.nextInt(250)); } catch (InterruptedException ignore) {} } // Load some children threads, checking the authentication is as expected in the children (ie another thread doesn't change it) if (topLevelThread) { // Make four children, but we don't want the children to have any more children (so anti-nature, huh?) if (injectAuthIntoCurrentThread && expectChildrenToShareAuthenticationWithParent) { loadStartAndWaitForThreads(false, threadIdentifier, 4, expectAllThreadsToUseIdenticalAuthentication, true); } else { loadStartAndWaitForThreads(false, threadIdentifier, 4, expectAllThreadsToUseIdenticalAuthentication, false); } } } }, threadIdentifier); return t; } }
SecurityContextHolderMTTests
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/authentication/AnonymousAuthenticationProvider.java
{ "start": 1415, "end": 2651 }
class ____ implements AuthenticationProvider, MessageSourceAware { protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); private String key; public AnonymousAuthenticationProvider(String key) { Assert.hasLength(key, "A Key is required"); this.key = key; } @Override public @Nullable Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; } if (this.key.hashCode() != ((AnonymousAuthenticationToken) authentication).getKeyHash()) { throw new BadCredentialsException(this.messages.getMessage("AnonymousAuthenticationProvider.incorrectKey", "The presented AnonymousAuthenticationToken does not contain the expected key")); } return authentication; } public String getKey() { return this.key; } @Override public void setMessageSource(MessageSource messageSource) { Assert.notNull(messageSource, "messageSource cannot be null"); this.messages = new MessageSourceAccessor(messageSource); } @Override public boolean supports(Class<?> authentication) { return (AnonymousAuthenticationToken.class.isAssignableFrom(authentication)); } }
AnonymousAuthenticationProvider
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/ipc/RPCUtil.java
{ "start": 1237, "end": 5289 }
class ____ { /** * Returns an instance of {@link YarnException}. * @param t instance of Throwable. * @return instance of YarnException. */ public static YarnException getRemoteException(Throwable t) { return new YarnException(t); } /** * Returns an instance of {@link YarnException}. * @param message yarn exception message. * @return instance of YarnException. */ public static YarnException getRemoteException(String message) { return new YarnException(message); } private static <T extends Throwable> T instantiateException( Class<? extends T> cls, RemoteException re) throws RemoteException { try { Constructor<? extends T> cn = cls.getConstructor(String.class); cn.setAccessible(true); T ex = cn.newInstance(re.getMessage()); ex.initCause(re); return ex; // RemoteException contains useful information as against the // java.lang.reflect exceptions. } catch (NoSuchMethodException e) { throw re; } catch (IllegalArgumentException e) { throw re; } catch (SecurityException e) { throw re; } catch (InstantiationException e) { throw re; } catch (IllegalAccessException e) { throw re; } catch (InvocationTargetException e) { throw re; } } private static <T extends YarnException> T instantiateYarnException( Class<? extends T> cls, RemoteException re) throws RemoteException { return instantiateException(cls, re); } private static <T extends IOException> T instantiateIOException( Class<? extends T> cls, RemoteException re) throws RemoteException { return instantiateException(cls, re); } private static <T extends RuntimeException> T instantiateRuntimeException( Class<? extends T> cls, RemoteException re) throws RemoteException { return instantiateException(cls, re); } /** * Utility method that unwraps and returns appropriate exceptions. * * @param se * ServiceException * @return An instance of the actual exception, which will be a subclass of * {@link YarnException} or {@link IOException} * @throws IOException io error occur. * @throws YarnException exceptions from yarn servers. */ public static Void unwrapAndThrowException(ServiceException se) throws IOException, YarnException { Throwable cause = se.getCause(); if (cause == null) { // SE generated by the RPC layer itself. throw new IOException(se); } else { if (cause instanceof RemoteException) { RemoteException re = (RemoteException) cause; Class<?> realClass = null; try { realClass = Class.forName(re.getClassName()); } catch (ClassNotFoundException cnf) { // Assume this to be a new exception type added to YARN. This isn't // absolutely correct since the RPC layer could add an exception as // well. throw instantiateYarnException(YarnException.class, re); } if (YarnException.class.isAssignableFrom(realClass)) { throw instantiateYarnException( realClass.asSubclass(YarnException.class), re); } else if (IOException.class.isAssignableFrom(realClass)) { throw instantiateIOException(realClass.asSubclass(IOException.class), re); } else if (RuntimeException.class.isAssignableFrom(realClass)) { throw instantiateRuntimeException( realClass.asSubclass(RuntimeException.class), re); } else { throw re; } // RemoteException contains useful information as against the // java.lang.reflect exceptions. } else if (cause instanceof IOException) { // RPC Client exception. throw (IOException) cause; } else if (cause instanceof RuntimeException) { // RPC RuntimeException throw (RuntimeException) cause; } else { // Should not be generated. throw new IOException(se); } } } }
RPCUtil
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java
{ "start": 20041, "end": 21361 }
class ____ { @Order(1) @Bean SecurityFilterChain filterChain1(HttpSecurity http) throws Exception { // @formatter:off return http .securityMatcher(pathPattern("/role1/**")) .authorizeHttpRequests((authorize) -> authorize .anyRequest().hasRole("1") ) .build(); // @formatter:on } @Order(2) @Bean SecurityFilterChain filterChain2(HttpSecurity http) throws Exception { // @formatter:off return http .securityMatcher(pathPattern("/role2/**")) .authorizeHttpRequests((authorize) -> authorize .anyRequest().hasRole("2") ) .build(); // @formatter:on } @Order(3) @Bean SecurityFilterChain filterChain3(HttpSecurity http) throws Exception { // @formatter:off return http .securityMatcher(pathPattern("/role3/**")) .authorizeHttpRequests((authorize) -> authorize .anyRequest().hasRole("3") ) .build(); // @formatter:on } @Bean SecurityFilterChain filterChain4(HttpSecurity http) throws Exception { // @formatter:off return http .authorizeHttpRequests((authorize) -> authorize .anyRequest().hasRole("4") ) .build(); // @formatter:on } } @Configuration @EnableWebSecurity @Import(AuthenticationTestConfiguration.class) static
SortedSecurityFilterChainConfig
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchFetchInstantiationTest.java
{ "start": 1252, "end": 2646 }
class ____ { @BeforeAll public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityB entityB = new EntityB( "entity_b" ); session.persist( entityB ); session.persist( new EntityA( 1L, entityB ) ); } ); } @AfterAll public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "delete from EntityA" ).executeUpdate(); session.createMutationQuery( "delete from EntityB" ).executeUpdate(); } ); } @Test public void testNormalSelect(SessionFactoryScope scope) { scope.inTransaction( session -> { final TypedQuery<EntityA> query = session.createQuery( "select t from EntityA t where t.id = ?1", EntityA.class ).setParameter( 1, 1L ); final EntityA result = query.getSingleResult(); assertThat( result.getEntityB().getName() ).isEqualTo( "entity_b" ); } ); } @Test public void testDynamicInstantiation(SessionFactoryScope scope) { scope.inTransaction( session -> { final TypedQuery<MyPojo> query2 = session.createQuery( String.format( "select new %s(t) from EntityA t where t.id = ?1", MyPojo.class.getName() ), MyPojo.class ).setParameter( 1, 1L ); final MyPojo pojo = query2.getSingleResult(); assertThat( pojo.getName() ).isEqualTo( "entity_b" ); } ); } @Entity( name = "EntityA" ) public static
BatchFetchInstantiationTest
java
apache__camel
components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/consumer/integration/pods/KubernetesPodsConsumerClusterwideLabelsIT.java
{ "start": 1974, "end": 3083 }
class ____ extends KubernetesConsumerTestSupport { @Test public void clusterWideLabelsTest() { createPod(ns2, "pod1", Map.of("otherKey", "otherValue")); createPod(ns1, "pod2", LABELS); createPod(ns2, "pod3", LABELS); Awaitility.await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> { final List<String> list = result.getExchanges().stream().map(ex -> ex.getIn().getBody(String.class)).toList(); assertThat(list, allOf(not(hasItem(containsString("pod1"))), hasItem(containsString("pod2")), hasItem(containsString("pod3")))); }); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { fromF("kubernetes-pods://%s?oauthToken=%s&labelKey=%s&labelValue=%s", host, authToken, "testkey", "testvalue") .process(new KubernetesProcessor()) .to(result); } }; } }
KubernetesPodsConsumerClusterwideLabelsIT
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java
{ "start": 8646, "end": 8779 }
class ____ there, in case of * a plain bean instance or a CGLIB proxy. When encountering a JDK dynamic * proxy, the <b>first</b>
name
java
apache__logging-log4j2
log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java
{ "start": 1629, "end": 1817 }
class ____ still correct."); logger.error("Hopefully nobody breaks me!"); logger.atInfo().log("Ignored message contents."); logger.atWarn().log("Verifying the caller
is
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/domain/SqmListPersistentAttribute.java
{ "start": 241, "end": 373 }
interface ____<D, E> extends ListPersistentAttribute<D, E>, SqmPluralPersistentAttribute<D, List<E>, E> { }
SqmListPersistentAttribute
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/observers/AbstractDisposableAutoRelease.java
{ "start": 1931, "end": 3993 }
class ____ extends AtomicReference<Disposable> implements Disposable, LambdaConsumerIntrospection { private static final long serialVersionUID = 8924480688481408726L; final AtomicReference<DisposableContainer> composite; final Consumer<? super Throwable> onError; final Action onComplete; AbstractDisposableAutoRelease( DisposableContainer composite, Consumer<? super Throwable> onError, Action onComplete ) { this.onError = onError; this.onComplete = onComplete; this.composite = new AtomicReference<>(composite); } public final void onError(Throwable t) { if (get() != DisposableHelper.DISPOSED) { lazySet(DisposableHelper.DISPOSED); try { onError.accept(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(new CompositeException(t, e)); } } else { RxJavaPlugins.onError(t); } removeSelf(); } public final void onComplete() { if (get() != DisposableHelper.DISPOSED) { lazySet(DisposableHelper.DISPOSED); try { onComplete.run(); } catch (Throwable e) { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(e); } } removeSelf(); } @Override public final void dispose() { DisposableHelper.dispose(this); removeSelf(); } final void removeSelf() { DisposableContainer c = composite.getAndSet(null); if (c != null) { c.delete(this); } } @Override public final boolean isDisposed() { return DisposableHelper.isDisposed(get()); } public final void onSubscribe(Disposable d) { DisposableHelper.setOnce(this, d); } @Override public final boolean hasCustomOnError() { return onError != Functions.ON_ERROR_MISSING; } }
AbstractDisposableAutoRelease
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/cli/util/ErasureCodingCliCmdExecutor.java
{ "start": 945, "end": 1395 }
class ____ extends CommandExecutor { protected String namenode = null; protected ECAdmin admin = null; public ErasureCodingCliCmdExecutor(String namenode, ECAdmin admin) { this.namenode = namenode; this.admin = admin; } @Override protected int execute(final String cmd) throws Exception { String[] args = getCommandAsArgs(cmd, "NAMENODE", this.namenode); return ToolRunner.run(admin, args); } }
ErasureCodingCliCmdExecutor
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/ast/AccessorUtilsTests.java
{ "start": 3610, "end": 3646 }
class ____ implements Animal { } }
Dog
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java
{ "start": 29386, "end": 30921 }
class ____ implements Matcher { private static final byte[] NO_DELIMITER = new byte[0]; private final NestedMatcher[] matchers; byte[] longestDelimiter = NO_DELIMITER; CompositeMatcher(byte[][] delimiters) { this.matchers = initMatchers(delimiters); } private static NestedMatcher[] initMatchers(byte[][] delimiters) { NestedMatcher[] matchers = new NestedMatcher[delimiters.length]; for (int i = 0; i < delimiters.length; i++) { matchers[i] = createMatcher(delimiters[i]); } return matchers; } @Override public int match(DataBuffer dataBuffer) { this.longestDelimiter = NO_DELIMITER; for (int pos = dataBuffer.readPosition(); pos < dataBuffer.writePosition(); pos++) { byte b = dataBuffer.getByte(pos); for (NestedMatcher matcher : this.matchers) { if (matcher.match(b) && matcher.delimiter().length > this.longestDelimiter.length) { this.longestDelimiter = matcher.delimiter(); } } if (this.longestDelimiter != NO_DELIMITER) { reset(); return pos; } } return -1; } @Override public byte[] delimiter() { Assert.state(this.longestDelimiter != NO_DELIMITER, "'delimiter' not set"); return this.longestDelimiter; } @Override public void reset() { for (NestedMatcher matcher : this.matchers) { matcher.reset(); } } } /** * Matcher that can be nested within {@link CompositeMatcher} where multiple * matchers advance together using the same index, one byte at a time. */ private
CompositeMatcher
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterFunctionStatement.java
{ "start": 857, "end": 2887 }
class ____ extends SQLStatementImpl implements SQLAlterStatement { private SQLName name; private boolean debug; private boolean reuseSettings; private SQLExpr comment; private boolean languageSql; private boolean containsSql; private SQLExpr sqlSecurity; public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public SQLName getName() { return name; } public void setName(SQLName name) { if (name != null) { name.setParent(this); } this.name = name; } public SQLExpr getComment() { return comment; } public void setComment(SQLExpr comment) { if (comment != null) { comment.setParent(this); } this.comment = comment; } public boolean isReuseSettings() { return reuseSettings; } public void setReuseSettings(boolean x) { this.reuseSettings = x; } public boolean isLanguageSql() { return languageSql; } public void setLanguageSql(boolean languageSql) { this.languageSql = languageSql; } public boolean isContainsSql() { return containsSql; } public void setContainsSql(boolean containsSql) { this.containsSql = containsSql; } public SQLExpr getSqlSecurity() { return sqlSecurity; } public void setSqlSecurity(SQLExpr sqlSecurity) { if (sqlSecurity != null) { sqlSecurity.setParent(this); } this.sqlSecurity = sqlSecurity; } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, name); acceptChild(visitor, comment); acceptChild(visitor, sqlSecurity); } visitor.endVisit(this); } @Override public DDLObjectType getDDLObjectType() { return DDLObjectType.FUNCTION; } }
SQLAlterFunctionStatement
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/execution/ExtensionContextStoreConcurrencyTests.java
{ "start": 860, "end": 1655 }
class ____ { private final AtomicInteger count = new AtomicInteger(); @Test void concurrentAccessToDefaultStoreWithoutParentStore() { // Run the actual test 100 times "for good measure". IntStream.range(1, 100).forEach(i -> { Store store = reset(); // Simulate 100 extensions interacting concurrently with the Store. IntStream.range(1, 100).parallel().forEach(j -> store.computeIfAbsent("key", this::newValue)); assertEquals(1, count.get(), () -> "number of times newValue() was invoked in run #" + i); }); } private String newValue(String key) { count.incrementAndGet(); return "value"; } private Store reset() { count.set(0); return new NamespaceAwareStore(new NamespacedHierarchicalStore<>(null), Namespace.GLOBAL); } }
ExtensionContextStoreConcurrencyTests
java
netty__netty
transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollRecvByteAllocatorHandle.java
{ "start": 976, "end": 2552 }
class ____ extends DelegatingHandle implements ExtendedHandle { private final PreferredDirectByteBufAllocator preferredDirectByteBufAllocator = new PreferredDirectByteBufAllocator(); private final UncheckedBooleanSupplier defaultMaybeMoreDataSupplier = new UncheckedBooleanSupplier() { @Override public boolean get() { return maybeMoreDataToRead(); } }; private boolean receivedRdHup; EpollRecvByteAllocatorHandle(ExtendedHandle handle) { super(handle); } final void receivedRdHup() { receivedRdHup = true; } final boolean isReceivedRdHup() { return receivedRdHup; } boolean maybeMoreDataToRead() { return lastBytesRead() == attemptedBytesRead(); } @Override public final ByteBuf allocate(ByteBufAllocator alloc) { // We need to ensure we always allocate a direct ByteBuf as we can only use a direct buffer to read via JNI. preferredDirectByteBufAllocator.updateAllocator(alloc); return delegate().allocate(preferredDirectByteBufAllocator); } @Override public final boolean continueReading(UncheckedBooleanSupplier maybeMoreDataSupplier) { return isReceivedRdHup() || ((ExtendedHandle) delegate()).continueReading(maybeMoreDataSupplier); } @Override public final boolean continueReading() { // We must override the supplier which determines if there maybe more data to read. return continueReading(defaultMaybeMoreDataSupplier); } }
EpollRecvByteAllocatorHandle
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/XdsTestUtils.java
{ "start": 3365, "end": 17302 }
class ____ { private static final Logger log = Logger.getLogger(XdsTestUtils.class.getName()); static final String RDS_NAME = "route-config.googleapis.com"; static final String CLUSTER_NAME = "cluster0"; static final String EDS_NAME = "eds-service-0"; static final String SERVER_LISTENER = "grpc/server?udpa.resource.listening_address="; static final String HTTP_CONNECTION_MANAGER_TYPE_URL = "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3" + ".HttpConnectionManager"; static final Bootstrapper.ServerInfo EMPTY_BOOTSTRAPPER_SERVER_INFO = Bootstrapper.ServerInfo.create( "td.googleapis.com", InsecureChannelCredentials.create(), false, true, false); public static final String ENDPOINT_HOSTNAME = "data-host"; public static final int ENDPOINT_PORT = 1234; static BindableService createLrsService(AtomicBoolean lrsEnded, Queue<LrsRpcCall> loadReportCalls) { return new LoadReportingServiceGrpc.LoadReportingServiceImplBase() { @Override public StreamObserver<LoadStatsRequest> streamLoadStats( StreamObserver<LoadStatsResponse> responseObserver) { assertThat(lrsEnded.get()).isTrue(); lrsEnded.set(false); @SuppressWarnings("unchecked") StreamObserver<LoadStatsRequest> requestObserver = mock(StreamObserver.class); LrsRpcCall call = new LrsRpcCall(requestObserver, responseObserver); Context.current().addListener( new CancellationListener() { @Override public void cancelled(Context context) { lrsEnded.set(true); } }, MoreExecutors.directExecutor()); loadReportCalls.offer(call); return requestObserver; } }; } static boolean matchErrorDetail( com.google.rpc.Status errorDetail, int expectedCode, List<String> expectedMessages) { if (expectedCode != errorDetail.getCode()) { return false; } List<String> errors = Splitter.on('\n').splitToList(errorDetail.getMessage()); if (errors.size() != expectedMessages.size()) { return false; } for (int i = 0; i < errors.size(); i++) { if (!errors.get(i).startsWith(expectedMessages.get(i))) { return false; } } return true; } static void setAdsConfig(XdsTestControlPlaneService service, String serverName) { setAdsConfig(service, serverName, RDS_NAME, CLUSTER_NAME, EDS_NAME, ENDPOINT_HOSTNAME, ENDPOINT_PORT); } static void setAdsConfig(XdsTestControlPlaneService service, String serverName, String rdsName, String clusterName, String edsName, String endpointHostname, int endpointPort) { Listener serverListener = ControlPlaneRule.buildServerListener(); Listener clientListener = ControlPlaneRule.buildClientListener(serverName, rdsName); service.setXdsConfig(ADS_TYPE_URL_LDS, ImmutableMap.of(SERVER_LISTENER, serverListener, serverName, clientListener)); RouteConfiguration routeConfig = buildRouteConfiguration(serverName, rdsName, clusterName); service.setXdsConfig(ADS_TYPE_URL_RDS, ImmutableMap.of(rdsName, routeConfig));; Cluster cluster = ControlPlaneRule.buildCluster(clusterName, edsName); service.setXdsConfig(ADS_TYPE_URL_CDS, ImmutableMap.<String, Message>of(clusterName, cluster)); ClusterLoadAssignment clusterLoadAssignment = ControlPlaneRule.buildClusterLoadAssignment( "127.0.0.11", endpointHostname, endpointPort, edsName); service.setXdsConfig(ADS_TYPE_URL_EDS, ImmutableMap.<String, Message>of(edsName, clusterLoadAssignment)); log.log(Level.FINE, String.format("Set ADS config for %s with address %s:%d", serverName, endpointHostname, endpointPort)); } static String getEdsNameForCluster(String clusterName) { return "eds_" + clusterName; } static void setAggregateCdsConfig(XdsTestControlPlaneService service, String serverName, String clusterName, List<String> children) { Map<String, Message> clusterMap = new HashMap<>(); ClusterConfig rootConfig = ClusterConfig.newBuilder().addAllClusters(children).build(); Cluster.CustomClusterType type = Cluster.CustomClusterType.newBuilder() .setName(XdsClusterResource.AGGREGATE_CLUSTER_TYPE_NAME) .setTypedConfig(Any.pack(rootConfig)) .build(); Cluster.Builder builder = Cluster.newBuilder().setName(clusterName).setClusterType(type); builder.setLbPolicy(Cluster.LbPolicy.ROUND_ROBIN); Cluster cluster = builder.build(); clusterMap.put(clusterName, cluster); for (String child : children) { Cluster childCluster = ControlPlaneRule.buildCluster(child, getEdsNameForCluster(child)); clusterMap.put(child, childCluster); } service.setXdsConfig(ADS_TYPE_URL_CDS, clusterMap); Map<String, Message> edsMap = new HashMap<>(); for (String child : children) { ClusterLoadAssignment clusterLoadAssignment = ControlPlaneRule.buildClusterLoadAssignment( "127.0.0.16", ENDPOINT_HOSTNAME, ENDPOINT_PORT, getEdsNameForCluster(child)); edsMap.put(getEdsNameForCluster(child), clusterLoadAssignment); } service.setXdsConfig(ADS_TYPE_URL_EDS, edsMap); } static void addAggregateToExistingConfig(XdsTestControlPlaneService service, String rootName, List<String> children) { Map<String, Message> clusterMap = new HashMap<>(service.getCurrentConfig(ADS_TYPE_URL_CDS)); if (clusterMap.containsKey(rootName)) { throw new IllegalArgumentException("Root cluster " + rootName + " already exists"); } ClusterConfig rootConfig = ClusterConfig.newBuilder().addAllClusters(children).build(); Cluster.CustomClusterType type = Cluster.CustomClusterType.newBuilder() .setName(XdsClusterResource.AGGREGATE_CLUSTER_TYPE_NAME) .setTypedConfig(Any.pack(rootConfig)) .build(); Cluster.Builder builder = Cluster.newBuilder().setName(rootName).setClusterType(type); builder.setLbPolicy(Cluster.LbPolicy.ROUND_ROBIN); Cluster cluster = builder.build(); clusterMap.put(rootName, cluster); for (String child : children) { if (clusterMap.containsKey(child)) { continue; } Cluster childCluster = ControlPlaneRule.buildCluster(child, getEdsNameForCluster(child)); clusterMap.put(child, childCluster); } service.setXdsConfig(ADS_TYPE_URL_CDS, clusterMap); Map<String, Message> edsMap = new HashMap<>(service.getCurrentConfig(ADS_TYPE_URL_EDS)); for (String child : children) { if (edsMap.containsKey(getEdsNameForCluster(child))) { continue; } ClusterLoadAssignment clusterLoadAssignment = ControlPlaneRule.buildClusterLoadAssignment( "127.0.0.15", ENDPOINT_HOSTNAME, ENDPOINT_PORT, getEdsNameForCluster(child)); edsMap.put(getEdsNameForCluster(child), clusterLoadAssignment); } service.setXdsConfig(ADS_TYPE_URL_EDS, edsMap); } static XdsConfig getDefaultXdsConfig(String serverHostName) throws XdsResourceType.ResourceInvalidException, IOException { XdsConfig.XdsConfigBuilder builder = new XdsConfig.XdsConfigBuilder(); Filter.NamedFilterConfig routerFilterConfig = new Filter.NamedFilterConfig( "terminal-filter", RouterFilter.ROUTER_CONFIG); HttpConnectionManager httpConnectionManager = HttpConnectionManager.forRdsName( 0L, RDS_NAME, Collections.singletonList(routerFilterConfig)); XdsListenerResource.LdsUpdate ldsUpdate = XdsListenerResource.LdsUpdate.forApiListener(httpConnectionManager); RouteConfiguration routeConfiguration = buildRouteConfiguration(serverHostName, RDS_NAME, CLUSTER_NAME); XdsResourceType.Args args = new XdsResourceType.Args( EMPTY_BOOTSTRAPPER_SERVER_INFO, "0", "0", null, null, null); XdsRouteConfigureResource.RdsUpdate rdsUpdate = XdsRouteConfigureResource.getInstance().doParse(args, routeConfiguration); // Take advantage of knowing that there is only 1 virtual host in the route configuration assertThat(rdsUpdate.virtualHosts).hasSize(1); VirtualHost virtualHost = rdsUpdate.virtualHosts.get(0); // Need to create endpoints to create locality endpoints map to create edsUpdate Map<Locality, LocalityLbEndpoints> lbEndpointsMap = new HashMap<>(); LbEndpoint lbEndpoint = LbEndpoint.create( "127.0.0.11", ENDPOINT_PORT, 0, true, ENDPOINT_HOSTNAME, ImmutableMap.of()); lbEndpointsMap.put( Locality.create("", "", ""), LocalityLbEndpoints.create(ImmutableList.of(lbEndpoint), 10, 0, ImmutableMap.of())); // Need to create EdsUpdate to create CdsUpdate to create XdsClusterConfig for builder XdsEndpointResource.EdsUpdate edsUpdate = new XdsEndpointResource.EdsUpdate( EDS_NAME, lbEndpointsMap, Collections.emptyList()); XdsClusterResource.CdsUpdate cdsUpdate = XdsClusterResource.CdsUpdate.forEds( CLUSTER_NAME, EDS_NAME, null, null, null, null, false, null) .lbPolicyConfig(getWrrLbConfigAsMap()).build(); XdsConfig.XdsClusterConfig clusterConfig = new XdsConfig.XdsClusterConfig( CLUSTER_NAME, cdsUpdate, new EndpointConfig(StatusOr.fromValue(edsUpdate))); builder .setListener(ldsUpdate) .setRoute(rdsUpdate) .setVirtualHost(virtualHost) .addCluster(CLUSTER_NAME, StatusOr.fromValue(clusterConfig)); return builder.build(); } static Map<Locality, LocalityLbEndpoints> createMinimalLbEndpointsMap(String serverAddress) { Map<Locality, LocalityLbEndpoints> lbEndpointsMap = new HashMap<>(); LbEndpoint lbEndpoint = LbEndpoint.create( serverAddress, ENDPOINT_PORT, 0, true, ENDPOINT_HOSTNAME, ImmutableMap.of()); lbEndpointsMap.put( Locality.create("", "", ""), LocalityLbEndpoints.create(ImmutableList.of(lbEndpoint), 10, 0, ImmutableMap.of())); return lbEndpointsMap; } @SuppressWarnings("unchecked") static ImmutableMap<String, ?> getWrrLbConfigAsMap() throws IOException { String lbConfigStr = "{\"wrr_locality_experimental\" : " + "{ \"childPolicy\" : [{\"round_robin\" : {}}]}}"; return ImmutableMap.copyOf((Map<String, ?>) JsonParser.parse(lbConfigStr)); } static RouteConfiguration buildRouteConfiguration(String authority, String rdsName, String clusterName) { return ControlPlaneRule.buildRouteConfiguration(authority, rdsName, clusterName); } static Cluster buildAggCluster(String name, List<String> childNames) { ClusterConfig rootConfig = ClusterConfig.newBuilder().addAllClusters(childNames).build(); Cluster.CustomClusterType type = Cluster.CustomClusterType.newBuilder() .setName(XdsClusterResource.AGGREGATE_CLUSTER_TYPE_NAME) .setTypedConfig(Any.pack(rootConfig)) .build(); Cluster.Builder builder = Cluster.newBuilder().setName(name).setClusterType(type); builder.setLbPolicy(Cluster.LbPolicy.ROUND_ROBIN); Cluster cluster = builder.build(); return cluster; } static void addEdsClusters(Map<String, Message> clusterMap, Map<String, Message> edsMap, String... clusterNames) { for (String clusterName : clusterNames) { String edsName = getEdsNameForCluster(clusterName); Cluster cluster = ControlPlaneRule.buildCluster(clusterName, edsName); clusterMap.put(clusterName, cluster); ClusterLoadAssignment clusterLoadAssignment = ControlPlaneRule.buildClusterLoadAssignment( "127.0.0.13", ENDPOINT_HOSTNAME, ENDPOINT_PORT, edsName); edsMap.put(edsName, clusterLoadAssignment); } } static Listener buildInlineClientListener(String rdsName, String clusterName, String serverName) { HttpFilter httpFilter = HttpFilter.newBuilder() .setName("terminal-filter") .setTypedConfig(Any.pack(Router.newBuilder().build())) .setIsOptional(true) .build(); ApiListener.Builder clientListenerBuilder = ApiListener.newBuilder().setApiListener(Any.pack( io.envoyproxy.envoy.extensions.filters.network.http_connection_manager.v3 .HttpConnectionManager.newBuilder() .setRouteConfig( buildRouteConfiguration(serverName, rdsName, clusterName)) .addAllHttpFilters(Collections.singletonList(httpFilter)) .build(), HTTP_CONNECTION_MANAGER_TYPE_URL)); return Listener.newBuilder() .setName(serverName) .setApiListener(clientListenerBuilder.build()).build(); } public static XdsClient createXdsClient( List<String> serverUris, XdsTransportFactory xdsTransportFactory, FakeClock fakeClock) { return createXdsClient( CommonBootstrapperTestUtils.buildBootStrap(serverUris), xdsTransportFactory, fakeClock, new XdsClientMetricReporter() {}); } /** Calls {@link CommonBootstrapperTestUtils#createXdsClient} with gRPC-specific values. */ public static XdsClient createXdsClient( Bootstrapper.BootstrapInfo bootstrapInfo, XdsTransportFactory xdsTransportFactory, FakeClock fakeClock, XdsClientMetricReporter xdsClientMetricReporter) { return CommonBootstrapperTestUtils.createXdsClient( bootstrapInfo, xdsTransportFactory, fakeClock, new ExponentialBackoffPolicy.Provider(), MessagePrinter.INSTANCE, xdsClientMetricReporter); } /** * Matches a {@link LoadStatsRequest} containing a collection of {@link ClusterStats} with * the same list of clusterName:clusterServiceName pair. */ static
XdsTestUtils
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/IncompatibleArgumentTypeTest.java
{ "start": 8517, "end": 8630 }
class ____<X extends Nothing & Something> { void doSomething(@CompatibleWith("X") Object whatever) {} }
Test
java
apache__flink
flink-test-utils-parent/flink-test-utils/src/main/java/org/apache/flink/test/util/SQLJobSubmission.java
{ "start": 1130, "end": 2108 }
class ____ { private final SQLJobClientMode clientMode; private final List<String> sqlLines; private final List<String> jars; private final Consumer<Map<String, String>> envProcessor; private SQLJobSubmission( SQLJobClientMode clientMode, List<String> sqlLines, List<String> jars, Consumer<Map<String, String>> envProcessor) { this.clientMode = clientMode; this.sqlLines = checkNotNull(sqlLines); this.jars = checkNotNull(jars); this.envProcessor = envProcessor; } public SQLJobClientMode getClientMode() { return clientMode; } public List<String> getJars() { return this.jars; } public List<String> getSqlLines() { return this.sqlLines; } public Consumer<Map<String, String>> getEnvProcessor() { return envProcessor; } /** Builder for the {@link SQLJobSubmission}. */ public static
SQLJobSubmission
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/extension/eventtime/EventTimeWatermarkHandler.java
{ "start": 1919, "end": 7158 }
class ____ { /** number of input of operator, it should between 1 and 2 in current design. */ private final int numOfInput; private final Output<?> output; private final List<EventTimeWithIdleStatus> eventTimePerInput; /** * time service manager is used to advance event time in operator, and it may be null if the * operator is not keyed. */ @Nullable private final InternalTimeServiceManager<?> timeServiceManager; private long lastEmitWatermark = Long.MIN_VALUE; private boolean lastEmitIdleStatus = false; /** A bitset to record whether the watermark has been received from each input. */ private final BitSet hasReceiveWatermarks; public EventTimeWatermarkHandler( int numOfInput, Output<?> output, @Nullable InternalTimeServiceManager<?> timeServiceManager) { checkArgument(numOfInput >= 1 && numOfInput <= 2, "numOfInput should between 1 and 2"); this.numOfInput = numOfInput; this.output = output; this.eventTimePerInput = new ArrayList<>(numOfInput); for (int i = 0; i < numOfInput; i++) { eventTimePerInput.add(new EventTimeWithIdleStatus()); } this.timeServiceManager = timeServiceManager; this.hasReceiveWatermarks = new BitSet(numOfInput); } private EventTimeUpdateStatus processEventTime(long timestamp, int inputIndex) throws Exception { checkState(inputIndex < numOfInput); hasReceiveWatermarks.set(inputIndex); eventTimePerInput.get(inputIndex).setEventTime(timestamp); eventTimePerInput.get(inputIndex).setIdleStatus(false); return tryAdvanceEventTimeAndEmitWatermark(); } private EventTimeUpdateStatus tryAdvanceEventTimeAndEmitWatermark() throws Exception { // if current event time is larger than last emit watermark, emit it long currentEventTime = getCurrentEventTime(); if (currentEventTime > lastEmitWatermark && hasReceiveWatermarks.cardinality() == numOfInput) { output.emitWatermark( new WatermarkEvent( EventTimeExtension.EVENT_TIME_WATERMARK_DECLARATION.newWatermark( currentEventTime), false)); lastEmitWatermark = currentEventTime; if (timeServiceManager != null) { timeServiceManager.advanceWatermark(new Watermark(currentEventTime)); } return EventTimeUpdateStatus.ofUpdatedWatermark(lastEmitWatermark); } return EventTimeUpdateStatus.NO_UPDATE; } private void processEventTimeIdleStatus(boolean isIdle, int inputIndex) { checkState(inputIndex < numOfInput); hasReceiveWatermarks.set(inputIndex); eventTimePerInput.get(inputIndex).setIdleStatus(isIdle); tryEmitEventTimeIdleStatus(); } private void tryEmitEventTimeIdleStatus() { // emit idle status if current idle status is different from last emit boolean inputIdle = isAllInputIdle(); if (inputIdle != lastEmitIdleStatus) { output.emitWatermark( new WatermarkEvent( EventTimeExtension.IDLE_STATUS_WATERMARK_DECLARATION.newWatermark( inputIdle), false)); lastEmitIdleStatus = inputIdle; } } private long getCurrentEventTime() { long currentEventTime = Long.MAX_VALUE; for (EventTimeWithIdleStatus eventTimeWithIdleStatus : eventTimePerInput) { if (!eventTimeWithIdleStatus.isIdle()) { currentEventTime = Math.min(currentEventTime, eventTimeWithIdleStatus.getEventTime()); } } return currentEventTime; } private boolean isAllInputIdle() { boolean allInputIsIdle = true; for (EventTimeWithIdleStatus eventTimeWithIdleStatus : eventTimePerInput) { allInputIsIdle &= eventTimeWithIdleStatus.isIdle(); } return allInputIsIdle; } public long getLastEmitWatermark() { return lastEmitWatermark; } /** * Process EventTimeWatermark/IdleStatusWatermark. * * <p>It's caller's responsibility to check whether the watermark is * EventTimeWatermark/IdleStatusWatermark. * * @return the status of event time watermark update. */ public EventTimeUpdateStatus processWatermark( org.apache.flink.api.common.watermark.Watermark watermark, int inputIndex) throws Exception { if (EventTimeExtension.isEventTimeWatermark(watermark.getIdentifier())) { long timestamp = ((LongWatermark) watermark).getValue(); return this.processEventTime(timestamp, inputIndex); } else if (EventTimeExtension.isIdleStatusWatermark(watermark.getIdentifier())) { boolean isIdle = ((BoolWatermark) watermark).getValue(); this.processEventTimeIdleStatus(isIdle, inputIndex); } return EventTimeUpdateStatus.NO_UPDATE; } /** This
EventTimeWatermarkHandler
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java
{ "start": 6594, "end": 7322 }
class ____ null, the method will be unchanged. Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass); // First try is the method in the target class. TransactionAttribute txAttr = findTransactionAttribute(specificMethod); if (txAttr != null) { return txAttr; } // Second try is the transaction attribute on the target class. txAttr = findTransactionAttribute(specificMethod.getDeclaringClass()); if (txAttr != null && ClassUtils.isUserLevelMethod(method)) { return txAttr; } if (specificMethod != method) { // Fallback is to look at the original method. txAttr = findTransactionAttribute(method); if (txAttr != null) { return txAttr; } // Last fallback is the
is
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client/runtime/src/main/java/io/quarkus/restclient/runtime/graal/ClientHttpEngineBuilder43Replacement.java
{ "start": 881, "end": 1760 }
class ____ implements ClientHttpEngineBuilder { @Alias private ResteasyClientBuilder that; @Substitute public ClientHttpEngineBuilder resteasyClientBuilder(ResteasyClientBuilder resteasyClientBuilder) { that = resteasyClientBuilder; // make sure we only set a context if there is none or one wouldn't be created implicitly if ((that.getSSLContext() == null) && (that.getTrustStore() == null) && (that.getKeyStore() == null)) { try { that.sslContext(SSLContext.getDefault()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } return this; } /** * Unused alias to implement the {@link ClientHttpEngineBuilder} interface */ @Alias public native ClientHttpEngine build(); }
ClientHttpEngineBuilder43Replacement
java
redisson__redisson
redisson/src/main/java/org/redisson/transaction/TransactionalSet.java
{ "start": 1235, "end": 2683 }
class ____<V> extends BaseTransactionalSet<V> { private final RSet<V> set; private final String transactionId; public TransactionalSet(CommandAsyncExecutor commandExecutor, long timeout, List<TransactionalOperation> operations, RSet<V> set, String transactionId) { super(commandExecutor, timeout, operations, set, transactionId); this.set = set; this.transactionId = transactionId; } @Override protected ScanResult<Object> scanIteratorSource(String name, RedisClient client, String startPos, String pattern, int count) { return ((ScanIterator) set).scanIterator(name, client, startPos, pattern, count); } @Override protected RFuture<Set<V>> readAllAsyncSource() { return set.readAllAsync(); } @Override protected TransactionalOperation createAddOperation(V value, long threadId) { return new AddOperation(set, value, lockName, transactionId, threadId); } @Override protected MoveOperation createMoveOperation(String destination, V value, long threadId) { return new MoveOperation(set, destination, threadId, value, transactionId); } @Override protected TransactionalOperation createRemoveOperation(Object value, long threadId) { return new RemoveOperation(set, value, lockName, transactionId, threadId); } }
TransactionalSet