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-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBean.java
{ "start": 9879, "end": 14632 }
class ____ interface. * @param mixIns a Map of entries with target classes (or interface) whose annotations * to effectively override as key and mix-in classes (or interface) whose * annotations are to be "added" to target's annotations as value. * @since 4.1.2 * @see com.fasterxml.jackson.databind.ObjectMapper#addMixInAnnotations(Class, Class) */ public void setMixIns(Map<Class<?>, Class<?>> mixIns) { this.builder.mixIns(mixIns); } /** * Configure custom serializers. Each serializer is registered for the type * returned by {@link JsonSerializer#handledType()}, which must not be {@code null}. * @see #setSerializersByType(Map) */ public void setSerializers(JsonSerializer<?>... serializers) { this.builder.serializers(serializers); } /** * Configure custom serializers for the given types. * @see #setSerializers(JsonSerializer...) */ public void setSerializersByType(Map<Class<?>, JsonSerializer<?>> serializers) { this.builder.serializersByType(serializers); } /** * Configure custom deserializers. Each deserializer is registered for the type * returned by {@link JsonDeserializer#handledType()}, which must not be {@code null}. * @since 4.3 * @see #setDeserializersByType(Map) */ public void setDeserializers(JsonDeserializer<?>... deserializers) { this.builder.deserializers(deserializers); } /** * Configure custom deserializers for the given types. */ public void setDeserializersByType(Map<Class<?>, JsonDeserializer<?>> deserializers) { this.builder.deserializersByType(deserializers); } /** * Shortcut for {@link MapperFeature#AUTO_DETECT_FIELDS} option. */ public void setAutoDetectFields(boolean autoDetectFields) { this.builder.autoDetectFields(autoDetectFields); } /** * Shortcut for {@link MapperFeature#AUTO_DETECT_SETTERS}/ * {@link MapperFeature#AUTO_DETECT_GETTERS}/{@link MapperFeature#AUTO_DETECT_IS_GETTERS} * options. */ public void setAutoDetectGettersSetters(boolean autoDetectGettersSetters) { this.builder.autoDetectGettersSetters(autoDetectGettersSetters); } /** * Shortcut for {@link MapperFeature#DEFAULT_VIEW_INCLUSION} option. * @since 4.1 */ public void setDefaultViewInclusion(boolean defaultViewInclusion) { this.builder.defaultViewInclusion(defaultViewInclusion); } /** * Shortcut for {@link DeserializationFeature#FAIL_ON_UNKNOWN_PROPERTIES} option. * @since 4.1.1 */ public void setFailOnUnknownProperties(boolean failOnUnknownProperties) { this.builder.failOnUnknownProperties(failOnUnknownProperties); } /** * Shortcut for {@link SerializationFeature#FAIL_ON_EMPTY_BEANS} option. */ public void setFailOnEmptyBeans(boolean failOnEmptyBeans) { this.builder.failOnEmptyBeans(failOnEmptyBeans); } /** * Shortcut for {@link SerializationFeature#INDENT_OUTPUT} option. */ public void setIndentOutput(boolean indentOutput) { this.builder.indentOutput(indentOutput); } /** * Define if a wrapper will be used for indexed (List, array) properties or not by * default (only applies to {@link XmlMapper}). * @since 4.3 */ public void setDefaultUseWrapper(boolean defaultUseWrapper) { this.builder.defaultUseWrapper(defaultUseWrapper); } /** * Specify features to enable. * @see com.fasterxml.jackson.core.JsonParser.Feature * @see com.fasterxml.jackson.core.JsonGenerator.Feature * @see com.fasterxml.jackson.databind.SerializationFeature * @see com.fasterxml.jackson.databind.DeserializationFeature * @see com.fasterxml.jackson.databind.MapperFeature */ public void setFeaturesToEnable(Object... featuresToEnable) { this.builder.featuresToEnable(featuresToEnable); } /** * Specify features to disable. * @see com.fasterxml.jackson.core.JsonParser.Feature * @see com.fasterxml.jackson.core.JsonGenerator.Feature * @see com.fasterxml.jackson.databind.SerializationFeature * @see com.fasterxml.jackson.databind.DeserializationFeature * @see com.fasterxml.jackson.databind.MapperFeature */ public void setFeaturesToDisable(Object... featuresToDisable) { this.builder.featuresToDisable(featuresToDisable); } /** * Set a complete list of modules to be registered with the {@link ObjectMapper}. * <p>Note: If this is set, no finding of modules is going to happen - not by * Jackson, and not by Spring either (see {@link #setFindModulesViaServiceLoader}). * As a consequence, specifying an empty list here will suppress any kind of * module detection. * <p>Specify either this or {@link #setModulesToInstall}, not both. * @since 4.0 * @see com.fasterxml.jackson.databind.Module */ public void setModules(List<Module> modules) { this.builder.modules(modules); } /** * Specify one or more modules by class (or
or
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/AbstractFineGrainedSlotManagerITCase.java
{ "start": 17285, "end": 44112 }
enum ____ { BEFORE_FREE, AFTER_FREE } /** * Tests that a resource allocated for one job can be allocated for another job after being * freed. */ private void testResourceCanBeAllocatedForDifferentJobAfterFree( SecondRequirementDeclarationTime secondRequirementDeclarationTime) throws Exception { final CompletableFuture<AllocationID> allocationIdFuture1 = new CompletableFuture<>(); final CompletableFuture<AllocationID> allocationIdFuture2 = new CompletableFuture<>(); final ResourceRequirements resourceRequirements1 = createResourceRequirementsForSingleSlot(); final ResourceRequirements resourceRequirements2 = createResourceRequirementsForSingleSlot(); final TaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder() .setRequestSlotFunction( tuple6 -> { if (!allocationIdFuture1.isDone()) { allocationIdFuture1.complete(tuple6.f2); } else { allocationIdFuture2.complete(tuple6.f2); } return CompletableFuture.completedFuture(Acknowledge.get()); }) .createTestingTaskExecutorGateway(); final ResourceID resourceID = ResourceID.generate(); final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(resourceID, taskExecutorGateway); final SlotReport slotReport = new SlotReport(); new Context() { { runTest( () -> { runInMainThread( () -> { getSlotManager() .registerTaskManager( taskManagerConnection, slotReport, DEFAULT_SLOT_RESOURCE_PROFILE, DEFAULT_SLOT_RESOURCE_PROFILE); getSlotManager() .processResourceRequirements(resourceRequirements1); }); final AllocationID allocationId1 = assertFutureCompleteAndReturn(allocationIdFuture1); TaskManagerSlotInformation slot = getTaskManagerTracker() .getAllocatedOrPendingSlot(allocationId1) .get(); assertThat(resourceRequirements1.getJobId()) .as("The slot has not been allocated to the expected job id.") .isEqualTo(slot.getJobId()); if (secondRequirementDeclarationTime == SecondRequirementDeclarationTime.BEFORE_FREE) { runInMainThread( () -> getSlotManager() .processResourceRequirements( resourceRequirements2)); } // clear resource requirements first so that the freed slot isn't // immediately re-assigned to the job runInMainThread( () -> { getSlotManager() .processResourceRequirements( ResourceRequirements.create( resourceRequirements1.getJobId(), resourceRequirements1 .getTargetAddress(), Collections.emptyList())); getSlotManager() .freeSlot( SlotID.getDynamicSlotID(resourceID), allocationId1); }); if (secondRequirementDeclarationTime == SecondRequirementDeclarationTime.AFTER_FREE) { runInMainThread( () -> getSlotManager() .processResourceRequirements( resourceRequirements2)); } slot = getTaskManagerTracker() .getAllocatedOrPendingSlot( assertFutureCompleteAndReturn( allocationIdFuture2)) .get(); assertThat(resourceRequirements2.getJobId()) .as("The slot has not been allocated to the expected job id.") .isEqualTo(slot.getJobId()); }); } }; } @Test void testRegisterPendingResourceAfterClearingRequirement() throws Exception { final CompletableFuture<AllocationID> allocationIdFuture = new CompletableFuture<>(); final CompletableFuture<Void> allocateResourceFutures = new CompletableFuture<>(); final CompletableFuture<Void> registerFuture = new CompletableFuture<>(); final ResourceRequirements resourceRequirements = createResourceRequirementsForSingleSlot(); final TaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder() .setRequestSlotFunction( tuple6 -> { allocationIdFuture.complete(tuple6.f2); return CompletableFuture.completedFuture(Acknowledge.get()); }) .createTestingTaskExecutorGateway(); final ResourceID resourceID = ResourceID.generate(); final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(resourceID, taskExecutorGateway); final SlotReport slotReport = new SlotReport(); new Context() { { resourceAllocatorBuilder.setDeclareResourceNeededConsumer( (ignored) -> allocateResourceFutures.complete(null)); runTest( () -> { runInMainThread( () -> getSlotManager() .processResourceRequirements( resourceRequirements)); assertFutureCompleteAndReturn(allocateResourceFutures); assertThat(getResourceTracker().getMissingResources()).hasSize(1); runInMainThreadAndWait( () -> getSlotManager() .clearResourceRequirements( resourceRequirements.getJobId())); assertThat(getResourceTracker().getMissingResources()).isEmpty(); runInMainThread( () -> { getSlotManager() .registerTaskManager( taskManagerConnection, slotReport, DEFAULT_TOTAL_RESOURCE_PROFILE, DEFAULT_SLOT_RESOURCE_PROFILE); registerFuture.complete(null); }); assertFutureCompleteAndReturn(registerFuture); assertFutureNotComplete(allocationIdFuture); assertThat(getTaskManagerTracker().getPendingTaskManagers()).isEmpty(); }); } }; } @Test void testRegisterPendingResourceAfterEmptyResourceRequirement() throws Exception { final CompletableFuture<AllocationID> allocationIdFuture = new CompletableFuture<>(); final CompletableFuture<Void> allocateResourceFutures = new CompletableFuture<>(); final CompletableFuture<Void> registerFuture = new CompletableFuture<>(); final ResourceRequirements resourceRequirements = createResourceRequirementsForSingleSlot(); final TaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder() .setRequestSlotFunction( tuple6 -> { allocationIdFuture.complete(tuple6.f2); return CompletableFuture.completedFuture(Acknowledge.get()); }) .createTestingTaskExecutorGateway(); final ResourceID resourceID = ResourceID.generate(); final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(resourceID, taskExecutorGateway); final SlotReport slotReport = new SlotReport(); new Context() { { resourceAllocatorBuilder.setDeclareResourceNeededConsumer( (ignored) -> allocateResourceFutures.complete(null)); runTest( () -> { runInMainThread( () -> getSlotManager() .processResourceRequirements( resourceRequirements)); assertFutureCompleteAndReturn(allocateResourceFutures); runInMainThread( () -> { getSlotManager() .processResourceRequirements( ResourceRequirements.empty( resourceRequirements.getJobId(), resourceRequirements .getTargetAddress())); getSlotManager() .registerTaskManager( taskManagerConnection, slotReport, DEFAULT_TOTAL_RESOURCE_PROFILE, DEFAULT_SLOT_RESOURCE_PROFILE); registerFuture.complete(null); }); assertFutureCompleteAndReturn(registerFuture); assertFutureNotComplete(allocationIdFuture); assertThat(getTaskManagerTracker().getPendingTaskManagers()).isEmpty(); }); } }; } /** * Tests that we only request new resources/containers once we have assigned all pending task * managers. */ @Test void testRequestNewResources() throws Exception { final JobID jobId = new JobID(); final AtomicInteger requestCount = new AtomicInteger(0); final List<CompletableFuture<Void>> allocateResourceFutures = new ArrayList<>(); allocateResourceFutures.add(new CompletableFuture<>()); allocateResourceFutures.add(new CompletableFuture<>()); new Context() { { resourceAllocatorBuilder.setDeclareResourceNeededConsumer( (resourceDeclarations) -> { if (!resourceDeclarations.isEmpty()) { assertThat(requestCount).hasValueLessThan(2); allocateResourceFutures .get(requestCount.getAndIncrement()) .complete(null); } }); runTest( () -> { // the first requirements should be fulfillable with the pending task // managers of the first allocation runInMainThread( () -> getSlotManager() .processResourceRequirements( createResourceRequirements( jobId, DEFAULT_NUM_SLOTS_PER_WORKER))); assertFutureCompleteAndReturn(allocateResourceFutures.get(0)); assertFutureNotComplete(allocateResourceFutures.get(1)); runInMainThread( () -> getSlotManager() .processResourceRequirements( createResourceRequirements( jobId, DEFAULT_NUM_SLOTS_PER_WORKER + 1))); assertFutureCompleteAndReturn(allocateResourceFutures.get(1)); }); } }; } // --------------------------------------------------------------------------------------------- // Slot allocation failure handling // --------------------------------------------------------------------------------------------- /** Tests that if a slot allocation times out we try to allocate another slot. */ @Test void testSlotRequestTimeout() throws Exception { testSlotRequestFailureWithException(new TimeoutException("timeout")); } /** * Tests that the SlotManager retries allocating a slot if the TaskExecutor#requestSlot call * fails. */ @Test void testSlotRequestFailure() throws Exception { testSlotRequestFailureWithException(new SlotAllocationException("Test exception.")); } void testSlotRequestFailureWithException(Exception exception) throws Exception { final JobID jobId = new JobID(); final ResourceRequirements resourceRequirements = createResourceRequirementsForSingleSlot(jobId); final CompletableFuture<Acknowledge> slotRequestFuture1 = new CompletableFuture<>(); final CompletableFuture<Acknowledge> slotRequestFuture2 = CompletableFuture.completedFuture(Acknowledge.get()); final Iterator<CompletableFuture<Acknowledge>> slotRequestFutureIterator = Arrays.asList(slotRequestFuture1, slotRequestFuture2).iterator(); final ArrayBlockingQueue<AllocationID> allocationIds = new ArrayBlockingQueue<>(2); final TestingTaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder() .setRequestSlotFunction( FunctionUtils.uncheckedFunction( requestSlotParameters -> { allocationIds.put(requestSlotParameters.f2); return slotRequestFutureIterator.next(); })) .createTestingTaskExecutorGateway(); final ResourceID resourceId = ResourceID.generate(); final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(resourceId, taskExecutorGateway); final SlotReport slotReport = new SlotReport(); new Context() { { runTest( () -> { runInMainThread( () -> { getSlotManager() .registerTaskManager( taskManagerConnection, slotReport, DEFAULT_TOTAL_RESOURCE_PROFILE, DEFAULT_SLOT_RESOURCE_PROFILE); getSlotManager() .processResourceRequirements(resourceRequirements); }); final AllocationID firstAllocationId = allocationIds.take(); assertThat(allocationIds).isEmpty(); // let the first attempt fail --> this should trigger a second attempt runInMainThread( () -> slotRequestFuture1.completeExceptionally(exception)); final AllocationID secondAllocationId = allocationIds.take(); assertThat(allocationIds).isEmpty(); final TaskManagerSlotInformation slot = getTaskManagerTracker() .getAllocatedOrPendingSlot(secondAllocationId) .get(); assertThat(slot.getJobId()).isEqualTo(jobId); assertThat( getTaskManagerTracker() .getAllocatedOrPendingSlot(firstAllocationId)) .isNotPresent(); }); } }; } // --------------------------------------------------------------------------------------------- // Allocation update // --------------------------------------------------------------------------------------------- /** * Verify that the ack of request slot form unregistered task manager will not cause system * breakdown. */ @Test void testAllocationUpdatesIgnoredIfTaskExecutorUnregistered() throws Exception { final CompletableFuture<Acknowledge> slotRequestFuture = new CompletableFuture<>(); final CompletableFuture<Void> slotRequestCallFuture = new CompletableFuture<>(); final TestingTaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder() .setRequestSlotFunction( ignored -> { slotRequestCallFuture.complete(null); return slotRequestFuture; }) .createTestingTaskExecutorGateway(); // The fatal error handler will exit the system if there is any exceptions in handling the // ack of request slot. We need the security manager to verify that would not happen. final SystemExitTrackingSecurityManager trackingSecurityManager = new SystemExitTrackingSecurityManager(); System.setSecurityManager(trackingSecurityManager); final JobID jobId = new JobID(); final ResourceID taskExecutorResourceId = ResourceID.generate(); final TaskExecutorConnection taskExecutionConnection = new TaskExecutorConnection(taskExecutorResourceId, taskExecutorGateway); final SlotReport slotReport = new SlotReport(); new Context() { { runTest( () -> { runInMainThread( () -> { getSlotManager() .processResourceRequirements( createResourceRequirements(jobId, 1)); getSlotManager() .registerTaskManager( taskExecutionConnection, slotReport, DEFAULT_TOTAL_RESOURCE_PROFILE, DEFAULT_SLOT_RESOURCE_PROFILE); }); assertFutureCompleteAndReturn(slotRequestCallFuture); runInMainThread( () -> { getSlotManager() .unregisterTaskManager( taskExecutionConnection.getInstanceID(), TEST_EXCEPTION); slotRequestFuture.complete(Acknowledge.get()); }); assertThat(trackingSecurityManager.getSystemExitFuture()).isNotDone(); }); } }; System.setSecurityManager(null); } @Test void testAllocationUpdatesIgnoredIfSlotMarkedAsAllocatedAfterSlotReport() throws Exception { final CompletableFuture<AllocationID> allocationIdFuture = new CompletableFuture<>(); final TestingTaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder() // it is important that the returned future is already completed // otherwise it will be cancelled when the task executor is unregistered .setRequestSlotFunction( tuple6 -> { allocationIdFuture.complete(tuple6.f2); return CompletableFuture.completedFuture(Acknowledge.get()); }) .createTestingTaskExecutorGateway(); // The fatal error handler will exit the system if there is any exceptions in handling the // ack of request slot. We need the security manager to verify that would not happen. final SystemExitTrackingSecurityManager trackingSecurityManager = new SystemExitTrackingSecurityManager(); System.setSecurityManager(trackingSecurityManager); final TaskExecutorConnection taskExecutionConnection = new TaskExecutorConnection(ResourceID.generate(), taskExecutorGateway); final SlotReport slotReport = new SlotReport(); new Context() { { runTest( () -> { runInMainThread( () -> { getSlotManager() .processResourceRequirements( createResourceRequirements(new JobID(), 1)); getSlotManager() .registerTaskManager( taskExecutionConnection, slotReport, DEFAULT_TOTAL_RESOURCE_PROFILE, DEFAULT_SLOT_RESOURCE_PROFILE); }); final AllocationID allocationId = assertFutureCompleteAndReturn(allocationIdFuture); runInMainThread( () -> getSlotManager() .reportSlotStatus( taskExecutionConnection.getInstanceID(), new SlotReport( createAllocatedSlotStatus( new JobID(), allocationId, DEFAULT_SLOT_RESOURCE_PROFILE)))); assertThat(trackingSecurityManager.getSystemExitFuture()).isNotDone(); }); } }; System.setSecurityManager(null); } }
SecondRequirementDeclarationTime
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/producer/discovery/ProducerOnClassWithoutBeanDefiningAnnotationTest.java
{ "start": 767, "end": 903 }
class ____ { @Produces String observeString() { return "foo"; } } static
StringProducerMethod
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerDetailsInfoTest.java
{ "start": 1503, "end": 3904 }
class ____ extends RestResponseMarshallingTestBase<TaskManagerDetailsInfo> { private static final Random random = new Random(); @Override protected Class<TaskManagerDetailsInfo> getTestResponseClass() { return TaskManagerDetailsInfo.class; } @Override protected TaskManagerDetailsInfo getTestResponseInstance() throws Exception { final TaskManagerInfoWithSlots taskManagerInfoWithSlots = new TaskManagerInfoWithSlots( TaskManagerInfoTest.createRandomTaskManagerInfo(), Collections.singletonList(new SlotInfo(new JobID(), ResourceProfile.ANY))); final TaskManagerMetricsInfo taskManagerMetricsInfo = createRandomTaskManagerMetricsInfo(); return new TaskManagerDetailsInfo(taskManagerInfoWithSlots, taskManagerMetricsInfo); } static TaskManagerMetricsInfo createRandomTaskManagerMetricsInfo() { final List<TaskManagerMetricsInfo.GarbageCollectorInfo> garbageCollectorsInfo = createRandomGarbageCollectorsInfo(); return new TaskManagerMetricsInfo( random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), random.nextLong(), garbageCollectorsInfo); } static List<TaskManagerMetricsInfo.GarbageCollectorInfo> createRandomGarbageCollectorsInfo() { final int numberGCs = random.nextInt(10); final List<TaskManagerMetricsInfo.GarbageCollectorInfo> garbageCollectorInfos = new ArrayList<>(numberGCs); for (int i = 0; i < numberGCs; i++) { garbageCollectorInfos.add( new TaskManagerMetricsInfo.GarbageCollectorInfo( UUID.randomUUID().toString(), random.nextLong(), random.nextLong())); } return garbageCollectorInfos; } }
TaskManagerDetailsInfoTest
java
quarkusio__quarkus
extensions/config-yaml/runtime/src/main/java/io/quarkus/config/yaml/runtime/YamlConfigBuilder.java
{ "start": 215, "end": 524 }
class ____ implements ConfigBuilder { @Override public SmallRyeConfigBuilder configBuilder(final SmallRyeConfigBuilder builder) { return builder.withSources(new YamlConfigSourceLoader.InFileSystem()) .withSources(new YamlConfigSourceLoader.InClassPath()); } }
YamlConfigBuilder
java
apache__flink
flink-formats/flink-avro/src/main/java/org/apache/flink/formats/avro/SchemaCoder.java
{ "start": 1199, "end": 1519 }
interface ____ { Schema readSchema(InputStream in) throws IOException; void writeSchema(Schema schema, OutputStream out) throws IOException; /** * Provider for {@link SchemaCoder}. It allows creating multiple instances of client in parallel * operators without serializing it. */
SchemaCoder
java
alibaba__druid
core/src/test/java/com/alibaba/druid/sql/parser/CommentTest.java
{ "start": 914, "end": 3346 }
class ____ extends TestCase { public void test_0() throws Exception { String sql = "SELECT /*mark for picman*/ * FROM WP_ALBUM WHERE MEMBER_ID = ? AND ID IN (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; Lexer lexer = new Lexer(sql); for (; ; ) { lexer.nextToken(); Token tok = lexer.token(); if (tok == Token.IDENTIFIER) { System.out.println(tok.name() + "\t\t" + lexer.stringVal()); } else if (tok == Token.MULTI_LINE_COMMENT) { System.out.println(tok.name() + "\t\t" + lexer.stringVal()); } else { System.out.println(tok.name() + "\t\t\t" + tok.name); } if (tok == Token.EOF) { break; } } } public void test_1() throws Exception { String sql = "SELECT /*mark for picman*/ * FROM WP_ALBUM WHERE MEMBER_ID = ? AND ID IN (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; StringBuilder out = new StringBuilder(); OracleOutputVisitor visitor = new OracleOutputVisitor(out); OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); for (SQLStatement statement : statementList) { statement.accept(visitor); visitor.print(";"); visitor.println(); } System.out.println(out.toString()); } public void test_2() throws Exception { String sql = "//hello world\n"; Lexer lexer = new Lexer(sql); lexer.nextToken(); assertEquals("hello world", lexer.stringVal()); sql = "/*hello \nworld*/"; lexer = new Lexer(sql); lexer.nextToken(); assertEquals("hello \nworld", lexer.stringVal()); sql = "--hello world\n"; lexer = new Lexer(sql); lexer.nextToken(); assertEquals("hello world", lexer.stringVal()); } }
CommentTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToDoubleFromBooleanEvaluator.java
{ "start": 3898, "end": 4507 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final Source source; private final EvalOperator.ExpressionEvaluator.Factory bool; public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory bool) { this.source = source; this.bool = bool; } @Override public ToDoubleFromBooleanEvaluator get(DriverContext context) { return new ToDoubleFromBooleanEvaluator(source, bool.get(context), context); } @Override public String toString() { return "ToDoubleFromBooleanEvaluator[" + "bool=" + bool + "]"; } } }
Factory
java
elastic__elasticsearch
x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/AutoFollowCoordinator.java
{ "start": 19724, "end": 52439 }
class ____ { private final String remoteCluster; private final Consumer<List<AutoFollowResult>> statsUpdater; private final Supplier<ClusterState> followerClusterStateSupplier; private final LongSupplier relativeTimeProvider; private final Executor executor; private volatile long lastAutoFollowTimeInMillis = -1; private volatile long metadataVersion = 0; private volatile boolean remoteClusterConnectionMissing = false; volatile boolean removed = false; private volatile CountDown autoFollowPatternsCountDown; private volatile AtomicArray<AutoFollowResult> autoFollowResults; private volatile boolean stop; private volatile List<String> lastActivePatterns = List.of(); AutoFollower( final String remoteCluster, final Consumer<List<AutoFollowResult>> statsUpdater, final Supplier<ClusterState> followerClusterStateSupplier, final LongSupplier relativeTimeProvider, final Executor executor ) { this.remoteCluster = remoteCluster; this.statsUpdater = statsUpdater; this.followerClusterStateSupplier = followerClusterStateSupplier; this.relativeTimeProvider = relativeTimeProvider; this.executor = Objects.requireNonNull(executor); } void start() { if (stop) { LOGGER.trace("auto-follower is stopped for remote cluster [{}]", remoteCluster); return; } if (removed) { // This check exists to avoid two AutoFollower instances a single remote cluster. // (If an auto follow pattern is deleted and then added back quickly enough then // the old AutoFollower instance still sees that there is an auto follow pattern // for the remote cluster it is tracking and will continue to operate, while in // the meantime in updateAutoFollowers() method another AutoFollower instance has been // started for the same remote cluster.) LOGGER.trace("auto-follower instance for cluster [{}] has been removed", remoteCluster); return; } lastAutoFollowTimeInMillis = relativeTimeProvider.getAsLong(); final ClusterState clusterState = followerClusterStateSupplier.get(); final AutoFollowMetadata autoFollowMetadata = clusterState.metadata().getProject().custom(AutoFollowMetadata.TYPE); if (autoFollowMetadata == null) { LOGGER.info("auto-follower for cluster [{}] has stopped, because there is no autofollow metadata", remoteCluster); return; } final List<String> patterns = autoFollowMetadata.getPatterns() .entrySet() .stream() .filter(entry -> entry.getValue().getRemoteCluster().equals(remoteCluster)) .filter(entry -> entry.getValue().isActive()) .map(Map.Entry::getKey) .sorted() .collect(Collectors.toList()); if (patterns.isEmpty()) { LOGGER.info("auto-follower for cluster [{}] has stopped, because there are no more patterns", remoteCluster); return; } this.autoFollowPatternsCountDown = new CountDown(patterns.size()); this.autoFollowResults = new AtomicArray<>(patterns.size()); // keep the list of the last known active patterns for this auto-follower // if the list changed, we explicitly retrieve the last cluster state in // order to avoid timeouts when waiting for the next remote cluster state // version that might never arrive final long nextMetadataVersion = Objects.equals(patterns, lastActivePatterns) ? metadataVersion + 1 : metadataVersion; this.lastActivePatterns = List.copyOf(patterns); final Thread thread = Thread.currentThread(); getRemoteClusterState(remoteCluster, Math.max(1L, nextMetadataVersion), (remoteClusterStateResponse, remoteError) -> { // Also check removed flag here, as it may take a while for this remote cluster state api call to return: if (removed) { LOGGER.trace("auto-follower instance for cluster [{}] has been removed", remoteCluster); return; } if (remoteClusterStateResponse != null) { assert remoteError == null; if (remoteClusterStateResponse.isWaitForTimedOut()) { LOGGER.trace("auto-follow coordinator timed out getting remote cluster state from [{}]", remoteCluster); start(); return; } ClusterState remoteClusterState = remoteClusterStateResponse.getState(); metadataVersion = remoteClusterState.metadata().version(); autoFollowIndices(autoFollowMetadata, clusterState, remoteClusterState, patterns, thread); } else { assert remoteError != null; if (remoteError instanceof NoSuchRemoteClusterException) { LOGGER.info("auto-follower for cluster [{}] has stopped, because remote connection is gone", remoteCluster); remoteClusterConnectionMissing = true; return; } for (int i = 0; i < patterns.size(); i++) { String autoFollowPatternName = patterns.get(i); finalise(i, new AutoFollowResult(autoFollowPatternName, remoteError), thread); } } }); } void stop() { LOGGER.trace("stopping auto-follower for remote cluster [{}]", remoteCluster); stop = true; } private void autoFollowIndices( final AutoFollowMetadata autoFollowMetadata, final ClusterState clusterState, final ClusterState remoteClusterState, final List<String> patterns, final Thread thread ) { int i = 0; for (String autoFollowPatternName : patterns) { final int slot = i; AutoFollowPattern autoFollowPattern = autoFollowMetadata.getPatterns().get(autoFollowPatternName); Map<String, String> headers = autoFollowMetadata.getHeaders().get(autoFollowPatternName); List<String> followedIndices = autoFollowMetadata.getFollowedLeaderIndexUUIDs().get(autoFollowPatternName); final List<Index> leaderIndicesToFollow = getLeaderIndicesToFollow(autoFollowPattern, remoteClusterState, followedIndices); if (leaderIndicesToFollow.isEmpty()) { finalise(slot, new AutoFollowResult(autoFollowPatternName), thread); } else { List<Tuple<String, AutoFollowPattern>> patternsForTheSameRemoteCluster = autoFollowMetadata.getPatterns() .entrySet() .stream() .filter(item -> autoFollowPatternName.equals(item.getKey()) == false) .filter(item -> remoteCluster.equals(item.getValue().getRemoteCluster())) .map(item -> new Tuple<>(item.getKey(), item.getValue())) .collect(Collectors.toList()); Consumer<AutoFollowResult> resultHandler = result -> finalise(slot, result, thread); checkAutoFollowPattern( autoFollowPatternName, remoteCluster, autoFollowPattern, leaderIndicesToFollow, headers, patternsForTheSameRemoteCluster, remoteClusterState.metadata(), clusterState.metadata(), resultHandler ); } i++; } cleanFollowedRemoteIndices(remoteClusterState, patterns); } /** * Go through all the leader indices that need to be followed, ensuring that they are * auto-followed by only a single pattern, have soft-deletes enabled, are not * searchable snapshots, and are not already followed. If all of those conditions are met, * then follow the indices. */ private void checkAutoFollowPattern( String autoFollowPattenName, String remoteClusterString, AutoFollowPattern autoFollowPattern, List<Index> leaderIndicesToFollow, Map<String, String> headers, List<Tuple<String, AutoFollowPattern>> patternsForTheSameRemoteCluster, Metadata remoteMetadata, Metadata localMetadata, Consumer<AutoFollowResult> resultHandler ) { final GroupedActionListener<Tuple<Index, Exception>> groupedListener = new GroupedActionListener<>( leaderIndicesToFollow.size(), ActionListener.wrap(rs -> resultHandler.accept(new AutoFollowResult(autoFollowPattenName, new ArrayList<>(rs))), e -> { final var illegalStateException = new IllegalStateException("must never happen", e); LOGGER.error("must never happen", illegalStateException); assert false : illegalStateException; throw illegalStateException; }) ); // Loop through all the as-of-yet-unfollowed indices from the leader for (final Index indexToFollow : leaderIndicesToFollow) { // Look up the abstraction for the given index, e.g., an index ".ds-foo" could look // up the Data Stream "foo" IndexAbstraction indexAbstraction = remoteMetadata.getProject().getIndicesLookup().get(indexToFollow.getName()); // Ensure that the remote cluster doesn't have other patterns // that would follow the index, there can be only one. List<String> otherMatchingPatterns = patternsForTheSameRemoteCluster.stream() .filter(otherPattern -> otherPattern.v2().match(indexAbstraction)) .map(Tuple::v1) .toList(); if (otherMatchingPatterns.size() != 0) { groupedListener.onResponse( new Tuple<>( indexToFollow, new ElasticsearchException( "index to follow [" + indexToFollow.getName() + "] for pattern [" + autoFollowPattenName + "] matches with other patterns " + otherMatchingPatterns + "" ) ) ); } else { final IndexMetadata leaderIndexMetadata = remoteMetadata.getProject().getIndexSafe(indexToFollow); // First ensure that the index on the leader that we want to follow has soft-deletes enabled if (IndexSettings.INDEX_SOFT_DELETES_SETTING.get(leaderIndexMetadata.getSettings()) == false) { String message = String.format( Locale.ROOT, "index [%s] cannot be followed, because soft deletes are not enabled", indexToFollow.getName() ); LOGGER.warn(message); updateAutoFollowMetadata(recordLeaderIndexAsFollowFunction(autoFollowPattenName, indexToFollow), error -> { ElasticsearchException failure = new ElasticsearchException(message); if (error != null) { failure.addSuppressed(error); } groupedListener.onResponse(new Tuple<>(indexToFollow, failure)); }); } else if (leaderIndexMetadata.isSearchableSnapshot()) { String message = String.format( Locale.ROOT, "index to follow [%s] is a searchable snapshot index and cannot be used for cross-cluster replication purpose", indexToFollow.getName() ); LOGGER.debug(message); updateAutoFollowMetadata(recordLeaderIndexAsFollowFunction(autoFollowPattenName, indexToFollow), error -> { ElasticsearchException failure = new ElasticsearchException(message); if (error != null) { failure.addSuppressed(error); } groupedListener.onResponse(new Tuple<>(indexToFollow, failure)); }); } else if (leaderIndexAlreadyFollowed(autoFollowPattern, indexToFollow, localMetadata)) { updateAutoFollowMetadata( recordLeaderIndexAsFollowFunction(autoFollowPattenName, indexToFollow), error -> groupedListener.onResponse(new Tuple<>(indexToFollow, error)) ); } else { // Finally, if there are no reasons why we cannot follow the leader index, perform the follow. followLeaderIndex( autoFollowPattenName, remoteClusterString, indexToFollow, indexAbstraction, autoFollowPattern, headers, error -> groupedListener.onResponse(new Tuple<>(indexToFollow, error)) ); } } } } private static boolean leaderIndexAlreadyFollowed(AutoFollowPattern autoFollowPattern, Index leaderIndex, Metadata localMetadata) { String followIndexName = getFollowerIndexName(autoFollowPattern, leaderIndex.getName()); IndexMetadata indexMetadata = localMetadata.getProject().index(followIndexName); if (indexMetadata != null) { // If an index with the same name exists, but it is not a follow index for this leader index then // we should let the auto follower attempt to auto follow it, so it can fail later and // it is then visible in the auto follow stats. For example a cluster can just happen to have // an index with the same name as the new follower index. Map<String, String> customData = indexMetadata.getCustomData(Ccr.CCR_CUSTOM_METADATA_KEY); if (customData != null) { String recordedLeaderIndexUUID = customData.get(Ccr.CCR_CUSTOM_METADATA_LEADER_INDEX_UUID_KEY); return leaderIndex.getUUID().equals(recordedLeaderIndexUUID); } } return false; } /** * Given a remote cluster, index that will be followed (and its abstraction), as well as an * {@link AutoFollowPattern}, generate the internal follow request for following the index. */ static PutFollowAction.Request generateRequest( String remoteCluster, Index indexToFollow, IndexAbstraction indexAbstraction, AutoFollowPattern pattern ) { final String leaderIndexName = indexToFollow.getName(); final String followIndexName = getFollowerIndexName(pattern, leaderIndexName); // TODO use longer timeouts here? see https://github.com/elastic/elasticsearch/issues/109150 PutFollowAction.Request request = new PutFollowAction.Request(TimeValue.THIRTY_SECONDS, TimeValue.THIRTY_SECONDS); request.setRemoteCluster(remoteCluster); request.setLeaderIndex(indexToFollow.getName()); request.setFollowerIndex(followIndexName); request.setSettings(pattern.getSettings()); // If there was a pattern specified for renaming the backing index, and this index is // part of a data stream, then send the new data stream name as part of the request. if (pattern.getFollowIndexPattern() != null && indexAbstraction.getParentDataStream() != null) { String dataStreamName = indexAbstraction.getParentDataStream().getName(); // Send the follow index pattern as the data stream pattern, so that data streams can be // renamed accordingly (not only the backing indices) request.setDataStreamName(pattern.getFollowIndexPattern().replace(AUTO_FOLLOW_PATTERN_REPLACEMENT, dataStreamName)); } request.getParameters().setMaxReadRequestOperationCount(pattern.getMaxReadRequestOperationCount()); request.getParameters().setMaxReadRequestSize(pattern.getMaxReadRequestSize()); request.getParameters().setMaxOutstandingReadRequests(pattern.getMaxOutstandingReadRequests()); request.getParameters().setMaxWriteRequestOperationCount(pattern.getMaxWriteRequestOperationCount()); request.getParameters().setMaxWriteRequestSize(pattern.getMaxWriteRequestSize()); request.getParameters().setMaxOutstandingWriteRequests(pattern.getMaxOutstandingWriteRequests()); request.getParameters().setMaxWriteBufferCount(pattern.getMaxWriteBufferCount()); request.getParameters().setMaxWriteBufferSize(pattern.getMaxWriteBufferSize()); request.getParameters().setMaxRetryDelay(pattern.getMaxRetryDelay()); request.getParameters().setReadPollTimeout(pattern.getReadPollTimeout()); request.masterNodeTimeout(TimeValue.MAX_VALUE); return request; } private void followLeaderIndex( String autoFollowPattenName, String remoteClusterString, Index indexToFollow, IndexAbstraction indexAbstraction, AutoFollowPattern pattern, Map<String, String> headers, Consumer<Exception> onResult ) { PutFollowAction.Request request = generateRequest(remoteClusterString, indexToFollow, indexAbstraction, pattern); // Execute if the create and follow api call succeeds: Runnable successHandler = () -> { LOGGER.info("auto followed leader index [{}] as follow index [{}]", indexToFollow, request.getFollowerIndex()); // This function updates the auto follow metadata in the cluster to record that the leader index has been followed: // (so that we do not try to follow it in subsequent auto follow runs) Function<ClusterState, ClusterState> function = recordLeaderIndexAsFollowFunction(autoFollowPattenName, indexToFollow); // The coordinator always runs on the elected master node, so we can update cluster state here: updateAutoFollowMetadata(function, onResult); }; createAndFollow(headers, request, successHandler, onResult); } private void finalise(int slot, AutoFollowResult result, final Thread thread) { assert autoFollowResults.get(slot) == null; autoFollowResults.set(slot, result); if (autoFollowPatternsCountDown.countDown()) { statsUpdater.accept(autoFollowResults.asList()); /* * In the face of a failure, we could be called back on the same thread. That is, it could be that we * never fired off the asynchronous remote cluster state call, instead failing beforehand. In this case, * we will recurse on the same thread. If there are repeated failures, we could blow the stack and * overflow. A real-world scenario in which this can occur is if the local connect queue is full. To * avoid this, if we are called back on the same thread, then we truncate the stack by forking to * another thread. */ if (thread == Thread.currentThread()) { executor.execute(this::start); return; } start(); } } /** * Given an auto following pattern for a set of indices and the cluster state from a remote * cluster, return the list of indices that need to be followed. The list of followed index * UUIDs contains indices that have already been followed, so the returned list will only * contain "new" indices from the leader that need to be followed. * * When looking up the name of the index to see if it matches one of the patterns, the index * abstraction ({@link IndexAbstraction}) of the index is used for comparison, this means * that if an index named ".ds-foo" was part of a data stream "foo", then an auto-follow * pattern of "f*" would allow the ".ds-foo" index to be returned. * * @param autoFollowPattern pattern to check indices that may need to be followed * @param remoteClusterState state from the remote ES cluster * @param followedIndexUUIDs a collection of UUIDs of indices already being followed * @return any new indices on the leader that need to be followed */ static List<Index> getLeaderIndicesToFollow( AutoFollowPattern autoFollowPattern, ClusterState remoteClusterState, List<String> followedIndexUUIDs ) { List<Index> leaderIndicesToFollow = new ArrayList<>(); for (IndexMetadata leaderIndexMetadata : remoteClusterState.getMetadata().getProject()) { if (leaderIndexMetadata.getState() != IndexMetadata.State.OPEN) { continue; } IndexAbstraction indexAbstraction = remoteClusterState.getMetadata() .getProject() .getIndicesLookup() .get(leaderIndexMetadata.getIndex().getName()); if (autoFollowPattern.isActive() && autoFollowPattern.match(indexAbstraction)) { IndexRoutingTable indexRoutingTable = remoteClusterState.routingTable().index(leaderIndexMetadata.getIndex()); if (indexRoutingTable != null && // Leader indices can be in the cluster state, but not all primary shards may be ready yet. // This checks ensures all primary shards have started, so that index following does not fail. // If not all primary shards are ready, then the next time the auto follow coordinator runs // this index will be auto followed. indexRoutingTable.allPrimaryShardsActive() && followedIndexUUIDs.contains(leaderIndexMetadata.getIndex().getUUID()) == false) { leaderIndicesToFollow.add(leaderIndexMetadata.getIndex()); } } } return leaderIndicesToFollow; } /** * Returns the new name for the follower index. If the auto-follow configuration includes a * follow index pattern, the text "{@code {{leader_index}}}" is replaced with the original * index name, so a leader index called "foo" and a pattern of "{{leader_index}}_copy" * becomes a new follower index called "foo_copy". */ static String getFollowerIndexName(AutoFollowPattern autoFollowPattern, String leaderIndexName) { final String followPattern = autoFollowPattern.getFollowIndexPattern(); if (followPattern != null) { if (leaderIndexName.contains(DataStream.BACKING_INDEX_PREFIX)) { // The index being replicated is a data stream backing index, so it's something // like: <optional-prefix>.ds-<data-stream-name>-20XX-mm-dd-NNNNNN // // However, we cannot just replace the name with the proposed follow index // pattern, or else we'll end up with something like ".ds-logs-foo-bar-2022-02-02-000001_copy" // for "{{leader_index}}_copy", which will cause problems because it doesn't // follow a parseable pattern. Instead it would be better to rename it as though // the data stream name was the leader index name, ending up with // ".ds-logs-foo-bar_copy-2022-02-02-000001" as the final index name. Matcher m = DS_BACKING_PATTERN.matcher(leaderIndexName); if (m.find()) { return m.group(1) + // Prefix including ".ds-" followPattern.replace(AUTO_FOLLOW_PATTERN_REPLACEMENT, m.group(2)) + // Data stream name changed "-" + // Hyphen separator m.group(3) + // Date math m.group(4); } else { throw new IllegalArgumentException( "unable to determine follower index name from leader index name [" + leaderIndexName + "] and follow index pattern: [" + followPattern + "], index appears to follow a regular data stream backing pattern, but could not be parsed" ); } } else { // If the index does nat contain a `.ds-<thing>`, then rename it as usual. return followPattern.replace("{{leader_index}}", leaderIndexName); } } else { return leaderIndexName; } } static Function<ClusterState, ClusterState> recordLeaderIndexAsFollowFunction(String name, Index indexToFollow) { return currentState -> { final var project = currentState.metadata().getProject(); AutoFollowMetadata currentAutoFollowMetadata = project.custom(AutoFollowMetadata.TYPE); Map<String, List<String>> newFollowedIndexUUIDS = new HashMap<>(currentAutoFollowMetadata.getFollowedLeaderIndexUUIDs()); if (newFollowedIndexUUIDS.containsKey(name) == false) { // A delete auto follow pattern request can have removed the auto follow pattern while we want to update // the auto follow metadata with the fact that an index was successfully auto followed. If this // happens, we can just skip this step. return currentState; } newFollowedIndexUUIDS.compute(name, (key, existingUUIDs) -> { assert existingUUIDs != null; List<String> newUUIDs = new ArrayList<>(existingUUIDs); newUUIDs.add(indexToFollow.getUUID()); return Collections.unmodifiableList(newUUIDs); }); final AutoFollowMetadata newAutoFollowMetadata = new AutoFollowMetadata( currentAutoFollowMetadata.getPatterns(), newFollowedIndexUUIDS, currentAutoFollowMetadata.getHeaders() ); return ClusterState.builder(currentState) .putProjectMetadata(ProjectMetadata.builder(project).putCustom(AutoFollowMetadata.TYPE, newAutoFollowMetadata).build()) .build(); }; } void cleanFollowedRemoteIndices(final ClusterState remoteClusterState, final List<String> patterns) { updateAutoFollowMetadata(cleanFollowedRemoteIndices(remoteClusterState.metadata(), patterns), e -> { if (e != null) { LOGGER.warn("Error occured while cleaning followed leader indices", e); } }); } static Function<ClusterState, ClusterState> cleanFollowedRemoteIndices( final Metadata remoteMetadata, final List<String> autoFollowPatternNames ) { return currentState -> { final var currentProject = currentState.metadata().getProject(); AutoFollowMetadata currentAutoFollowMetadata = currentProject.custom(AutoFollowMetadata.TYPE); Map<String, List<String>> autoFollowPatternNameToFollowedIndexUUIDs = new HashMap<>( currentAutoFollowMetadata.getFollowedLeaderIndexUUIDs() ); Set<String> remoteIndexUUIDS = remoteMetadata.getProject() .indices() .values() .stream() .map(IndexMetadata::getIndexUUID) .collect(Collectors.toSet()); boolean requiresCSUpdate = false; for (String autoFollowPatternName : autoFollowPatternNames) { if (autoFollowPatternNameToFollowedIndexUUIDs.containsKey(autoFollowPatternName) == false) { // A delete auto follow pattern request can have removed the auto follow pattern while we want to update // the auto follow metadata with the fact that an index was successfully auto followed. If this // happens, we can just skip this step. continue; } List<String> followedIndexUUIDs = new ArrayList<>(autoFollowPatternNameToFollowedIndexUUIDs.get(autoFollowPatternName)); // Remove leader indices that no longer exist in the remote cluster: boolean entriesRemoved = followedIndexUUIDs.removeIf( followedLeaderIndexUUID -> remoteIndexUUIDS.contains(followedLeaderIndexUUID) == false ); if (entriesRemoved) { requiresCSUpdate = true; } autoFollowPatternNameToFollowedIndexUUIDs.put(autoFollowPatternName, followedIndexUUIDs); } if (requiresCSUpdate) { final AutoFollowMetadata newAutoFollowMetadata = new AutoFollowMetadata( currentAutoFollowMetadata.getPatterns(), autoFollowPatternNameToFollowedIndexUUIDs, currentAutoFollowMetadata.getHeaders() ); return ClusterState.builder(currentState) .putProjectMetadata( ProjectMetadata.builder(currentProject).putCustom(AutoFollowMetadata.TYPE, newAutoFollowMetadata).build() ) .build(); } else { return currentState; } }; } /** * Fetch a remote cluster state from with the specified cluster alias * @param remoteCluster the name of the leader cluster * @param metadataVersion the last seen metadata version * @param handler the callback to invoke */ abstract void getRemoteClusterState( String remoteCluster, long metadataVersion, BiConsumer<ClusterStateResponse, Exception> handler ); abstract void createAndFollow( Map<String, String> headers, PutFollowAction.Request followRequest, Runnable successHandler, Consumer<Exception> failureHandler ); abstract void updateAutoFollowMetadata(Function<ClusterState, ClusterState> updateFunction, Consumer<Exception> handler); } static
AutoFollower
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/condition/AllOf.java
{ "start": 891, "end": 2378 }
class ____<T> extends Join<T> { /** * Creates a new <code>{@link AllOf}</code> * @param <T> the type of object the given condition accept. * @param conditions the conditions to evaluate. * @return the created {@code AllOf}. * @throws NullPointerException if the given array is {@code null}. * @throws NullPointerException if any of the elements in the given array is {@code null}. */ @SafeVarargs public static <T> Condition<T> allOf(Condition<? super T>... conditions) { return new AllOf<>(conditions); } /** * Creates a new <code>{@link AllOf}</code> * @param <T> the type of object the given condition accept. * @param conditions the conditions to evaluate. * @return the created {@code AllOf}. * @throws NullPointerException if the given iterable is {@code null}. * @throws NullPointerException if any of the elements in the given iterable is {@code null}. */ public static <T> Condition<T> allOf(Iterable<? extends Condition<? super T>> conditions) { return new AllOf<>(conditions); } @SafeVarargs private AllOf(Condition<? super T>... conditions) { super(conditions); } private AllOf(Iterable<? extends Condition<? super T>> conditions) { super(conditions); } /** {@inheritDoc} */ @Override public boolean matches(T value) { return conditions.stream().allMatch(condition -> condition.matches(value)); } @Override public String descriptionPrefix() { return "all of"; } }
AllOf
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 12839, "end": 13002 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return dialect.supportsSkipLocked(); } } public static
SupportsSkipLocked
java
apache__dubbo
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConventionTest.java
{ "start": 1260, "end": 3293 }
class ____ { static DubboServerObservationConvention dubboServerObservationConvention = DefaultDubboServerObservationConvention.getInstance(); @Test void testGetName() { Assertions.assertEquals("rpc.server.duration", dubboServerObservationConvention.getName()); } @Test void testGetLowCardinalityKeyValues() throws NoSuchFieldException, IllegalAccessException { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("testMethod"); invocation.setAttachment("interface", "com.example.TestService"); invocation.setTargetServiceUniqueName("targetServiceName1"); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setInvoker(invoker); DubboServerContext context = new DubboServerContext(invoker, invocation); KeyValues keyValues = dubboServerObservationConvention.getLowCardinalityKeyValues(context); Assertions.assertEquals("testMethod", ObservationConventionUtils.getValueForKey(keyValues, "rpc.method")); Assertions.assertEquals( "targetServiceName1", ObservationConventionUtils.getValueForKey(keyValues, "rpc.service")); Assertions.assertEquals("apache_dubbo", ObservationConventionUtils.getValueForKey(keyValues, "rpc.system")); } @Test void testGetContextualName() { RpcInvocation invocation = new RpcInvocation(); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setMethodName("testMethod"); invocation.setServiceName("com.example.TestService"); DubboClientContext context = new DubboClientContext(invoker, invocation); DefaultDubboClientObservationConvention convention = new DefaultDubboClientObservationConvention(); String contextualName = convention.getContextualName(context); Assertions.assertEquals("com.example.TestService/testMethod", contextualName); } }
DefaultDubboServerObservationConventionTest
java
spring-projects__spring-security
aspects/src/test/java/org/springframework/security/authorization/method/aspectj/PostAuthorizeAspectTests.java
{ "start": 4805, "end": 4899 }
class ____ { @PostAuthorize("denyAll") void denyAllMethod() { } } static
PrePostSecured
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/ingest/PutPipelineTransportAction.java
{ "start": 1454, "end": 3595 }
class ____ extends AcknowledgedTransportMasterNodeAction<PutPipelineRequest> { public static final ActionType<AcknowledgedResponse> TYPE = new ActionType<>("cluster:admin/ingest/pipeline/put"); private final IngestService ingestService; private final ProjectResolver projectResolver; @Inject public PutPipelineTransportAction( ThreadPool threadPool, TransportService transportService, ActionFilters actionFilters, ProjectResolver projectResolver, IngestService ingestService ) { super( TYPE.name(), transportService, ingestService.getClusterService(), threadPool, actionFilters, PutPipelineRequest::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.ingestService = ingestService; this.projectResolver = projectResolver; } @Override protected void masterOperation(Task task, PutPipelineRequest request, ClusterState state, ActionListener<AcknowledgedResponse> listener) throws Exception { ingestService.putPipeline(projectResolver.getProjectId(), request, listener); } @Override protected ClusterBlockException checkBlock(PutPipelineRequest request, ClusterState state) { return state.blocks().globalBlockedException(projectResolver.getProjectId(), ClusterBlockLevel.METADATA_WRITE); } @Override public Optional<String> reservedStateHandlerName() { return Optional.of(ReservedPipelineAction.NAME); } @Override public Set<String> modifiedKeys(PutPipelineRequest request) { return Set.of(request.getId()); } @Override protected void validateForReservedState(PutPipelineRequest request, ClusterState state) { super.validateForReservedState(request, state); validateForReservedState( ProjectStateRegistry.get(state).reservedStateMetadata(projectResolver.getProjectId()).values(), reservedStateHandlerName().get(), modifiedKeys(request), request::toString ); } }
PutPipelineTransportAction
java
elastic__elasticsearch
x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/action/CrossClusterLookupJoinFailuresIT.java
{ "start": 1078, "end": 11912 }
class ____ extends AbstractCrossClusterTestCase { protected boolean reuseClusters() { return false; } public void testLookupFail() throws IOException { setupClusters(3); populateLookupIndex(LOCAL_CLUSTER, "values_lookup", 10); populateLookupIndex(REMOTE_CLUSTER_1, "values_lookup", 25); populateLookupIndex(REMOTE_CLUSTER_2, "values_lookup", 25); setSkipUnavailable(REMOTE_CLUSTER_1, true); Exception simulatedFailure = randomFailure(); // fail when trying to do the lookup on remote cluster for (TransportService transportService : cluster(REMOTE_CLUSTER_1).getInstances(TransportService.class)) { MockTransportService ts = asInstanceOf(MockTransportService.class, transportService); ts.addRequestHandlingBehavior( EsqlResolveFieldsAction.RESOLVE_REMOTE_TYPE.name(), (handler, request, channel, task) -> handler.messageReceived(request, new TransportChannel() { @Override public String getProfileName() { return channel.getProfileName(); } @Override public void sendResponse(TransportResponse response) { sendResponse(simulatedFailure); } @Override public void sendResponse(Exception exception) { channel.sendResponse(exception); } }, task) ); } try { // FIXME: this should catch the error but fails instead /* try ( EsqlQueryResponse resp = runQuery( "FROM c*:logs-* | EVAL lookup_key = v | LOOKUP JOIN values_lookup ON lookup_key", randomBoolean() ) ) { var columns = resp.columns().stream().map(ColumnInfoImpl::name).toList(); assertThat(columns, hasItems("lookup_key", "lookup_name", "lookup_tag", "v", "tag")); List<List<Object>> values = getValuesList(resp); assertThat(values, hasSize(0)); EsqlExecutionInfo executionInfo = resp.getExecutionInfo(); var remoteCluster = executionInfo.getCluster(REMOTE_CLUSTER_1); assertThat(remoteCluster.getStatus(), equalTo(EsqlExecutionInfo.Cluster.Status.SKIPPED)); assertThat(remoteCluster.getFailures(), not(empty())); var failure = remoteCluster.getFailures().get(0); assertThat(failure.reason(), containsString(simulatedFailure.getMessage())); } */ try ( // This only calls REMOTE_CLUSTER_1 which is skip_unavailable=true EsqlQueryResponse resp = runQuery( "FROM logs-*,c*:logs-* | EVAL lookup_key = v | LOOKUP JOIN values_lookup ON lookup_key", randomBoolean() ) ) { var columns = resp.columns().stream().map(ColumnInfoImpl::name).toList(); assertThat(columns, hasItems("lookup_key", "lookup_name", "lookup_tag", "v", "tag")); List<List<Object>> values = getValuesList(resp); assertThat(values, hasSize(10)); EsqlExecutionInfo executionInfo = resp.getExecutionInfo(); var localCluster = executionInfo.getCluster(LOCAL_CLUSTER); assertThat(localCluster.getStatus(), equalTo(EsqlExecutionInfo.Cluster.Status.SUCCESSFUL)); var remoteCluster = executionInfo.getCluster(REMOTE_CLUSTER_1); assertThat(remoteCluster.getStatus(), equalTo(EsqlExecutionInfo.Cluster.Status.SKIPPED)); assertThat(remoteCluster.getFailures(), not(empty())); var failure = remoteCluster.getFailures().get(0); assertThat(failure.reason(), containsString(simulatedFailure.getMessage())); assertThat(failure.reason(), containsString("lookup failed in remote cluster [cluster-a] for index [values_lookup]")); } try ( EsqlQueryResponse resp = runQuery( "FROM logs-*,*:logs-* | EVAL lookup_key = v | LOOKUP JOIN values_lookup ON lookup_key", randomBoolean() ) ) { var columns = resp.columns().stream().map(ColumnInfoImpl::name).toList(); assertThat(columns, hasItems("lookup_key", "lookup_name", "lookup_tag", "v", "tag")); List<List<Object>> values = getValuesList(resp); assertThat(values, hasSize(20)); EsqlExecutionInfo executionInfo = resp.getExecutionInfo(); var localCluster = executionInfo.getCluster(LOCAL_CLUSTER); assertThat(localCluster.getStatus(), equalTo(EsqlExecutionInfo.Cluster.Status.SUCCESSFUL)); var remoteCluster = executionInfo.getCluster(REMOTE_CLUSTER_1); assertThat(remoteCluster.getStatus(), equalTo(EsqlExecutionInfo.Cluster.Status.SKIPPED)); var remoteCluster2 = executionInfo.getCluster(REMOTE_CLUSTER_2); assertThat(remoteCluster2.getStatus(), equalTo(EsqlExecutionInfo.Cluster.Status.SUCCESSFUL)); assertThat(remoteCluster.getFailures(), not(empty())); var failure = remoteCluster.getFailures().get(0); assertThat(failure.reason(), containsString(simulatedFailure.getMessage())); assertThat(failure.reason(), containsString("lookup failed in remote cluster [cluster-a] for index [values_lookup]")); } // now fail setSkipUnavailable(REMOTE_CLUSTER_1, false); // c*: only calls REMOTE_CLUSTER_1 which is skip_unavailable=false now Exception ex = expectThrows( VerificationException.class, () -> runQuery("FROM logs-*,c*:logs-* | EVAL lookup_key = v | LOOKUP JOIN values_lookup ON lookup_key", randomBoolean()) ); assertThat(ex.getMessage(), containsString("lookup failed in remote cluster [cluster-a] for index [values_lookup]")); String message = ex.getCause() == null ? ex.getMessage() : ex.getCause().getMessage(); assertThat(message, containsString(simulatedFailure.getMessage())); ex = expectThrows( Exception.class, () -> runQuery("FROM c*:logs-* | EVAL lookup_key = v | LOOKUP JOIN values_lookup ON lookup_key", randomBoolean()) ); message = ex.getCause() == null ? ex.getMessage() : ex.getCause().getMessage(); assertThat(message, containsString(simulatedFailure.getMessage())); } finally { for (TransportService transportService : cluster(REMOTE_CLUSTER_1).getInstances(TransportService.class)) { MockTransportService ts = asInstanceOf(MockTransportService.class, transportService); ts.clearAllRules(); } } } public void testLookupDisconnect() throws IOException { setupClusters(2); populateLookupIndex(LOCAL_CLUSTER, "values_lookup", 10); populateLookupIndex(REMOTE_CLUSTER_1, "values_lookup", 10); setSkipUnavailable(REMOTE_CLUSTER_1, true); try { // close the remote cluster so that it is unavailable cluster(REMOTE_CLUSTER_1).close(); try ( EsqlQueryResponse resp = runQuery( "FROM c*:logs-* | EVAL lookup_key = v | LOOKUP JOIN values_lookup ON lookup_key", randomBoolean() ) ) { var columns = resp.columns().stream().map(ColumnInfoImpl::name).toList(); // this is a bit weird but that's how it works assertThat(columns, hasSize(1)); assertThat(columns, hasItems("<no-fields>")); List<List<Object>> values = getValuesList(resp); assertThat(values, hasSize(0)); EsqlExecutionInfo executionInfo = resp.getExecutionInfo(); var remoteCluster = executionInfo.getCluster(REMOTE_CLUSTER_1); assertThat(remoteCluster.getStatus(), equalTo(EsqlExecutionInfo.Cluster.Status.SKIPPED)); assertThat(remoteCluster.getFailures(), not(empty())); var failure = remoteCluster.getFailures().get(0); assertThat(failure.reason(), containsString("unable to connect to remote cluster")); } try ( EsqlQueryResponse resp = runQuery( "FROM logs-*,c*:logs-* | EVAL lookup_key = v | LOOKUP JOIN values_lookup ON lookup_key", randomBoolean() ) ) { var columns = resp.columns().stream().map(ColumnInfoImpl::name).toList(); assertThat(columns, hasItems("lookup_key", "lookup_name", "lookup_tag", "v", "tag")); List<List<Object>> values = getValuesList(resp); assertThat(values, hasSize(10)); EsqlExecutionInfo executionInfo = resp.getExecutionInfo(); var localCluster = executionInfo.getCluster(LOCAL_CLUSTER); assertThat(localCluster.getStatus(), equalTo(EsqlExecutionInfo.Cluster.Status.SUCCESSFUL)); var remoteCluster = executionInfo.getCluster(REMOTE_CLUSTER_1); assertThat(remoteCluster.getStatus(), equalTo(EsqlExecutionInfo.Cluster.Status.SKIPPED)); assertThat(remoteCluster.getFailures(), not(empty())); var failure = remoteCluster.getFailures().get(0); assertThat( failure.reason(), containsString("Remote cluster [cluster-a] (with setting skip_unavailable=true) is not available") ); } setSkipUnavailable(REMOTE_CLUSTER_1, false); Exception ex = expectThrows( ElasticsearchException.class, () -> runQuery("FROM c*:logs-* | EVAL lookup_key = v | LOOKUP JOIN values_lookup ON lookup_key", randomBoolean()) ); assertTrue(ExceptionsHelper.isRemoteUnavailableException(ex)); ex = expectThrows( ElasticsearchException.class, () -> runQuery("FROM logs-*,c*:logs-* | EVAL lookup_key = v | LOOKUP JOIN values_lookup ON lookup_key", randomBoolean()) ); assertTrue(ExceptionsHelper.isRemoteUnavailableException(ex)); } finally { clearSkipUnavailable(2); } } }
CrossClusterLookupJoinFailuresIT
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/FieldSerializationTest.java
{ "start": 2687, "end": 2882 }
class ____ { @JsonProperty public int z; @JsonProperty("z") public int getZ() { return z+1; } } @JsonInclude(JsonInclude.Include.NON_EMPTY) public
FieldAndMethodBean
java
apache__camel
components/camel-sap-netweaver/src/main/java/org/apache/camel/component/sap/netweaver/NetWeaverConstants.java
{ "start": 940, "end": 1590 }
class ____ { @Metadata(description = "The command to execute in\n" + "http://msdn.microsoft.com/en-us/library/cc956153.aspx[MS ADO.Net Data\n" + "Service] format.", javaType = "String", required = true) public static final String COMMAND = "CamelNetWeaverCommand"; @Metadata(description = "The http path.", javaType = "String") public static final String HTTP_PATH = Exchange.HTTP_PATH; @Metadata(description = "The media type.", javaType = "String") public static final String ACCEPT = "Accept"; private NetWeaverConstants() { } }
NetWeaverConstants
java
apache__spark
common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/protocol/MergeStatuses.java
{ "start": 1629, "end": 4429 }
class ____ extends BlockTransferMessage { /** Shuffle ID **/ public final int shuffleId; /** * shuffleMergeId is used to uniquely identify merging process of shuffle by * an indeterminate stage attempt. */ public final int shuffleMergeId; /** * Array of bitmaps tracking the set of mapper partition blocks merged for each * reducer partition */ public final RoaringBitmap[] bitmaps; /** Array of reducer IDs **/ public final int[] reduceIds; /** * Array of merged shuffle partition block size. Each represents the total size of all * merged shuffle partition blocks for one reducer partition. * **/ public final long[] sizes; public MergeStatuses( int shuffleId, int shuffleMergeId, RoaringBitmap[] bitmaps, int[] reduceIds, long[] sizes) { this.shuffleId = shuffleId; this.shuffleMergeId = shuffleMergeId; this.bitmaps = bitmaps; this.reduceIds = reduceIds; this.sizes = sizes; } @Override protected Type type() { return Type.MERGE_STATUSES; } @Override public int hashCode() { int objectHashCode = Objects.hashCode(shuffleId) * 41 + Objects.hashCode(shuffleMergeId); return (objectHashCode * 41 + Arrays.hashCode(reduceIds) * 41 + Arrays.hashCode(bitmaps) * 41 + Arrays.hashCode(sizes)); } @Override public String toString() { return "MergeStatuses[shuffleId=" + shuffleId + ",shuffleMergeId=" + shuffleMergeId + ",reduceId size=" + reduceIds.length + "]"; } @Override public boolean equals(Object other) { if (other instanceof MergeStatuses o) { return Objects.equals(shuffleId, o.shuffleId) && Objects.equals(shuffleMergeId, o.shuffleMergeId) && Arrays.equals(bitmaps, o.bitmaps) && Arrays.equals(reduceIds, o.reduceIds) && Arrays.equals(sizes, o.sizes); } return false; } @Override public int encodedLength() { return 4 + 4 // shuffleId and shuffleMergeId + Encoders.BitmapArrays.encodedLength(bitmaps) + Encoders.IntArrays.encodedLength(reduceIds) + Encoders.LongArrays.encodedLength(sizes); } @Override public void encode(ByteBuf buf) { buf.writeInt(shuffleId); buf.writeInt(shuffleMergeId); Encoders.BitmapArrays.encode(buf, bitmaps); Encoders.IntArrays.encode(buf, reduceIds); Encoders.LongArrays.encode(buf, sizes); } public static MergeStatuses decode(ByteBuf buf) { int shuffleId = buf.readInt(); int shuffleMergeId = buf.readInt(); RoaringBitmap[] bitmaps = Encoders.BitmapArrays.decode(buf); int[] reduceIds = Encoders.IntArrays.decode(buf); long[] sizes = Encoders.LongArrays.decode(buf); return new MergeStatuses(shuffleId, shuffleMergeId, bitmaps, reduceIds, sizes); } }
MergeStatuses
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/procedures/PostgresStoredProcedureIntegrationTests.java
{ "start": 7466, "end": 8422 }
class ____ { @Id @GeneratedValue // private Integer id; private String name; public Employee(Integer id, String name) { this.id = id; this.name = name; } public Employee() {} public Integer getId() { return this.id; } public String getName() { return this.name; } public void setId(Integer id) { this.id = id; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; return Objects.equals(id, employee.id) && Objects.equals(name, employee.name); } @Override public int hashCode() { return Objects.hash(id, name); } public String toString() { return "PostgresStoredProcedureIntegrationTests.Employee(id=" + this.getId() + ", name=" + this.getName() + ")"; } } @Transactional public
Employee
java
apache__rocketmq
auth/src/main/java/org/apache/rocketmq/auth/authorization/strategy/StatelessAuthorizationStrategy.java
{ "start": 1031, "end": 1370 }
class ____ extends AbstractAuthorizationStrategy { public StatelessAuthorizationStrategy(AuthConfig authConfig, Supplier<?> metadataService) { super(authConfig, metadataService); } @Override public void evaluate(AuthorizationContext context) { super.doEvaluate(context); } }
StatelessAuthorizationStrategy
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/HazelcastMultimapComponentBuilderFactory.java
{ "start": 1404, "end": 1944 }
interface ____ { /** * Hazelcast Multimap (camel-hazelcast) * Perform operations on Hazelcast distributed multimap. * * Category: cache,clustering * Since: 2.7 * Maven coordinates: org.apache.camel:camel-hazelcast * * @return the dsl builder */ static HazelcastMultimapComponentBuilder hazelcastMultimap() { return new HazelcastMultimapComponentBuilderImpl(); } /** * Builder for the Hazelcast Multimap component. */
HazelcastMultimapComponentBuilderFactory
java
grpc__grpc-java
core/src/test/java/io/grpc/internal/ServerCallImplTest.java
{ "start": 16677, "end": 17116 }
class ____ implements Marshaller<Long> { @Override public InputStream stream(Long value) { return new ByteArrayInputStream(value.toString().getBytes(UTF_8)); } @Override public Long parse(InputStream stream) { try { return Long.parseLong(CharStreams.toString(new InputStreamReader(stream, UTF_8))); } catch (Exception e) { throw new RuntimeException(e); } } } }
LongMarshaller
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/DefaultSchemaNameResolver.java
{ "start": 443, "end": 941 }
class ____ implements SchemaNameResolver { public static final DefaultSchemaNameResolver INSTANCE = new DefaultSchemaNameResolver(); private DefaultSchemaNameResolver() { } @Override public String resolveSchemaName(Connection connection, Dialect dialect) throws SQLException { try { return connection.getSchema(); } catch (AbstractMethodError ignore) { // jConnect and jTDS report that they "support" schemas, but they don't really return null; } } }
DefaultSchemaNameResolver
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/lookup/LookupConditionsTest.java
{ "start": 1139, "end": 1355 }
interface ____ { String ping(); } // -> suppressed because service.alpha.enabled=false @LookupUnlessProperty(name = "service.alpha.enabled", stringValue = "false") @Singleton static
Service
java
apache__flink
flink-core/src/main/java/org/apache/flink/util/TimeUtils.java
{ "start": 8385, "end": 10639 }
enum ____ { DAYS(ChronoUnit.DAYS, singular("d"), plural("day")), HOURS(ChronoUnit.HOURS, singular("h"), plural("hour")), MINUTES(ChronoUnit.MINUTES, singular("min"), singular("m"), plural("minute")), SECONDS(ChronoUnit.SECONDS, singular("s"), plural("sec"), plural("second")), MILLISECONDS(ChronoUnit.MILLIS, singular("ms"), plural("milli"), plural("millisecond")), MICROSECONDS(ChronoUnit.MICROS, singular("µs"), plural("micro"), plural("microsecond")), NANOSECONDS(ChronoUnit.NANOS, singular("ns"), plural("nano"), plural("nanosecond")); private static final String PLURAL_SUFFIX = "s"; private final List<String> labels; private final ChronoUnit unit; private final BigInteger unitAsNanos; TimeUnit(ChronoUnit unit, String[]... labels) { this.unit = unit; this.unitAsNanos = BigInteger.valueOf(unit.getDuration().toNanos()); this.labels = Arrays.stream(labels).flatMap(Arrays::stream).collect(Collectors.toList()); } /** * @param label the original label * @return the singular format of the original label */ private static String[] singular(String label) { return new String[] {label}; } /** * @param label the original label * @return both the singular format and plural format of the original label */ private static String[] plural(String label) { return new String[] {label, label + PLURAL_SUFFIX}; } public List<String> getLabels() { return labels; } public ChronoUnit getUnit() { return unit; } public BigInteger getUnitAsNanos() { return unitAsNanos; } public static String getAllUnits() { return Arrays.stream(TimeUnit.values()) .map(TimeUnit::createTimeUnitString) .collect(Collectors.joining(", ")); } private static String createTimeUnitString(TimeUnit timeUnit) { return timeUnit.name() + ": (" + String.join(" | ", timeUnit.getLabels()) + ")"; } } }
TimeUnit
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/Limits.java
{ "start": 2428, "end": 3318 }
enum ____ { ConcurrentAsyncGetReportInstances, ConcurrentSyncReportRuns, DailyApiRequests, DailyAsyncApexExecutions, DailyBulkApiRequests, DailyDurableGenericStreamingApiEvents, DailyDurableStreamingApiEvents, DailyGenericStreamingApiEvents, DailyStreamingApiEvents, DailyWorkflowEmails, DataStorageMB, DurableStreamingApiConcurrentClients, FileStorageMB, HourlyAsyncReportRuns, HourlyDashboardRefreshes, HourlyDashboardResults, HourlyDashboardStatuses, HourlyODataCallout, HourlySyncReportRuns, HourlyTimeBasedWorkflow, MassEmail, PermissionSets, SingleEmail, StreamingApiConcurrentClients } /** * Encapsulates usage limits for single operation. */ public static final
Operation
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/CheckReturnValueTest.java
{ "start": 7236, "end": 7827 }
class ____ { @CheckReturnValue public String getString() { return "string"; } public void doIt() { // BUG: Diagnostic contains: CheckReturnValue getString(); } } """) .doTest(); } @Test public void customCanIgnoreReturnValueAnnotation() { compilationHelper .addSourceLines( "foo/bar/CanIgnoreReturnValue.java", """ package foo.bar; public @
TestCustomCheckReturnValueAnnotation
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GraphqlEndpointBuilderFactory.java
{ "start": 1447, "end": 1572 }
interface ____ { /** * Builder for endpoint for the GraphQL component. */ public
GraphqlEndpointBuilderFactory
java
elastic__elasticsearch
benchmarks/src/main/java/org/elasticsearch/benchmark/index/codec/tsdb/TSDBDocValuesMergeBenchmark.java
{ "start": 5072, "end": 5890 }
class ____ { @Param("20431204") private int nDocs; @Param("1000") private int deltaTime; @Param("42") private int seed; private Directory directory; private final Supplier<IndexWriterConfig> iwc = () -> createIndexWriterConfig(false); @Setup(Level.Trial) public void setup() throws IOException { directory = FSDirectory.open(Files.createTempDirectory("temp4-")); createIndex(directory, iwc.get(), true, nDocs, deltaTime, seed); } } @Benchmark public void forceMergeSparseWithoutOptimizedMerge(StateSparseWithoutOptimizeMerge state) throws IOException { forceMerge(state.directory, state.iwc.get()); } @State(Scope.Benchmark) public static
StateSparseWithoutOptimizeMerge
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/task/support/ContextPropagatingTaskDecoratorTests.java
{ "start": 2117, "end": 2657 }
class ____ implements ThreadLocalAccessor<String> { static final String KEY = "test.threadlocal"; @Override public Object key() { return KEY; } @Override public String getValue() { return TestThreadLocalHolder.getValue(); } @Override public void setValue(String value) { TestThreadLocalHolder.setValue(value); } @Override public void setValue() { TestThreadLocalHolder.reset(); } @Override public void restore(String previousValue) { setValue(previousValue); } } }
TestThreadLocalAccessor
java
quarkusio__quarkus
integration-tests/hibernate-search-orm-elasticsearch/src/main/java/io/quarkus/it/hibernate/search/orm/elasticsearch/management/ManagementTestEntity.java
{ "start": 412, "end": 970 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "managementSeq") private Long id; @FullTextField private String name; public ManagementTestEntity() { } public ManagementTestEntity(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
ManagementTestEntity
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/support/service/BaseService.java
{ "start": 15494, "end": 15728 }
class ____ { static final Logger LOG = LoggerFactory.getLogger(Holder.class); } private static Logger logger() { return Holder.LOG; } protected Lock getInternalLock() { return lock; } }
Holder
java
redisson__redisson
redisson/src/main/java/org/redisson/misc/RedisURI.java
{ "start": 961, "end": 6559 }
class ____ { public static final String REDIS_PROTOCOL= "redis://"; public static final String REDIS_SSL_PROTOCOL = "rediss://"; public static final String REDIS_UDS_PROTOCOL= "redis+uds://"; public static final String VALKEY_PROTOCOL= "valkey://"; public static final String VALKEY_SSL_PROTOCOL = "valkeys://"; public static final String VALKEY_UDS_PROTOCOL= "valkey+uds://"; private final String scheme; private final String host; private final int port; private String username; private String password; private int hashCode; public static boolean isValid(String url) { return url.startsWith(REDIS_PROTOCOL) || url.startsWith(REDIS_SSL_PROTOCOL) || url.startsWith(VALKEY_PROTOCOL) || url.startsWith(VALKEY_SSL_PROTOCOL) || url.startsWith(REDIS_UDS_PROTOCOL) || url.startsWith(VALKEY_UDS_PROTOCOL); } public RedisURI(String scheme, String host, int port) { this.scheme = scheme; this.host = host; this.port = port; this.hashCode = Objects.hash(isSsl(), host, port); } public RedisURI(String uri) { if (!isValid(uri)) { throw new IllegalArgumentException("Redis url should start with redis:// or rediss:// (for SSL connection)"); } scheme = uri.split("://")[0]; try { if (isUDS()) { host = uri.split("://")[1]; port = 0; return; } if (uri.split(":").length < 3) { throw new IllegalArgumentException("Redis url doesn't contain a port"); } String urlHost = parseUrl(uri); URL url = new URL(urlHost); if (url.getUserInfo() != null) { String[] details = url.getUserInfo().split(":", 2); if (details.length == 1) { // According to RFC 1738 section 3.1, the password can be omitted. // However, Redis CLI extends this URL semantic and uses the single auth component as password password = URLDecoder.decode(details[0], StandardCharsets.UTF_8.toString()); } else if (details.length == 2) { if (!details[0].isEmpty()) { username = URLDecoder.decode(details[0], StandardCharsets.UTF_8.toString()); } password = URLDecoder.decode(details[1], StandardCharsets.UTF_8.toString()); } } if (url.getHost().isEmpty()) { throw new IllegalArgumentException("Redis host can't be parsed"); } host = url.getHost(); port = url.getPort(); } catch (MalformedURLException | UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } this.hashCode = Objects.hash(isSsl(), host, port); } private String parseUrl(String uri) { int hostStartIndex = uri.indexOf("://") + 3; String urlHost = "http://" + uri.substring(hostStartIndex); String ipV6Host = uri.substring(hostStartIndex, uri.lastIndexOf(":")); if (ipV6Host.contains("@")) { ipV6Host = ipV6Host.split("@")[1]; } if (ipV6Host.contains(":") && !ipV6Host.startsWith("[")) { urlHost = urlHost.replace(ipV6Host, "[" + ipV6Host + "]"); } return urlHost; } public String getScheme() { return scheme; } public String getUsername() { return username; } public String getPassword() { return password; } public boolean isSsl() { return "rediss".equals(scheme) || "valkeys".equals(scheme); } public String getHost() { return host; } public int getPort() { return port; } public boolean isUDS() { return "redis+uds".equals(scheme) || "valkey+uds".equals(scheme); } public boolean isIP() { return NetUtil.createByteArrayFromIpAddressString(host) != null; } private String trimIpv6Brackets(String host) { if (host.startsWith("[") && host.endsWith("]")) { return host.substring(1, host.length() - 1); } return host; } public boolean equals(InetSocketAddress entryAddr) { String ip = trimIpv6Brackets(getHost()); if (((entryAddr.getHostName() != null && entryAddr.getHostName().equals(ip)) || entryAddr.getAddress().getHostAddress().equals(ip)) && entryAddr.getPort() == getPort()) { return true; } return false; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RedisURI redisURI = (RedisURI) o; return isSsl() == redisURI.isSsl() && port == redisURI.port && Objects.equals(host, redisURI.host); } @Override public int hashCode() { return hashCode; } @Override public String toString() { if (username != null && password != null) { return getScheme() + "://" + username + ":" + password + "@" + trimIpv6Brackets(host) + ":" + port; } else if (password != null) { return getScheme() + "://" + password + "@" + trimIpv6Brackets(host) + ":" + port; } return getScheme() + "://" + trimIpv6Brackets(host) + ":" + port; } }
RedisURI
java
alibaba__nacos
plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/configuration/ConditionOnLdapAuthTest.java
{ "start": 1404, "end": 2017 }
class ____ { @Mock private static ConfigurableEnvironment environment; private ConditionOnLdapAuth conditionOnLdapAuth; @Mock private ConditionContext conditionContext; @Mock private AnnotatedTypeMetadata annotatedTypeMetadata; @BeforeEach void setup() { conditionOnLdapAuth = new ConditionOnLdapAuth(); EnvUtil.setEnvironment(environment); } @Test void matches() { boolean matches = conditionOnLdapAuth.matches(conditionContext, annotatedTypeMetadata); assertFalse(matches); } }
ConditionOnLdapAuthTest
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/validation/InitializerMethodMarkedDisposerTest.java
{ "start": 538, "end": 945 }
class ____ { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder().beanClasses(Producers.class).shouldFail().build(); @Test public void testFailure() { Throwable error = container.getFailure(); assertNotNull(error); assertTrue(error instanceof DefinitionException); } @ApplicationScoped static
InitializerMethodMarkedDisposerTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cid/CompositeIdAndMergeTest.java
{ "start": 2037, "end": 2583 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String description; @ManyToOne(cascade = { CascadeType.ALL }) private Invoice invoice; public Order() { } public Order(String description) { this.description = description; } public Long getId() { return id; } public Invoice getInvoice() { return invoice; } public void setInvoice(Invoice invoice) { this.invoice = invoice; } } @Entity(name = "Invoice") public static
Order
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/synthbean/SynthBeanWithGenericClassInterceptionAndBindingsSourceTest.java
{ "start": 3858, "end": 4037 }
class ____<T> { @MyBinding2 abstract T hello2(T param); @MyBinding2 @NoClassInterceptors abstract T hello3(T param); } }
MyNonbeanBindings
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxUsingWhen.java
{ "start": 15789, "end": 17030 }
class ____ implements InnerConsumer<Object> { final UsingWhenParent parent; boolean done; CommitInner(UsingWhenParent ts) { this.parent = ts; } @Override public Context currentContext() { return parent.currentContext(); } @Override public void onSubscribe(Subscription s) { Objects.requireNonNull(s, "Subscription cannot be null") .request(Long.MAX_VALUE); } @Override public void onNext(Object o) { //NO-OP } @Override public void onError(Throwable e) { done = true; Throwable e_ = Operators.onOperatorError(e, parent.currentContext()); Throwable commitError = new RuntimeException("Async resource cleanup failed after onComplete", e_); parent.deferredError(commitError); } @Override public void onComplete() { done = true; parent.deferredComplete(); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.PARENT) return parent; if (key == Attr.ACTUAL) return parent.actual(); if (key == Attr.TERMINATED) return done; if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return null; } } /** * Used in the cancel path to still give the generated Publisher access to the Context */ static final
CommitInner
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/connector/expressions/GetArrayItem.java
{ "start": 1047, "end": 2014 }
class ____ extends ExpressionWithToString { private final Expression childArray; private final Expression ordinal; private final boolean failOnError; /** * Creates GetArrayItem expression. * @param childArray Array that is source to get element from. Child of this expression. * @param ordinal Ordinal of element. Zero-based indexing. * @param failOnError Whether expression should throw exception for index out of bound or to * return null. */ public GetArrayItem(Expression childArray, Expression ordinal, boolean failOnError) { this.childArray = childArray; this.ordinal = ordinal; this.failOnError = failOnError; } public Expression childArray() { return this.childArray; } public Expression ordinal() { return this.ordinal; } public boolean failOnError() { return this.failOnError; } @Override public Expression[] children() { return new Expression[]{ childArray, ordinal }; } }
GetArrayItem
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/manytomanyassociationclass/compositeid/MembershipWithCompositeId.java
{ "start": 544, "end": 2246 }
class ____ implements Serializable { private Long userId; private Long groupId; public Id() { } public Id(Long userId, Long groupId) { this.userId = userId; this.groupId = groupId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getGroupId() { return groupId; } public void setGroupId(Long groupId) { this.groupId = groupId; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Id other = (Id) obj; if (userId == null) { if (other.userId != null) return false; } else if (!userId.equals(other.userId)) return false; if (groupId == null) { if (other.groupId != null) return false; } else if (!groupId.equals(other.groupId)) return false; return true; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((userId == null) ? 0 : userId.hashCode()); result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); return result; } } public MembershipWithCompositeId() { super( new Id() ); } public MembershipWithCompositeId(String name) { super( new Id(), name ); } public void setGroup(Group group) { if (getId() == null) { setId(new Id()); } ( (Id) getId() ).setGroupId( ( group == null ? null : group.getId() ) ); super.setGroup( group ); } public void setUser(User user) { if (getId() == null) { setId(new Id()); } ( (Id) getId() ).setUserId( user == null ? null : user.getId() ); super.setUser( user ); } }
Id
java
spring-projects__spring-boot
module/spring-boot-data-couchbase/src/main/java/org/springframework/boot/data/couchbase/autoconfigure/CouchbaseClientFactoryDependentConfiguration.java
{ "start": 1571, "end": 2262 }
class ____ { @Bean(name = BeanNames.COUCHBASE_TEMPLATE) @ConditionalOnMissingBean(name = BeanNames.COUCHBASE_TEMPLATE) CouchbaseTemplate couchbaseTemplate(CouchbaseClientFactory couchbaseClientFactory, MappingCouchbaseConverter mappingCouchbaseConverter) { return new CouchbaseTemplate(couchbaseClientFactory, mappingCouchbaseConverter); } @Bean(name = BeanNames.COUCHBASE_OPERATIONS_MAPPING) @ConditionalOnMissingBean(name = BeanNames.COUCHBASE_OPERATIONS_MAPPING) RepositoryOperationsMapping couchbaseRepositoryOperationsMapping(CouchbaseTemplate couchbaseTemplate) { return new RepositoryOperationsMapping(couchbaseTemplate); } }
CouchbaseClientFactoryDependentConfiguration
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/LogEvent.java
{ "start": 4315, "end": 4402 }
class ____ of the caller of the logging API. * * @return The fully qualified
name
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/ibmwatsonx/request/IbmWatsonxRerankRequest.java
{ "start": 1030, "end": 3298 }
class ____ implements IbmWatsonxRequest { private final String query; private final List<String> input; private final IbmWatsonxRerankTaskSettings taskSettings; private final IbmWatsonxRerankModel model; public IbmWatsonxRerankRequest(String query, List<String> input, IbmWatsonxRerankModel model) { Objects.requireNonNull(model); this.input = Objects.requireNonNull(input); this.query = Objects.requireNonNull(query); taskSettings = model.getTaskSettings(); this.model = model; } @Override public HttpRequest createHttpRequest() { URI uri; try { uri = new URI(model.uri().toString()); } catch (URISyntaxException ex) { throw new IllegalArgumentException("cannot parse URI patter"); } HttpPost httpPost = new HttpPost(uri); ByteArrayEntity byteEntity = new ByteArrayEntity( Strings.toString( new IbmWatsonxRerankRequestEntity( query, input, taskSettings, model.getServiceSettings().modelId(), model.getServiceSettings().projectId() ) ).getBytes(StandardCharsets.UTF_8) ); httpPost.setEntity(byteEntity); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, XContentType.JSON.mediaType()); decorateWithAuth(httpPost); return new HttpRequest(httpPost, getInferenceEntityId()); } public void decorateWithAuth(HttpPost httpPost) { IbmWatsonxRequest.decorateWithBearerToken(httpPost, model.getSecretSettings(), model.getInferenceEntityId()); } @Override public String getInferenceEntityId() { return model.getInferenceEntityId(); } @Override public URI getURI() { return model.uri(); } @Override public Request truncate() { return this; } public String getQuery() { return query; } public List<String> getInput() { return input; } public IbmWatsonxRerankModel getModel() { return model; } @Override public boolean[] getTruncationInfo() { return null; } }
IbmWatsonxRerankRequest
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/eql/EqlAsyncActionNames.java
{ "start": 367, "end": 498 }
class ____ { public static final String EQL_ASYNC_GET_RESULT_ACTION_NAME = "indices:data/read/eql/async/get"; }
EqlAsyncActionNames
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/standalone/StandaloneHerderTest.java
{ "start": 63136, "end": 63214 }
class ____ extends SourceTask { } private abstract static
BogusSourceTask
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/web/servlet/assertj/MockMvcTester.java
{ "start": 20855, "end": 22998 }
class ____ extends AbstractMockMultipartHttpServletRequestBuilder<MockMultipartMvcRequestBuilder> implements AssertProvider<MvcTestResultAssert> { private MockMultipartMvcRequestBuilder(MockMvcRequestBuilder currentBuilder) { super(currentBuilder.httpMethod); merge(currentBuilder); } /** * Execute the request. If the request is processing asynchronously, * wait at most the given timeout value associated with the async request, * see {@link org.springframework.mock.web.MockAsyncContext#setTimeout}. * <p>For simple assertions, you can wrap this builder in * {@code assertThat} rather than calling this method explicitly: * <pre><code class="java"> * // These two examples are equivalent * assertThat(mvc.get().uri("/greet")).hasStatusOk(); * assertThat(mvc.get().uri("/greet").exchange()).hasStatusOk(); * </code></pre> * <p>For assertions on the original asynchronous request that might * still be in progress, use {@link #asyncExchange()}. * @see #exchange(Duration) to customize the timeout for async requests */ public MvcTestResult exchange() { return MockMvcTester.this.exchange(this, null); } /** * Execute the request and wait at most the given {@code timeToWait} * duration for the asynchronous request to complete. If the request * is not asynchronous, the {@code timeToWait} is ignored. * <p>For assertions on the original asynchronous request that might * still be in progress, use {@link #asyncExchange()}. * @see #exchange() */ public MvcTestResult exchange(Duration timeToWait) { return MockMvcTester.this.exchange(this, timeToWait); } /** * Execute the request and do not attempt to wait for the completion of * an asynchronous request. Contrary to {@link #exchange()}, this returns * the original result that might still be in progress. */ public MvcTestResult asyncExchange() { return MockMvcTester.this.perform(this); } @Override public MvcTestResultAssert assertThat() { return new MvcTestResultAssert(exchange(), MockMvcTester.this.converterDelegate); } } }
MockMultipartMvcRequestBuilder
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/ttl/TtlValue.java
{ "start": 995, "end": 1161 }
class ____ user value of state with TTL. Visibility is public for usage with external * tools. * * @param <T> Type of the user value of state with TTL */ public
wraps
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/criteria/JpaFetch.java
{ "start": 396, "end": 1314 }
interface ____<O,T> extends JpaFetchParent<O,T>, Fetch<O,T> { @Override Set<Fetch<T, ?>> getFetches(); @Override <Y> JpaFetch<T, Y> fetch(SingularAttribute<? super T, Y> attribute); @Override <Y> JpaFetch<T, Y> fetch(SingularAttribute<? super T, Y> attribute, JoinType jt); @Override <Y> JpaFetch<T, Y> fetch(PluralAttribute<? super T, ?, Y> attribute); @Override <Y> JpaFetch<T, Y> fetch(PluralAttribute<? super T, ?, Y> attribute, JoinType jt); @Override <X, Y> JpaFetch<X, Y> fetch(String attributeName); @Override <X, Y> JpaFetch<X, Y> fetch(String attributeName, JoinType jt); /** * Add a restriction to the fetch. * * @apiNote JPA does not allow restricting a fetch */ JpaJoin<O, T> on(JpaExpression<Boolean> restriction); /** * Add a restriction to the fetch. * * @apiNote JPA does not allow restricting a fetch */ JpaJoin<O, T> on(JpaPredicate... restrictions); }
JpaFetch
java
google__error-prone
core/src/test/java/com/google/errorprone/matchers/CompoundAssignmentTest.java
{ "start": 3190, "end": 3820 }
class ____ { public void getHash(int a, long b) { long c = a; c -= b; } } """); Set<Kind> operators = EnumSet.noneOf(Kind.class); operators.add(Kind.PLUS_ASSIGNMENT); assertCompiles( compoundAssignmentMatches( /* shouldMatch= */ false, new CompoundAssignment( operators, Matchers.<ExpressionTree>anything(), Matchers.<ExpressionTree>anything()))); } @Test public void shouldNotMatchWhenLeftOperandMatcherFails() { writeFile( "A.java", """ public
A
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MarkerLookupConfigTest.java
{ "start": 1555, "end": 3180 }
class ____ { public static final Marker PAYLOAD = MarkerManager.getMarker("PAYLOAD"); private static final String PAYLOAD_LOG = "Message in payload.log"; public static final Marker PERFORMANCE = MarkerManager.getMarker("PERFORMANCE"); private static final String PERFORMANCE_LOG = "Message in performance.log"; public static final Marker SQL = MarkerManager.getMarker("SQL"); private static final String SQL_LOG = "Message in sql.log"; @Test void test() throws IOException { final Logger logger = LogManager.getLogger(); logger.info(SQL, SQL_LOG); logger.info(PAYLOAD, PAYLOAD_LOG); logger.info(PERFORMANCE, PERFORMANCE_LOG); { final String log = FileUtils.readFileToString(new File("target/logs/sql.log"), StandardCharsets.UTF_8); assertTrue(log.contains(SQL_LOG)); assertFalse(log.contains(PAYLOAD_LOG)); assertFalse(log.contains(PERFORMANCE_LOG)); } { final String log = FileUtils.readFileToString(new File("target/logs/payload.log"), StandardCharsets.UTF_8); assertFalse(log.contains(SQL_LOG)); assertTrue(log.contains(PAYLOAD_LOG)); assertFalse(log.contains(PERFORMANCE_LOG)); } { final String log = FileUtils.readFileToString(new File("target/logs/performance.log"), StandardCharsets.UTF_8); assertFalse(log.contains(SQL_LOG)); assertFalse(log.contains(PAYLOAD_LOG)); assertTrue(log.contains(PERFORMANCE_LOG)); } } }
MarkerLookupConfigTest
java
apache__hadoop
hadoop-common-project/hadoop-kms/src/main/java/org/apache/hadoop/crypto/key/kms/server/KMSMDCFilter.java
{ "start": 1619, "end": 4060 }
class ____ { private final UserGroupInformation ugi; private final String method; private final String url; private final String remoteClientAddress; private Data(UserGroupInformation ugi, String method, String url, String remoteClientAddress) { this.ugi = ugi; this.method = method; this.url = url; this.remoteClientAddress = remoteClientAddress; } } private static final ThreadLocal<Data> DATA_TL = new ThreadLocal<Data>(); public static UserGroupInformation getUgi() { Data data = DATA_TL.get(); return data != null ? data.ugi : null; } public static String getMethod() { Data data = DATA_TL.get(); return data != null ? data.method : null; } public static String getURL() { Data data = DATA_TL.get(); return data != null ? data.url : null; } public static String getRemoteClientAddress() { Data data = DATA_TL.get(); return data != null ? data.remoteClientAddress : null; } @Override public void init(FilterConfig config) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { clearContext(); UserGroupInformation ugi = HttpUserGroupInformation.get(); HttpServletRequest httpServletRequest = (HttpServletRequest) request; String method = httpServletRequest.getMethod(); StringBuffer requestURL = httpServletRequest.getRequestURL(); String queryString = httpServletRequest.getQueryString(); if (queryString != null) { requestURL.append("?").append(queryString); } setContext(ugi, method, requestURL.toString(), request.getRemoteAddr()); chain.doFilter(request, response); } finally { clearContext(); } } @Override public void destroy() { } /** * Sets the context with the given parameters. * @param ugi the {@link UserGroupInformation} for the current request. * @param method the http method * @param requestURL the requested URL. * @param remoteAddr the remote address of the client. */ @VisibleForTesting public static void setContext(UserGroupInformation ugi, String method, String requestURL, String remoteAddr) { DATA_TL.set(new Data(ugi, method, requestURL, remoteAddr)); } private static void clearContext() { DATA_TL.remove(); } }
Data
java
quarkusio__quarkus
extensions/kubernetes-config/runtime/src/main/java/io/quarkus/kubernetes/config/runtime/SecretConfigSourceUtil.java
{ "start": 2328, "end": 3256 }
class ____ extends MapBackedConfigSource { private static final String NAME_FORMAT = "SecretStringInputPropertiesConfigSource[secret=%s,file=%s]"; SecretStringInputPropertiesConfigSource(String secretName, String fileName, String input, int ordinal) { super(String.format(NAME_FORMAT, secretName, fileName), readProperties(decodeValue(input)), ordinal); } @SuppressWarnings({ "rawtypes", "unchecked" }) private static Map<String, String> readProperties(String rawData) { try (StringReader br = new StringReader(rawData)) { final Properties properties = new Properties(); properties.load(br); return (Map<String, String>) (Map) properties; } catch (IOException e) { throw new UncheckedIOException(e); } } } private static
SecretStringInputPropertiesConfigSource
java
dropwizard__dropwizard
dropwizard-example/src/main/java/com/example/helloworld/filter/DateRequiredFeature.java
{ "start": 227, "end": 542 }
class ____ implements DynamicFeature { @Override public void configure(ResourceInfo resourceInfo, FeatureContext context) { if (resourceInfo.getResourceMethod().getAnnotation(DateRequired.class) != null) { context.register(DateNotSpecifiedFilter.class); } } }
DateRequiredFeature
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/convention/TestBeanByNameLookupTestMethodScopedExtensionContextIntegrationTests.java
{ "start": 5578, "end": 5871 }
class ____ { @Bean("field") String bean1() { return "prod"; } @Bean("nestedField") String bean2() { return "nestedProd"; } @Bean("methodRenamed1") String bean3() { return "Prod"; } @Bean("methodRenamed2") String bean4() { return "NestedProd"; } } }
Config
java
apache__camel
components/camel-pg-replication-slot/src/test/java/org/apache/camel/component/pg/replication/slot/PgReplicationSlotEndpointTest.java
{ "start": 1204, "end": 3375 }
class ____ { @Test public void testUriParsing() { PgReplicationSlotEndpoint endpoint = null; PgReplicationSlotComponent component = mock(PgReplicationSlotComponent.class); endpoint = new PgReplicationSlotEndpoint("pg-replication-slot:/database/slot:plugin", component); assertEquals("database", endpoint.getDatabase()); assertEquals(Integer.valueOf(5432), endpoint.getPort()); assertEquals("localhost", endpoint.getHost()); assertEquals("slot", endpoint.getSlot()); assertEquals("plugin", endpoint.getOutputPlugin()); endpoint = new PgReplicationSlotEndpoint("pg-replication-slot:remote-server/database/slot:plugin", component); assertEquals("database", endpoint.getDatabase()); assertEquals(Integer.valueOf(5432), endpoint.getPort()); assertEquals("remote-server", endpoint.getHost()); assertEquals("slot", endpoint.getSlot()); assertEquals("plugin", endpoint.getOutputPlugin()); endpoint = new PgReplicationSlotEndpoint("pg-replication-slot:remote-server:333/database/slot:plugin", component); assertEquals("database", endpoint.getDatabase()); assertEquals(Integer.valueOf(333), endpoint.getPort()); assertEquals("remote-server", endpoint.getHost()); assertEquals("slot", endpoint.getSlot()); assertEquals("plugin", endpoint.getOutputPlugin()); endpoint = new PgReplicationSlotEndpoint("pg-replication-slot://remote-server:333/database/slot:plugin", component); assertEquals("database", endpoint.getDatabase()); assertEquals(Integer.valueOf(333), endpoint.getPort()); assertEquals("remote-server", endpoint.getHost()); assertEquals("slot", endpoint.getSlot()); assertEquals("plugin", endpoint.getOutputPlugin()); } @Test public void testParsingBadUri() { PgReplicationSlotComponent component = mock(PgReplicationSlotComponent.class); assertThrows(IllegalArgumentException.class, () -> new PgReplicationSlotEndpoint("pg-replication-slot:/database/slot", component)); } }
PgReplicationSlotEndpointTest
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/StackIdTests.java
{ "start": 1190, "end": 2637 }
class ____ { @Test @SuppressWarnings("NullAway") // Test null check void fromImageWhenImageIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> StackId.fromImage(null)) .withMessage("'image' must not be null"); } @Test void fromImageWhenLabelIsMissingHasNoId() { Image image = mock(Image.class); ImageConfig imageConfig = mock(ImageConfig.class); given(image.getConfig()).willReturn(imageConfig); StackId stackId = StackId.fromImage(image); assertThat(stackId.hasId()).isFalse(); } @Test void fromImageCreatesStackId() { Image image = mock(Image.class); ImageConfig imageConfig = mock(ImageConfig.class); given(image.getConfig()).willReturn(imageConfig); given(imageConfig.getLabels()).willReturn(Collections.singletonMap("io.buildpacks.stack.id", "test")); StackId stackId = StackId.fromImage(image); assertThat(stackId).hasToString("test"); assertThat(stackId.hasId()).isTrue(); } @Test void ofCreatesStackId() { StackId stackId = StackId.of("test"); assertThat(stackId).hasToString("test"); } @Test void equalsAndHashCode() { StackId s1 = StackId.of("a"); StackId s2 = StackId.of("a"); StackId s3 = StackId.of("b"); assertThat(s1).hasSameHashCodeAs(s2); assertThat(s1).isEqualTo(s1).isEqualTo(s2).isNotEqualTo(s3); } @Test void toStringReturnsValue() { StackId stackId = StackId.of("test"); assertThat(stackId).hasToString("test"); } }
StackIdTests
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest_manual.java
{ "start": 1294, "end": 1352 }
class ____ { public OrderType orderType; } }
Model
java
spring-projects__spring-boot
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/testing/springbootapplications/usingapplicationarguments/MyApplicationArgumentTests.java
{ "start": 1038, "end": 1293 }
class ____ { @Test void applicationArgumentsPopulated(@Autowired ApplicationArguments args) { assertThat(args.getOptionNames()).containsOnly("app.test"); assertThat(args.getOptionValues("app.test")).containsOnly("one"); } }
MyApplicationArgumentTests
java
grpc__grpc-java
binder/src/test/java/io/grpc/binder/LifecycleOnDestroyHelperTest.java
{ "start": 3036, "end": 3082 }
class ____ extends LifecycleService {} }
MyService
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/AuxServicesEvent.java
{ "start": 1098, "end": 2562 }
class ____ extends AbstractEvent<AuxServicesEventType> { private final String user; private final String serviceId; private final ByteBuffer serviceData; private final ApplicationId appId; private final Container container; public AuxServicesEvent(AuxServicesEventType eventType, ApplicationId appId) { this(eventType, null, appId, null, null); } public AuxServicesEvent(AuxServicesEventType eventType, Container container) { this(eventType, null, container.getContainerId().getApplicationAttemptId() .getApplicationId(), null, null, container); } public AuxServicesEvent(AuxServicesEventType eventType, String user, ApplicationId appId, String serviceId, ByteBuffer serviceData) { this(eventType, user, appId, serviceId, serviceData, null); } public AuxServicesEvent(AuxServicesEventType eventType, String user, ApplicationId appId, String serviceId, ByteBuffer serviceData, Container container) { super(eventType); this.user = user; this.appId = appId; this.serviceId = serviceId; this.serviceData = serviceData; this.container = container; } public String getServiceID() { return serviceId; } public ByteBuffer getServiceData() { return serviceData; } public String getUser() { return user; } public ApplicationId getApplicationID() { return appId; } public Container getContainer() { return container; } }
AuxServicesEvent
java
redisson__redisson
redisson/src/main/java/org/redisson/spring/cache/RedissonSpringCacheManager.java
{ "start": 4081, "end": 9939 }
class ____ resource names * that include the package path (e.g. "mypackage/myresource.txt"). * * @param redisson object * @param configLocation path * @param codec object */ public RedissonSpringCacheManager(RedissonClient redisson, String configLocation, Codec codec) { this.redisson = redisson; this.configLocation = configLocation; this.codec = codec; } /** * Defines possibility of storing {@code null} values. * <p> * Default is <code>true</code> * * @param allowNullValues stores if <code>true</code> */ public void setAllowNullValues(boolean allowNullValues) { this.allowNullValues = allowNullValues; } /** * Defines if cache aware of Spring-managed transactions. * If {@code true} put/evict operations are executed only for successful transaction in after-commit phase. * <p> * Default is <code>false</code> * * @param transactionAware cache is transaction aware if <code>true</code> */ public void setTransactionAware(boolean transactionAware) { this.transactionAware = transactionAware; } /** * Defines 'fixed' cache names. * A new cache instance will not be created in dynamic for non-defined names. * <p> * `null` parameter setups dynamic mode * * @param names of caches */ public void setCacheNames(Collection<String> names) { if (names != null) { for (String name : names) { getCache(name); } dynamic = false; } else { dynamic = true; } } /** * Set cache config location * * @param configLocation object */ public void setConfigLocation(String configLocation) { this.configLocation = configLocation; } /** * Set cache config mapped by cache name * * @param config object */ public void setConfig(Map<String, ? extends CacheConfig> config) { this.configMap = (Map<String, CacheConfig>) config; } /** * Set Redisson instance * * @param redisson instance */ public void setRedisson(RedissonClient redisson) { this.redisson = redisson; } /** * Set Codec instance shared between all Cache instances * * @param codec object */ public void setCodec(Codec codec) { this.codec = codec; } protected CacheConfig createDefaultConfig() { return new CacheConfig(); } @Override public Cache getCache(String name) { Cache cache = instanceMap.get(name); if (cache != null) { return cache; } if (!dynamic) { return cache; } CacheConfig config = configMap.get(name); if (config == null) { config = createDefaultConfig(); configMap.put(name, config); } if (config.getMaxIdleTime() == 0 && config.getTTL() == 0 && config.getMaxSize() == 0) { return createMap(name, config); } return createMapCache(name, config); } private Cache createMap(String name, CacheConfig config) { RMap<Object, Object> map = getMap(name, config); Cache cache = new RedissonCache(map, allowNullValues); if (transactionAware) { cache = new TransactionAwareCacheDecorator(cache); } Cache oldCache = instanceMap.putIfAbsent(name, cache); if (oldCache != null) { cache = oldCache; } return cache; } protected RMap<Object, Object> getMap(String name, CacheConfig config) { if (codec != null) { return redisson.getMap(name, codec); } return redisson.getMap(name); } private Cache createMapCache(String name, CacheConfig config) { RMapCache<Object, Object> map = getMapCache(name, config); Cache cache = new RedissonCache(map, config, allowNullValues); if (transactionAware) { cache = new TransactionAwareCacheDecorator(cache); } Cache oldCache = instanceMap.putIfAbsent(name, cache); if (oldCache != null) { cache = oldCache; } else { map.setMaxSize(config.getMaxSize(), config.getEvictionMode()); for (MapEntryListener listener : config.getListeners()) { map.addListener(listener); } } return cache; } protected RMapCache<Object, Object> getMapCache(String name, CacheConfig config) { if (codec != null) { return redisson.getMapCache(name, codec); } return redisson.getMapCache(name); } @Override public Collection<String> getCacheNames() { return Collections.unmodifiableSet(configMap.keySet()); } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @Override public void afterPropertiesSet() throws Exception { if (configLocation == null) { return; } Resource resource = resourceLoader.getResource(configLocation); try { this.configMap = (Map<String, CacheConfig>) CacheConfig.fromYAML(resource.getInputStream()); } catch (IOException e) { // try to read yaml try { this.configMap = (Map<String, CacheConfig>) CacheConfig.fromJSON(resource.getInputStream()); } catch (IOException e1) { e1.addSuppressed(e); throw new BeanDefinitionStoreException( "Could not parse cache configuration at [" + configLocation + "]", e1); } } } }
path
java
spring-projects__spring-boot
module/spring-boot-webmvc-test/src/test/java/org/springframework/boot/webmvc/test/autoconfigure/mockmvc/ExampleFilter.java
{ "start": 1278, "end": 1756 }
class ____ implements Filter, Ordered { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); ((HttpServletResponse) response).addHeader("x-test", "abc"); } @Override public void destroy() { } @Override public int getOrder() { return 0; } }
ExampleFilter
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/cleaner/JdbcConnectionContext.java
{ "start": 2258, "end": 2378 }
interface ____<R> { R apply(Connection c) throws Exception; } private JdbcConnectionContext() { } }
ConnectionFunction
java
quarkusio__quarkus
extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/ApplyReplicasToStatefulSetDecorator.java
{ "start": 338, "end": 932 }
class ____ extends NamedResourceDecorator<StatefulSetSpecFluent> { private final int replicas; public ApplyReplicasToStatefulSetDecorator(int replicas) { this(ANY, replicas); } public ApplyReplicasToStatefulSetDecorator(String statefulSetName, int replicas) { super(statefulSetName); this.replicas = replicas; } public void andThenVisit(StatefulSetSpecFluent statefulSetSpec, ObjectMeta resourceMeta) { if (this.replicas > 0) { statefulSetSpec.withReplicas(this.replicas); } } }
ApplyReplicasToStatefulSetDecorator
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2937/Issue2937Mapper.java
{ "start": 517, "end": 801 }
interface ____ { Issue2937Mapper INSTANCE = Mappers.getMapper( Issue2937Mapper.class ); Target map(Source source); @Condition default boolean isApplicable(Collection<?> collection) { return collection == null || collection.size() > 1; }
Issue2937Mapper
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/security/contexts/TestSecurityContextFactory.java
{ "start": 1567, "end": 1764 }
class ____ implements SecurityContext { @Override public <T> T runSecured(Callable<T> securedCallable) throws Exception { return null; } } }
TestSecurityContext
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/ITestS3AConfiguration.java
{ "start": 3892, "end": 25385 }
class ____ extends AbstractHadoopTestBase { private static final String EXAMPLE_ID = "AKASOMEACCESSKEY"; private static final String EXAMPLE_KEY = "RGV0cm9pdCBSZ/WQgY2xl/YW5lZCB1cAEXAMPLE"; private static final String AP_ILLEGAL_ACCESS = "ARN of type accesspoint cannot be passed as a bucket"; private static final String US_EAST_1 = "us-east-1"; private static final String STS_ENDPOINT = "sts.us-east-1.amazonaws.com"; private Configuration conf; private S3AFileSystem fs; private static final Logger LOG = LoggerFactory.getLogger(ITestS3AConfiguration.class); @TempDir private java.nio.file.Path tempDir; /** * Get the S3 client of the active filesystem. * @param reason why? * @return the client */ private S3Client getS3Client(String reason) { return requireNonNull(getS3AInternals().getAmazonS3Client(reason)); } /** * Get the internals of the active filesystem. * @return the internals */ private S3AInternals getS3AInternals() { return fs.getS3AInternals(); } /** * Test if custom endpoint is picked up. * <p> * The test expects {@link S3ATestConstants#CONFIGURATION_TEST_ENDPOINT} * to be defined in the Configuration * describing the endpoint of the bucket to which TEST_FS_S3A_NAME points * (i.e. "s3-eu-west-1.amazonaws.com" if the bucket is located in Ireland). * Evidently, the bucket has to be hosted in the region denoted by the * endpoint for the test to succeed. * <p> * More info and the list of endpoint identifiers: * @see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region">endpoint list</a>. * * @throws Exception */ @Test public void testEndpoint() throws Exception { conf = new Configuration(); String endpoint = conf.getTrimmed( S3ATestConstants.CONFIGURATION_TEST_ENDPOINT, ""); if (endpoint.isEmpty()) { LOG.warn("Custom endpoint test skipped as " + S3ATestConstants.CONFIGURATION_TEST_ENDPOINT + " config " + "setting was not detected"); } else { conf.set(Constants.ENDPOINT, endpoint); fs = S3ATestUtils.createTestFileSystem(conf); String endPointRegion = ""; // Differentiate handling of "s3-" and "s3." based endpoint identifiers String[] endpointParts = StringUtils.split(endpoint, '.'); if (endpointParts.length == 3) { endPointRegion = endpointParts[0].substring(3); } else if (endpointParts.length == 4) { endPointRegion = endpointParts[1]; } else { fail("Unexpected endpoint"); } String region = getS3AInternals().getBucketLocation(); assertEquals(endPointRegion, region, "Endpoint config setting and bucket location differ: "); } } @Test public void testProxyConnection() throws Exception { useFailFastConfiguration(); conf.set(Constants.PROXY_HOST, "127.0.0.1"); conf.setInt(Constants.PROXY_PORT, 1); String proxy = conf.get(Constants.PROXY_HOST) + ":" + conf.get(Constants.PROXY_PORT); expectFSCreateFailure(ConnectException.class, conf, "when using proxy " + proxy); } /** * Create a configuration designed to fail fast on network problems. */ protected void useFailFastConfiguration() { conf = new Configuration(); conf.setInt(Constants.MAX_ERROR_RETRIES, 2); conf.setInt(Constants.RETRY_LIMIT, 2); conf.set(RETRY_INTERVAL, "100ms"); } /** * Expect a filesystem to not be created from a configuration. * @return the exception intercepted * @throws Exception any other exception */ private <E extends Throwable> E expectFSCreateFailure( Class<E> clazz, Configuration conf, String text) throws Exception { return intercept(clazz, () -> { fs = S3ATestUtils.createTestFileSystem(conf); fs.listFiles(new Path("/"), false); return "expected failure creating FS " + text + " got " + fs; }); } @Test public void testProxyPortWithoutHost() throws Exception { useFailFastConfiguration(); conf.unset(Constants.PROXY_HOST); conf.setInt(Constants.PROXY_PORT, 1); IllegalArgumentException e = expectFSCreateFailure( IllegalArgumentException.class, conf, "Expected a connection error for proxy server"); String msg = e.toString(); if (!msg.contains(Constants.PROXY_HOST) && !msg.contains(Constants.PROXY_PORT)) { throw e; } } @Test public void testAutomaticProxyPortSelection() throws Exception { useFailFastConfiguration(); conf.unset(Constants.PROXY_PORT); conf.set(Constants.PROXY_HOST, "127.0.0.1"); conf.set(Constants.SECURE_CONNECTIONS, "true"); expectFSCreateFailure(ConnectException.class, conf, "Expected a connection error for proxy server"); conf.set(Constants.SECURE_CONNECTIONS, "false"); expectFSCreateFailure(ConnectException.class, conf, "Expected a connection error for proxy server"); } @Test public void testUsernameInconsistentWithPassword() throws Exception { useFailFastConfiguration(); conf.set(Constants.PROXY_HOST, "127.0.0.1"); conf.setInt(Constants.PROXY_PORT, 1); conf.set(Constants.PROXY_USERNAME, "user"); IllegalArgumentException e = expectFSCreateFailure( IllegalArgumentException.class, conf, "Expected a connection error for proxy server"); assertIsProxyUsernameError(e); } private void assertIsProxyUsernameError(final IllegalArgumentException e) { String msg = e.toString(); if (!msg.contains(Constants.PROXY_USERNAME) && !msg.contains(Constants.PROXY_PASSWORD)) { throw e; } } @Test public void testUsernameInconsistentWithPassword2() throws Exception { useFailFastConfiguration(); conf.set(Constants.PROXY_HOST, "127.0.0.1"); conf.setInt(Constants.PROXY_PORT, 1); conf.set(Constants.PROXY_PASSWORD, "password"); IllegalArgumentException e = expectFSCreateFailure( IllegalArgumentException.class, conf, "Expected a connection error for proxy server"); assertIsProxyUsernameError(e); } @Test public void testCredsFromCredentialProvider() throws Exception { // set up conf to have a cred provider final Configuration conf = new Configuration(); final File file = tempDir.resolve("test.jks").toFile(); final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider( file.toURI()); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, jks.toString()); provisionAccessKeys(conf); conf.set(Constants.ACCESS_KEY, EXAMPLE_ID + "LJM"); S3xLoginHelper.Login creds = S3AUtils.getAWSAccessKeys(new URI("s3a://foobar"), conf); assertEquals(EXAMPLE_ID, creds.getUser(), "AccessKey incorrect."); assertEquals(EXAMPLE_KEY, creds.getPassword(), "SecretKey incorrect."); } void provisionAccessKeys(final Configuration conf) throws Exception { // add our creds to the provider final CredentialProvider provider = CredentialProviderFactory.getProviders(conf).get(0); provider.createCredentialEntry(Constants.ACCESS_KEY, EXAMPLE_ID.toCharArray()); provider.createCredentialEntry(Constants.SECRET_KEY, EXAMPLE_KEY.toCharArray()); provider.flush(); } @Test public void testSecretFromCredentialProviderIDFromConfig() throws Exception { // set up conf to have a cred provider final Configuration conf = new Configuration(); final File file = tempDir.resolve("test.jks").toFile(); final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider( file.toURI()); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, jks.toString()); // add our creds to the provider final CredentialProvider provider = CredentialProviderFactory.getProviders(conf).get(0); provider.createCredentialEntry(Constants.SECRET_KEY, EXAMPLE_KEY.toCharArray()); provider.flush(); conf.set(Constants.ACCESS_KEY, EXAMPLE_ID); S3xLoginHelper.Login creds = S3AUtils.getAWSAccessKeys(new URI("s3a://foobar"), conf); assertEquals(EXAMPLE_ID, creds.getUser(), "AccessKey incorrect."); assertEquals(EXAMPLE_KEY, creds.getPassword(), "SecretKey incorrect."); } @Test public void testIDFromCredentialProviderSecretFromConfig() throws Exception { // set up conf to have a cred provider final Configuration conf = new Configuration(); final File file = tempDir.resolve("test.jks").toFile(); final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider( file.toURI()); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, jks.toString()); // add our creds to the provider final CredentialProvider provider = CredentialProviderFactory.getProviders(conf).get(0); provider.createCredentialEntry(Constants.ACCESS_KEY, EXAMPLE_ID.toCharArray()); provider.flush(); conf.set(Constants.SECRET_KEY, EXAMPLE_KEY); S3xLoginHelper.Login creds = S3AUtils.getAWSAccessKeys(new URI("s3a://foobar"), conf); assertEquals(EXAMPLE_ID, creds.getUser(), "AccessKey incorrect."); assertEquals(EXAMPLE_KEY, creds.getPassword(), "SecretKey incorrect."); } @Test public void testExcludingS3ACredentialProvider() throws Exception { // set up conf to have a cred provider final Configuration conf = new Configuration(); final File file = tempDir.resolve("test.jks").toFile(); final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider( file.toURI()); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, "jceks://s3a/foobar," + jks.toString()); // first make sure that the s3a based provider is removed Configuration c = ProviderUtils.excludeIncompatibleCredentialProviders( conf, S3AFileSystem.class); String newPath = conf.get( CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH); assertFalse(newPath.contains("s3a://"), "Provider Path incorrect"); // now let's make sure the new path is created by the S3AFileSystem // and the integration still works. Let's provision the keys through // the altered configuration instance and then try and access them // using the original config with the s3a provider in the path. provisionAccessKeys(c); conf.set(Constants.ACCESS_KEY, EXAMPLE_ID + "LJM"); URI uri2 = new URI("s3a://foobar"); S3xLoginHelper.Login creds = S3AUtils.getAWSAccessKeys(uri2, conf); assertEquals(EXAMPLE_ID, creds.getUser(), "AccessKey incorrect."); assertEquals(EXAMPLE_KEY, creds.getPassword(), "SecretKey incorrect."); } @Test public void shouldBeAbleToSwitchOnS3PathStyleAccessViaConfigProperty() throws Exception { conf = new Configuration(); skipIfCrossRegionClient(conf); unsetEncryption(conf); conf.set(Constants.PATH_STYLE_ACCESS, Boolean.toString(true)); assertTrue(conf.getBoolean(Constants.PATH_STYLE_ACCESS, false)); try { fs = S3ATestUtils.createTestFileSystem(conf); assertNotNull(fs); S3Client s3 = getS3Client("configuration"); SdkClientConfiguration clientConfiguration = getField(s3, SdkClientConfiguration.class, "clientConfiguration"); S3Configuration s3Configuration = (S3Configuration)clientConfiguration.option(SdkClientOption.SERVICE_CONFIGURATION); assertTrue(s3Configuration.pathStyleAccessEnabled(), "Expected to find path style access to be switched on!"); byte[] file = ContractTestUtils.toAsciiByteArray("test file"); ContractTestUtils.writeAndRead(fs, createTestPath(new Path("/path/style/access/testFile")), file, file.length, (int) conf.getLongBytes(Constants.FS_S3A_BLOCK_SIZE, file.length), false, true); } catch (final AWSRedirectException e) { LOG.error("Caught exception: ", e); // Catch/pass standard path style access behaviour when live bucket // isn't in the same region as the s3 client default. See // http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html assertEquals(HttpStatus.SC_MOVED_PERMANENTLY, e.statusCode()); } catch (final IllegalArgumentException e) { // Path style addressing does not work with AP ARNs if (!fs.getBucket().contains("arn:")) { LOG.error("Caught unexpected exception: ", e); throw e; } GenericTestUtils.assertExceptionContains(AP_ILLEGAL_ACCESS, e); } } @Test public void testDefaultUserAgent() throws Exception { conf = new Configuration(); skipIfCrossRegionClient(conf); unsetEncryption(conf); fs = S3ATestUtils.createTestFileSystem(conf); assertNotNull(fs); S3Client s3 = getS3Client("User Agent"); SdkClientConfiguration clientConfiguration = getField(s3, SdkClientConfiguration.class, "clientConfiguration"); assertThat(clientConfiguration.option(SdkClientOption.CLIENT_USER_AGENT)) .describedAs("User Agent prefix") .startsWith("Hadoop " + VersionInfo.getVersion()); } @Test public void testCustomUserAgent() throws Exception { conf = new Configuration(); skipIfCrossRegionClient(conf); unsetEncryption(conf); conf.set(Constants.USER_AGENT_PREFIX, "MyApp"); fs = S3ATestUtils.createTestFileSystem(conf); assertNotNull(fs); S3Client s3 = getS3Client("User agent"); SdkClientConfiguration clientConfiguration = getField(s3, SdkClientConfiguration.class, "clientConfiguration"); assertThat(clientConfiguration.option(SdkClientOption.CLIENT_USER_AGENT)) .describedAs("User Agent prefix") .startsWith("MyApp, Hadoop " + VersionInfo.getVersion()); } @Test public void testRequestTimeout() throws Exception { conf = new Configuration(); skipIfCrossRegionClient(conf); // remove the safety check on minimum durations. AWSClientConfig.setMinimumOperationDuration(Duration.ZERO); try { Duration timeout = Duration.ofSeconds(120); conf.set(REQUEST_TIMEOUT, timeout.getSeconds() + "s"); fs = S3ATestUtils.createTestFileSystem(conf); SdkClient s3 = getS3Client("Request timeout (ms)"); if (s3 instanceof S3EncryptionClient) { s3 = ((S3EncryptionClient) s3).delegate(); } SdkClientConfiguration clientConfiguration = getField(s3, SdkClientConfiguration.class, "clientConfiguration"); assertThat(clientConfiguration.option(SdkClientOption.API_CALL_ATTEMPT_TIMEOUT)) .describedAs("Configured " + REQUEST_TIMEOUT + " is different than what AWS sdk configuration uses internally") .isEqualTo(timeout); } finally { AWSClientConfig.resetMinimumOperationDuration(); } } @Test public void testCloseIdempotent() throws Throwable { conf = new Configuration(); fs = S3ATestUtils.createTestFileSystem(conf); AWSCredentialProviderList credentials = getS3AInternals().shareCredentials("testCloseIdempotent"); credentials.close(); fs.close(); assertTrue(credentials.isClosed(), "Closing FS didn't close credentials " + credentials); assertEquals(0, credentials.getRefCount(), "refcount not zero in " + credentials); fs.close(); // and the numbers should not change assertEquals(0, credentials.getRefCount(), "refcount not zero in " + credentials); } @Test public void testDirectoryAllocatorDefval() throws Throwable { removeAllocatorContexts(); conf = new Configuration(); final String bucketName = getTestBucketName(conf); final String blank = " "; conf.set(Constants.BUFFER_DIR, blank); conf.set(format("fs.s3a.bucket.%s.buffer.dir", bucketName), blank); try { fs = S3ATestUtils.createTestFileSystem(conf); final Configuration fsConf = fs.getConf(); assertThat(fsConf.get(Constants.BUFFER_DIR)) .describedAs("Config option %s", Constants.BUFFER_DIR) .isEqualTo(blank); File tmp = createTemporaryFileForWriting(); assertTrue(tmp.exists(), "not found: " + tmp); tmp.delete(); } finally { removeAllocatorContexts(); } } private static void removeAllocatorContexts() { LocalDirAllocator.removeContext(BUFFER_DIR); LocalDirAllocator.removeContext(HADOOP_TMP_DIR); } /** * Create a temporary file for writing; requires the FS to have been created/initialized. * @return a temporary file * @throws IOException creation issues. */ private File createTemporaryFileForWriting() throws IOException { return fs.getS3AInternals().getStore().createTemporaryFileForWriting("out-", 1024, conf); } @Test public void testDirectoryAllocatorRR() throws Throwable { removeAllocatorContexts(); File dir1 = GenericTestUtils.getRandomizedTestDir(); File dir2 = GenericTestUtils.getRandomizedTestDir(); dir1.mkdirs(); dir2.mkdirs(); conf = new Configuration(); final String bucketName = getTestBucketName(conf); final String dirs = dir1 + ", " + dir2; conf.set(Constants.BUFFER_DIR, dirs); conf.set(format("fs.s3a.bucket.%s.buffer.dir", bucketName), dirs); fs = S3ATestUtils.createTestFileSystem(conf); final Configuration fsConf = fs.getConf(); assertThat(fsConf.get(Constants.BUFFER_DIR)) .describedAs("Config option %s", Constants.BUFFER_DIR) .isEqualTo(dirs); File tmp1 = createTemporaryFileForWriting(); tmp1.delete(); File tmp2 = createTemporaryFileForWriting(); tmp2.delete(); assertNotEquals(tmp1.getParent(), tmp2.getParent(), "round robin not working"); } @Test public void testUsernameFromUGI() throws Throwable { final String alice = "alice"; UserGroupInformation fakeUser = UserGroupInformation.createUserForTesting(alice, new String[]{"users", "administrators"}); conf = new Configuration(); fs = fakeUser.doAs(new PrivilegedExceptionAction<S3AFileSystem>() { @Override public S3AFileSystem run() throws Exception{ return S3ATestUtils.createTestFileSystem(conf); } }); assertEquals(alice, fs.getUsername(), "username"); FileStatus status = fs.getFileStatus(new Path("/")); assertEquals(alice, status.getOwner(), "owner in " + status); assertEquals(alice, status.getGroup(), "group in " + status); } /** * Reads and returns a field from an object using reflection. If the field * cannot be found, is null, or is not the expected type, then this method * fails the test. * * @param target object to read * @param fieldType type of field to read, which will also be the return type * @param fieldName name of field to read * @return field that was read * @throws IllegalAccessException if access not allowed */ private static <T> T getField(Object target, Class<T> fieldType, String fieldName) throws IllegalAccessException { Object obj = FieldUtils.readField(target, fieldName, true); assertNotNull(obj, format( "Could not read field named %s in object with class %s.", fieldName, target.getClass().getName())); assertTrue(fieldType.isAssignableFrom(obj.getClass()), format( "Unexpected type found for field named %s, expected %s, actual %s.", fieldName, fieldType.getName(), obj.getClass().getName())); return fieldType.cast(obj); } @Test public void testConfOptionPropagationToFS() throws Exception { Configuration config = new Configuration(); String testFSName = config.getTrimmed(TEST_FS_S3A_NAME, ""); String bucket = new URI(testFSName).getHost(); setBucketOption(config, bucket, "propagation", "propagated"); fs = S3ATestUtils.createTestFileSystem(config); Configuration updated = fs.getConf(); assertOptionEquals(updated, "fs.s3a.propagation", "propagated"); } @Test @Timeout(10) public void testS3SpecificSignerOverride() throws Exception { Configuration config = new Configuration(); removeBaseAndBucketOverrides(config, CUSTOM_SIGNERS, SIGNING_ALGORITHM_S3, SIGNING_ALGORITHM_STS, AWS_REGION); config.set(CUSTOM_SIGNERS, "CustomS3Signer:" + CustomS3Signer.class.getName() + ",CustomSTSSigner:" + CustomSTSSigner.class.getName()); config.set(SIGNING_ALGORITHM_S3, "CustomS3Signer"); config.set(SIGNING_ALGORITHM_STS, "CustomSTSSigner"); config.set(AWS_REGION, EU_WEST_1); disableFilesystemCaching(config); fs = S3ATestUtils.createTestFileSystem(config); assumeStoreAwsHosted(fs); S3Client s3Client = getS3Client("testS3SpecificSignerOverride"); final String bucket = fs.getBucket(); StsClient stsClient = STSClientFactory.builder(config, bucket, new AnonymousAWSCredentialsProvider(), STS_ENDPOINT, US_EAST_1).build(); intercept(StsException.class, "", () -> stsClient.getSessionToken()); final IOException ioe = intercept(IOException.class, "", () -> Invoker.once("head", bucket, () -> s3Client.headBucket(HeadBucketRequest.builder().bucket(bucket).build()))); assertThat(CustomS3Signer.isS3SignerCalled()) .describedAs("Custom S3 signer not called").isTrue(); assertThat(CustomSTSSigner.isSTSSignerCalled()) .describedAs("Custom STS signer not called").isTrue(); } public static final
ITestS3AConfiguration
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java
{ "start": 671, "end": 10084 }
class ____ extends TestBase { private MockSettingsImpl<?> mockSettingsImpl = new MockSettingsImpl<Object>(); @Mock private InvocationListener invocationListener; @Mock private StubbingLookupListener stubbingLookupListener; @Test @SuppressWarnings("unchecked") public void shouldNotAllowSettingNullInterface() { assertThatThrownBy( () -> { mockSettingsImpl.extraInterfaces(List.class, null); }) .isInstanceOf(MockitoException.class) .hasMessageContaining("extraInterfaces() does not accept null parameters."); } @Test @SuppressWarnings("unchecked") public void shouldNotAllowNonInterfaces() { assertThatThrownBy( () -> { mockSettingsImpl.extraInterfaces(List.class, LinkedList.class); }) .isInstanceOf(MockitoException.class) .hasMessageContainingAll( "extraInterfaces() accepts only interfaces", "You passed following type: LinkedList which is not an interface."); } @Test @SuppressWarnings("unchecked") public void shouldNotAllowUsingTheSameInterfaceAsExtra() { assertThatThrownBy( () -> { mockSettingsImpl.extraInterfaces(List.class, LinkedList.class); }) .isInstanceOf(MockitoException.class) .hasMessageContainingAll( "extraInterfaces() accepts only interfaces.", "You passed following type: LinkedList which is not an interface."); } @Test @SuppressWarnings("unchecked") public void shouldNotAllowEmptyExtraInterfaces() { assertThatThrownBy( () -> { mockSettingsImpl.extraInterfaces(); }) .isInstanceOf(MockitoException.class) .hasMessageContaining("extraInterfaces() requires at least one interface."); } @Test @SuppressWarnings("unchecked") public void shouldNotAllowNullArrayOfExtraInterfaces() { assertThatThrownBy( () -> { mockSettingsImpl.extraInterfaces((Class<?>[]) null); }) .isInstanceOf(MockitoException.class) .hasMessageContaining("extraInterfaces() requires at least one interface."); } @Test @SuppressWarnings("unchecked") public void shouldAllowMultipleInterfaces() { // when mockSettingsImpl.extraInterfaces(List.class, Set.class); // then assertThat(mockSettingsImpl.getExtraInterfaces().size()).isEqualTo(2); assertThat(mockSettingsImpl.getExtraInterfaces()).contains(List.class); assertThat(mockSettingsImpl.getExtraInterfaces()).contains(Set.class); } @Test public void shouldSetMockToBeSerializable() { // when mockSettingsImpl.serializable(); // then assertThat(mockSettingsImpl.isSerializable()).isTrue(); } @Test public void shouldKnowIfIsSerializable() { // given assertThat(mockSettingsImpl.isSerializable()).isFalse(); // when mockSettingsImpl.serializable(); // then assertThat(mockSettingsImpl.isSerializable()).isTrue(); } @Test public void shouldAddVerboseLoggingListener() { // given assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl.verboseLogging(); // then assertThat(mockSettingsImpl.getInvocationListeners()) .extracting("class") .contains(VerboseMockInvocationLogger.class); } @Test public void shouldAddVerboseLoggingListenerOnlyOnce() { // given assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl.verboseLogging().verboseLogging(); // then assertThat(mockSettingsImpl.getInvocationListeners()).hasSize(1); } @Test @SuppressWarnings("unchecked") public void shouldAddInvocationListener() { // given assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl.invocationListeners(invocationListener); // then assertThat(mockSettingsImpl.getInvocationListeners()).contains(invocationListener); } @Test @SuppressWarnings("unchecked") public void canAddDuplicateInvocationListeners_ItsNotOurBusinessThere() { // given assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl .invocationListeners(invocationListener, invocationListener) .invocationListeners(invocationListener); // then assertThat(mockSettingsImpl.getInvocationListeners()) .containsSequence(invocationListener, invocationListener, invocationListener); } @Test public void validates_listeners() { assertThatThrownBy( () -> mockSettingsImpl.addListeners( new Object[] {}, new LinkedList<Object>(), "myListeners")) .hasMessageContaining("myListeners() requires at least one listener"); assertThatThrownBy( () -> mockSettingsImpl.addListeners( null, new LinkedList<Object>(), "myListeners")) .hasMessageContaining("myListeners() does not accept null vararg array"); assertThatThrownBy( () -> mockSettingsImpl.addListeners( new Object[] {null}, new LinkedList<Object>(), "myListeners")) .hasMessageContaining("myListeners() does not accept null listeners"); } @Test public void validates_stubbing_lookup_listeners() { assertThatThrownBy( () -> mockSettingsImpl.stubbingLookupListeners( new StubbingLookupListener[] {})) .hasMessageContaining("stubbingLookupListeners() requires at least one listener"); assertThatThrownBy(() -> mockSettingsImpl.stubbingLookupListeners(null)) .hasMessageContaining( "stubbingLookupListeners() does not accept null vararg array"); assertThatThrownBy( () -> mockSettingsImpl.stubbingLookupListeners( new StubbingLookupListener[] {null})) .hasMessageContaining("stubbingLookupListeners() does not accept null listeners"); } @Test public void validates_invocation_listeners() { assertThatThrownBy(() -> mockSettingsImpl.invocationListeners(new InvocationListener[] {})) .hasMessageContaining("invocationListeners() requires at least one listener"); assertThatThrownBy(() -> mockSettingsImpl.invocationListeners(null)) .hasMessageContaining("invocationListeners() does not accept null vararg array"); assertThatThrownBy( () -> mockSettingsImpl.invocationListeners(new InvocationListener[] {null})) .hasMessageContaining("invocationListeners() does not accept null listeners"); } @Test public void addListeners_has_empty_listeners_by_default() { assertThat(mockSettingsImpl.getInvocationListeners()).isEmpty(); assertThat(mockSettingsImpl.getStubbingLookupListeners()).isEmpty(); } @Test public void addListeners_shouldAddMockObjectListeners() { // when mockSettingsImpl.invocationListeners(invocationListener); mockSettingsImpl.stubbingLookupListeners(stubbingLookupListener); // then assertThat(mockSettingsImpl.getInvocationListeners()).contains(invocationListener); assertThat(mockSettingsImpl.getStubbingLookupListeners()).contains(stubbingLookupListener); } @Test public void addListeners_canAddDuplicateMockObjectListeners_ItsNotOurBusinessThere() { // when mockSettingsImpl .stubbingLookupListeners(stubbingLookupListener) .stubbingLookupListeners(stubbingLookupListener) .invocationListeners(invocationListener) .invocationListeners(invocationListener); // then assertThat(mockSettingsImpl.getInvocationListeners()) .containsSequence(invocationListener, invocationListener); assertThat(mockSettingsImpl.getStubbingLookupListeners()) .containsSequence(stubbingLookupListener, stubbingLookupListener); } @Test public void validates_strictness() { assertThatThrownBy(() -> mockSettingsImpl.strictness(null)) .hasMessageContaining("strictness() does not accept null parameter"); } }
MockSettingsImplTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/loading/WeightLoadable.java
{ "start": 1040, "end": 1162 }
interface ____ holds the {@link LoadingWeight} getter is required for corresponding * abstractions. */ @Internal public
that
java
apache__flink
flink-test-utils-parent/flink-test-utils/src/main/java/org/apache/flink/test/util/SQLJobClientMode.java
{ "start": 2183, "end": 2390 }
class ____ extends GatewayClientMode { public GatewaySqlClient(String host, int port) { super(host, port); } } /** Uses the Hive JDBC to submit jobs. */
GatewaySqlClient
java
google__auto
value/src/main/java/com/google/auto/value/processor/BuilderRequiredProperties.java
{ "start": 12433, "end": 14271 }
class ____ extends BuilderRequiredProperties { NoDefaults(ImmutableSet<Property> requiredProperties) { super(requiredProperties, primitivePropertiesIn(requiredProperties)); } private static ImmutableList<Property> primitivePropertiesIn( ImmutableSet<Property> properties) { return properties.stream().filter(p -> p.getKind().isPrimitive()).collect(toImmutableList()); } @Override String allRequiredBitmask( ImmutableList<Property> trackedProperties, int bitBase, int remainingBits) { // We have to be a bit careful with sign-extension. If we're using a byte and // the mask is 0xff, then we'll write -1 instead. The comparison set$0 == 0xff // would always fail since the byte value gets sign-extended to 0xffff_ffff. // We should also write -1 if this is not the last field. boolean minusOne = remainingBits >= 32 || remainingBits == 16 || remainingBits == 8; return minusOne ? "-1" : hex((1 << remainingBits) - 1); } /** * {@inheritDoc} * * <p>We check the bitmask for primitive properties, and null checks for non-primitive ones. */ @Override public String getAnyMissing() { Stream<String> primitiveConditions = bitmaskFields.stream().map(field -> field.name + " != " + field.allRequiredBitmask); Stream<String> nonPrimitiveConditions = requiredProperties.stream() .filter(p -> !trackedPropertyToIndex.containsKey(p)) .map(this::missingRequiredProperty); return Stream.concat(primitiveConditions, nonPrimitiveConditions).collect(joining("\n|| ")); } @Override public String getDefaultedBitmaskParameters() { return ""; } } /** Subclass for when there are Kotlin default properties. */ private static final
NoDefaults
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java
{ "start": 107769, "end": 107857 }
interface ____ { } @ComposedMyAliasedTransactional static
ComposedMyAliasedTransactional
java
apache__camel
core/camel-base/src/main/java/org/apache/camel/converter/IOConverter.java
{ "start": 9740, "end": 12816 }
class ____ // work in OSGi and other containers Class<?> answer = null; String name = objectStreamClass.getName(); if (exchange != null) { LOG.trace("Loading class {} using Camel ClassResolver", name); answer = exchange.getContext().getClassResolver().resolveClass(name); } if (answer == null) { LOG.trace("Loading class {} using JDK default implementation", name); answer = super.resolveClass(objectStreamClass); } return answer; } }; } } @Converter(order = 35) public static byte[] toBytes(InputStream stream) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(IOHelper.buffered(stream), bos); // no need to close the ByteArrayOutputStream as it's close() // implementation is noop return bos.toByteArray(); } @Converter(order = 36) public static byte[] toByteArray(ByteArrayOutputStream os) { return os.toByteArray(); } @Converter(order = 37) public static ByteBuffer covertToByteBuffer(InputStream is) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(is, os); return ByteBuffer.wrap(os.toByteArray()); } @Converter(order = 38) public static String toString(ByteArrayOutputStream os, Exchange exchange) throws IOException { return os.toString(ExchangeHelper.getCharset(exchange)); } @Converter(order = 39) public static InputStream toInputStream(ByteArrayOutputStream os) { // no buffering required as the complete byte array input is already // passed over as a whole return new ByteArrayInputStream(os.toByteArray()); } @Converter(order = 40) public static Properties toProperties(File file) throws IOException { return toProperties(new FileInputStream(file)); } @Converter(order = 41) public static Properties toProperties(InputStream is) throws IOException { Properties prop = new Properties(); try { prop.load(is); } finally { IOHelper.close(is); } return prop; } @Converter(order = 42) public static Properties toProperties(Reader reader) throws IOException { Properties prop = new Properties(); try { prop.load(reader); } finally { IOHelper.close(reader); } return prop; } @Converter(order = 43) public static Path toPath(File file) { return file.toPath(); } @Converter(order = 44) public static File toFile(Path path) { return path.toFile(); } @Converter(order = 45) public static Charset toCharset(String name) { return Charset.forName(name); } }
loading
java
spring-projects__spring-framework
spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java
{ "start": 34989, "end": 35108 }
class ____ { @PersistenceUnit private EntityManagerFactory emf; } public static
DefaultPrivatePersistenceUnitField
java
apache__flink
flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/KeyedStateTransformation.java
{ "start": 1856, "end": 5408 }
class ____<K, T> { /** The data set containing the data to bootstrap the operator state with. */ private final DataStream<T> stream; /** Checkpoint ID. */ private final long checkpointId; /** Local max parallelism for the bootstrapped operator. */ private final OptionalInt operatorMaxParallelism; /** Partitioner for the bootstrapping data set. */ private final KeySelector<T, K> keySelector; /** Type information for the key of the bootstrapped operator. */ private final TypeInformation<K> keyType; KeyedStateTransformation( DataStream<T> stream, long checkpointId, OptionalInt operatorMaxParallelism, KeySelector<T, K> keySelector, TypeInformation<K> keyType) { this.stream = stream; this.checkpointId = checkpointId; this.operatorMaxParallelism = operatorMaxParallelism; this.keySelector = keySelector; this.keyType = keyType; } /** * Applies the given {@link KeyedStateBootstrapFunction} on the keyed input. * * <p>The function will be called for every element in the input and can be used for writing * both keyed and operator state into a {@link Savepoint}. * * @param processFunction The {@link KeyedStateBootstrapFunction} that is called for each * element. * @return An {@link StateBootstrapTransformation} that can be added to a {@link Savepoint}. */ public StateBootstrapTransformation<T> transform( KeyedStateBootstrapFunction<K, T> processFunction) { SavepointWriterOperatorFactory factory = (timestamp, path) -> SimpleOperatorFactory.of( new KeyedStateBootstrapOperator<>( checkpointId, timestamp, path, processFunction)); return transform(factory); } /** * Method for passing user defined operators along with the type information that will transform * the OperatorTransformation. * * <p><b>IMPORTANT:</b> Any output from this operator will be discarded. * * @param factory A factory returning transformation logic type of the return stream * @return An {@link StateBootstrapTransformation} that can be added to a {@link Savepoint}. */ public StateBootstrapTransformation<T> transform(SavepointWriterOperatorFactory factory) { return new StateBootstrapTransformation<>( stream, operatorMaxParallelism, factory, keySelector, keyType); } /** * Windows this transformation into a {@code WindowedOperatorTransformation}, which bootstraps * state that can be restored by a {@code WindowOperator}. Elements are put into windows by a * {@link WindowAssigner}. The grouping of elements is done both by key and by window. * * <p>A {@link org.apache.flink.streaming.api.windowing.triggers.Trigger} can be defined to * specify when windows are evaluated. However, {@code WindowAssigners} have a default {@code * Trigger} that is used if a {@code Trigger} is not specified. * * @param assigner The {@code WindowAssigner} that assigns elements to windows. */ public <W extends Window> WindowedStateTransformation<T, K, W> window( WindowAssigner<? super T, W> assigner) { return new WindowedStateTransformation<>( stream, checkpointId, operatorMaxParallelism, keySelector, keyType, assigner); } }
KeyedStateTransformation
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/client/PubSubApiClient.java
{ "start": 3339, "end": 12813 }
class ____ extends ServiceSupport { public static final String PUBSUB_ERROR_AUTH_ERROR = "sfdc.platform.eventbus.grpc.service.auth.error"; private static final String PUBSUB_ERROR_AUTH_REFRESH_INVALID = "sfdc.platform.eventbus.grpc.service.auth.refresh.invalid"; public static final String PUBSUB_ERROR_CORRUPTED_REPLAY_ID = "sfdc.platform.eventbus.grpc.subscription.fetch.replayid.corrupted"; protected PubSubGrpc.PubSubStub asyncStub; protected PubSubGrpc.PubSubBlockingStub blockingStub; protected String accessToken; private final long backoffIncrement; private final long maxBackoff; private long reconnectDelay; private final String pubSubHost; private final int pubSubPort; private final boolean allowUseProxyServer; private final Logger LOG = LoggerFactory.getLogger(getClass()); private final SalesforceLoginConfig loginConfig; private final SalesforceSession session; private final Map<String, Schema> schemaCache = new ConcurrentHashMap<>(); private final Map<String, String> schemaJsonCache = new ConcurrentHashMap<>(); private final Map<String, TopicInfo> topicInfoCache = new ConcurrentHashMap<>(); private final ConcurrentHashMap<PubSubApiConsumer, StreamObserver<FetchRequest>> observerMap = new ConcurrentHashMap<>(); private ManagedChannel channel; private boolean usePlainTextConnection = false; private ReplayPreset initialReplayPreset; private String initialReplayId; private boolean fallbackToLatestReplayId; public PubSubApiClient(SalesforceSession session, SalesforceLoginConfig loginConfig, String pubSubHost, int pubSubPort, long backoffIncrement, long maxBackoff, boolean allowUseProxyServer) { this.session = session; this.loginConfig = loginConfig; this.pubSubHost = pubSubHost; this.pubSubPort = pubSubPort; this.maxBackoff = maxBackoff; this.backoffIncrement = backoffIncrement; this.reconnectDelay = backoffIncrement; this.allowUseProxyServer = allowUseProxyServer; } public List<org.apache.camel.component.salesforce.api.dto.pubsub.PublishResult> publishMessage( String topic, List<?> bodies) throws IOException { LOG.debug("Preparing to publish on topic {}", topic); TopicInfo topicInfo = getTopicInfo(topic); String busTopicName = topicInfo.getTopicName(); Schema schema = getSchema(topicInfo.getSchemaId()); List<ProducerEvent> events = new ArrayList<>(bodies.size()); for (Object body : bodies) { final ProducerEvent event = createProducerEvent(topicInfo.getSchemaId(), schema, body); events.add(event); } PublishRequest publishRequest = PublishRequest.newBuilder() .setTopicName(busTopicName) .addAllEvents(events) .build(); PublishResponse response = blockingStub.publish(publishRequest); LOG.debug("Published on topic {}", topic); final List<PublishResult> results = response.getResultsList(); List<org.apache.camel.component.salesforce.api.dto.pubsub.PublishResult> publishResults = new ArrayList<>(results.size()); for (PublishResult rawResult : results) { if (rawResult.hasError()) { LOG.error("{} {} ", rawResult.getError().getCode(), rawResult.getError().getMsg()); } publishResults.add( new org.apache.camel.component.salesforce.api.dto.pubsub.PublishResult(rawResult)); } return publishResults; } public void subscribe( PubSubApiConsumer consumer, ReplayPreset replayPreset, String initialReplayId, boolean fallbackToLatestReplayId) { LOG.debug("Starting subscribe {}", consumer.getTopic()); this.initialReplayPreset = replayPreset; this.initialReplayId = initialReplayId; this.fallbackToLatestReplayId = fallbackToLatestReplayId; if (replayPreset == ReplayPreset.CUSTOM && initialReplayId == null) { throw new RuntimeException("initialReplayId is required for ReplayPreset.CUSTOM"); } String topic = consumer.getTopic(); ByteString replayId = null; if (initialReplayId != null) { replayId = base64DecodeToByteString(initialReplayId); } LOG.info("Subscribing to topic: {}.", topic); final FetchResponseObserver responseObserver = new FetchResponseObserver(consumer); StreamObserver<FetchRequest> serverStream = asyncStub.subscribe(responseObserver); LOG.info("Subscribe successful."); responseObserver.setServerStream(serverStream); observerMap.put(consumer, serverStream); FetchRequest.Builder fetchRequestBuilder = FetchRequest.newBuilder() .setReplayPreset(replayPreset) .setTopicName(topic) .setNumRequested(consumer.getBatchSize()); if (replayPreset == ReplayPreset.CUSTOM) { fetchRequestBuilder.setReplayId(replayId); } serverStream.onNext(fetchRequestBuilder.build()); } public TopicInfo getTopicInfo(String name) { return topicInfoCache.computeIfAbsent(name, topic -> blockingStub.getTopic(TopicRequest.newBuilder().setTopicName(topic).build())); } public String getSchemaJson(String schemaId) { return schemaJsonCache.computeIfAbsent(schemaId, s -> blockingStub.getSchema(SchemaRequest.newBuilder().setSchemaId(s).build()).getSchemaJson()); } public Schema getSchema(String schemaId) { return schemaCache.computeIfAbsent(schemaId, id -> (new Schema.Parser()).parse(getSchemaJson(id))); } public static String base64EncodeByteString(ByteString bs) { var bb = bs.asReadOnlyByteBuffer(); bb.position(0); byte[] bytes = new byte[bb.limit()]; bb.get(bytes, 0, bytes.length); return Base64.getEncoder().encodeToString(bytes); } public static ByteString base64DecodeToByteString(String b64) { final byte[] decode = Base64.getDecoder().decode(b64); return ByteString.copyFrom(decode); } @Override protected void doStart() throws Exception { super.doStart(); final ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder .forAddress(pubSubHost, pubSubPort); if (!allowUseProxyServer) { channelBuilder.proxyDetector(socketAddress -> null); } if (usePlainTextConnection) { channelBuilder.usePlaintext(); } channel = channelBuilder.build(); TokenCredentials callCredentials = new TokenCredentials(session); this.asyncStub = PubSubGrpc.newStub(channel).withCallCredentials(callCredentials); this.blockingStub = PubSubGrpc.newBlockingStub(channel).withCallCredentials(callCredentials); // accessToken could be null accessToken = session.getAccessToken(); if (accessToken == null && !loginConfig.isLazyLogin()) { try { accessToken = session.login(null); } catch (SalesforceException e) { throw new RuntimeException(e); } } } @Override protected void doStop() throws Exception { LOG.debug("Stopping PubSubApiClient"); // stop each open stream observerMap.values().forEach(observer -> { LOG.debug("Stopping subscription"); observer.onCompleted(); }); channel.shutdown(); channel.awaitTermination(10, TimeUnit.SECONDS); super.doStop(); } private ProducerEvent createProducerEvent(String schemaId, Schema schema, Object body) throws IOException { if (body instanceof ProducerEvent e) { return e; } byte[] bytes; if (body instanceof IndexedRecord indexedRecord) { if (body instanceof GenericRecord genericRecord) { bytes = getBytes(body, new GenericDatumWriter<>(genericRecord.getSchema())); } else if (body instanceof SpecificRecord) { bytes = getBytes(body, new SpecificDatumWriter<>()); } else { throw new IllegalArgumentException( "Body is of unexpected type: " + indexedRecord.getClass().getName()); } } else if (body instanceof byte[] bodyBytes) { bytes = bodyBytes; } else if (body instanceof String json) { JsonAvroConverter converter = new JsonAvroConverter(); bytes = converter.convertToAvro(json.getBytes(), schema); } else { // try serializing as POJO bytes = getBytes(body, new ReflectDatumWriter<>(schema)); } return ProducerEvent.newBuilder() .setSchemaId(schemaId) .setPayload(ByteString.copyFrom(bytes)) .build(); } private byte[] getBytes(Object body, DatumWriter<Object> writer) throws IOException { byte[] bytes; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); BinaryEncoder encoder = EncoderFactory.get().directBinaryEncoder(buffer, null); writer.write(body, encoder); bytes = buffer.toByteArray(); return bytes; } private
PubSubApiClient
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/GenericManyToOneParameterTest.java
{ "start": 3200, "end": 3551 }
class ____ implements Site { @Id protected Long id; private String name; public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity( name = "UserSiteImpl" ) public static
SiteImpl
java
apache__kafka
server-common/src/main/java/org/apache/kafka/server/share/persister/ReadShareGroupStateResult.java
{ "start": 2740, "end": 3114 }
class ____ { private List<TopicData<PartitionAllData>> topicsData; public Builder setTopicsData(List<TopicData<PartitionAllData>> topicsData) { this.topicsData = topicsData; return this; } public ReadShareGroupStateResult build() { return new ReadShareGroupStateResult(topicsData); } } }
Builder
java
quarkusio__quarkus
extensions/devui/runtime/src/main/java/io/quarkus/devui/runtime/jsonrpc/JsonRpcResponse.java
{ "start": 125, "end": 845 }
class ____ { // Public for serialization public final int id; public final Object result; public final Error error; public JsonRpcResponse(int id, Object result) { this.id = id; this.result = result; this.error = null; } public JsonRpcResponse(int id, Error error) { this.id = id; this.result = null; this.error = error; } public String getJsonrpc() { return VERSION; } @Override public String toString() { return "JsonRpcResponse{" + "id=" + id + ", result=" + result + ", error=" + error + '}'; } public static final
JsonRpcResponse
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/ThreadCache.java
{ "start": 13089, "end": 13683 }
class ____ { private final Bytes key; private final byte[] newValue; private final LRUCacheEntry recordContext; DirtyEntry(final Bytes key, final byte[] newValue, final LRUCacheEntry recordContext) { this.key = key; this.newValue = newValue; this.recordContext = recordContext; } public Bytes key() { return key; } public byte[] newValue() { return newValue; } public LRUCacheEntry entry() { return recordContext; } } }
DirtyEntry
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/task/support/ExecutorServiceAdapter.java
{ "start": 1847, "end": 3242 }
class ____ extends AbstractExecutorService { private final TaskExecutor taskExecutor; /** * Create a new ExecutorServiceAdapter, using the given target executor. * @param taskExecutor the target executor to delegate to */ public ExecutorServiceAdapter(TaskExecutor taskExecutor) { Assert.notNull(taskExecutor, "TaskExecutor must not be null"); this.taskExecutor = taskExecutor; } @Override public void execute(Runnable task) { this.taskExecutor.execute(task); } @Override public void shutdown() { throw new IllegalStateException( "Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle"); } @Override public List<Runnable> shutdownNow() { throw new IllegalStateException( "Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle"); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { throw new IllegalStateException( "Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle"); } @Override public boolean isShutdown() { return false; } @Override public boolean isTerminated() { return false; } // @Override on JDK 19 public void close() { // no-op in order to avoid container-triggered shutdown call which would lead to exception logging } }
ExecutorServiceAdapter
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/callbacks/CallbackMethodTest.java
{ "start": 1048, "end": 10155 }
class ____ { @BeforeEach public void reset() { ClassContainingCallbacks.reset(); BaseMapper.reset(); } @ProcessorTest public void callbackMethodsForBeanMappingCalled() { SourceTargetMapper.INSTANCE.sourceToTarget( createSource() ); assertBeanMappingInvocations( ClassContainingCallbacks.getInvocations() ); assertBeanMappingInvocations( BaseMapper.getInvocations() ); } @ProcessorTest public void callbackMethodsForBeanMappingWithResultParamCalled() { SourceTargetMapper.INSTANCE.sourceToTarget( createSource(), createEmptyTarget() ); assertBeanMappingInvocations( ClassContainingCallbacks.getInvocations() ); assertBeanMappingInvocations( BaseMapper.getInvocations() ); } @ProcessorTest public void callbackMethodsForIterableMappingCalled() { SourceTargetCollectionMapper.INSTANCE.sourceToTarget( Arrays.asList( createSource() ) ); assertIterableMappingInvocations( ClassContainingCallbacks.getInvocations() ); assertIterableMappingInvocations( BaseMapper.getInvocations() ); } @ProcessorTest public void callbackMethodsForIterableMappingWithResultParamCalled() { SourceTargetCollectionMapper.INSTANCE.sourceToTarget( Arrays.asList( createSource() ), new ArrayList<>() ); assertIterableMappingInvocations( ClassContainingCallbacks.getInvocations() ); assertIterableMappingInvocations( BaseMapper.getInvocations() ); } @ProcessorTest public void callbackMethodsForMapMappingCalled() { SourceTargetCollectionMapper.INSTANCE.sourceToTarget( toMap( "foo", createSource() ) ); assertMapMappingInvocations( ClassContainingCallbacks.getInvocations() ); assertMapMappingInvocations( BaseMapper.getInvocations() ); } @ProcessorTest public void callbackMethodsForMapMappingWithResultParamCalled() { SourceTargetCollectionMapper.INSTANCE.sourceToTarget( toMap( "foo", createSource() ), new HashMap<>() ); assertMapMappingInvocations( ClassContainingCallbacks.getInvocations() ); assertMapMappingInvocations( BaseMapper.getInvocations() ); } @ProcessorTest public void qualifiersAreEvaluatedCorrectly() { Source source = createSource(); Target target = SourceTargetMapper.INSTANCE.qualifiedSourceToTarget( source ); assertQualifiedInvocations( ClassContainingCallbacks.getInvocations(), source, target ); assertQualifiedInvocations( BaseMapper.getInvocations(), source, target ); reset(); List<Source> sourceList = Arrays.asList( createSource() ); List<Target> targetList = SourceTargetCollectionMapper.INSTANCE.qualifiedSourceToTarget( sourceList ); assertQualifiedInvocations( ClassContainingCallbacks.getInvocations(), sourceList, targetList ); assertQualifiedInvocations( BaseMapper.getInvocations(), sourceList, targetList ); } @ProcessorTest public void callbackMethodsForEnumMappingCalled() { SourceEnum source = SourceEnum.B; TargetEnum target = SourceTargetMapper.INSTANCE.toTargetEnum( source ); List<Invocation> invocations = new ArrayList<>(); invocations.addAll( allBeforeMappingMethods( source, target, TargetEnum.class ) ); invocations.addAll( allAfterMappingMethods( source, target, TargetEnum.class ) ); assertThat( invocations ).isEqualTo( ClassContainingCallbacks.getInvocations() ); assertThat( invocations ).isEqualTo( BaseMapper.getInvocations() ); } private void assertBeanMappingInvocations(List<Invocation> invocations) { Source source = createSource(); Target target = createResultTarget(); Target emptyTarget = createEmptyTarget(); assertThat( invocations ).isEqualTo( beanMappingInvocationList( source, target, emptyTarget ) ); } private void assertIterableMappingInvocations(List<Invocation> invocations) { Source source = createSource(); List<Source> sourceList = Arrays.asList( source ); Target target = createResultTarget(); Target emptyTarget = createEmptyTarget(); List<Target> emptyTargetList = Collections.emptyList(); List<Target> targetList = Arrays.asList( target ); assertCollectionMappingInvocations( invocations, source, sourceList, target, emptyTarget, emptyTargetList, targetList, List.class ); } private void assertMapMappingInvocations(List<Invocation> invocations) { Source source = createSource(); Map<String, Source> sourceMap = toMap( "foo", source ); Target target = createResultTarget(); Target emptyTarget = createEmptyTarget(); Map<String, Target> emptyTargetMap = Collections.emptyMap(); Map<String, Target> targetMap = toMap( "foo", target ); assertCollectionMappingInvocations( invocations, source, sourceMap, target, emptyTarget, emptyTargetMap, targetMap, Map.class ); } private <T> Map<String, T> toMap(String string, T value) { Map<String, T> result = new HashMap<>(); result.put( string, value ); return result; } private void assertCollectionMappingInvocations(List<Invocation> invocations, Object source, Object sourceCollection, Object target, Object emptyTarget, Object emptyTargetCollection, Object targetCollection, Class<?> targetCollectionClass) { List<Invocation> expected = allBeforeMappingMethods( sourceCollection, emptyTargetCollection, targetCollectionClass ); expected.addAll( beanMappingInvocationList( source, target, emptyTarget ) ); expected.addAll( allAfterMappingMethods( sourceCollection, targetCollection, targetCollectionClass ) ); assertThat( invocations ).isEqualTo( expected ); } private List<Invocation> beanMappingInvocationList(Object source, Object target, Object emptyTarget) { List<Invocation> invocations = new ArrayList<>(); invocations.addAll( allBeforeMappingMethods( source, emptyTarget, Target.class ) ); invocations.addAll( allAfterMappingMethods( source, target, Target.class ) ); return invocations; } private List<Invocation> allAfterMappingMethods(Object source, Object target, Class<?> targetClass) { return new ArrayList<>( Arrays.asList( new Invocation( "noArgsAfterMapping" ), new Invocation( "withSourceAfterMapping", source ), new Invocation( "withSourceAsObjectAfterMapping", source ), new Invocation( "withSourceAndTargetAfterMapping", source, target ), new Invocation( "withTargetAfterMapping", target ), new Invocation( "withTargetAsObjectAfterMapping", target ), new Invocation( "withTargetAndTargetTypeAfterMapping", target, targetClass ) ) ); } private List<Invocation> allBeforeMappingMethods(Object source, Object emptyTarget, Class<?> targetClass) { return new ArrayList<>( Arrays.asList( new Invocation( "noArgsBeforeMapping" ), new Invocation( "withSourceBeforeMapping", source ), new Invocation( "withSourceAsObjectBeforeMapping", source ), new Invocation( "withSourceAndTargetTypeBeforeMapping", source, targetClass ), new Invocation( "withSourceAndTargetBeforeMapping", source, emptyTarget ), new Invocation( "withTargetBeforeMapping", emptyTarget ), new Invocation( "withTargetAsObjectBeforeMapping", emptyTarget ) ) ); } private void assertQualifiedInvocations(List<Invocation> actual, Object source, Object target) { assertThat( actual ).isEqualTo( allQualifiedCallbackMethods( source, target ) ); } private List<Invocation> allQualifiedCallbackMethods(Object source, Object target) { List<Invocation> invocations = new ArrayList<>(); invocations.add( new Invocation( "withSourceBeforeMappingQualified", source ) ); if ( source instanceof List || source instanceof Map ) { invocations.addAll( beanMappingInvocationList( createSource(), createResultTarget(), createEmptyTarget() ) ); } invocations.add( new Invocation( "withTargetAfterMappingQualified", target ) ); return invocations; } private Source createSource() { Source source = new Source(); source.setFoo( "foo" ); return source; } private Target createEmptyTarget() { return new Target(); } private Target createResultTarget() { Target target = createEmptyTarget(); target.setFoo( "foo" ); return target; } }
CallbackMethodTest
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java
{ "start": 6400, "end": 6497 }
class ____... } if (cl == null) { // No thread context
loader
java
apache__camel
components/camel-quartz/src/test/java/org/apache/camel/component/quartz/QuartzStopRouteTest.java
{ "start": 982, "end": 2120 }
class ____ extends BaseQuartzTest { @Test void testQuartzSuspend() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); mock.assertIsSatisfied(); context.getRouteController().stopRoute("foo"); mock.reset(); mock.expectedMessageCount(0); mock.assertIsSatisfied(3000); mock.reset(); mock.expectedMinimumMessageCount(1); context.getRouteController().startRoute("foo"); mock.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // START SNIPPET: e1 // triggers every second at precise 00,01,02,03..59 // notice we must use + as space when configured using URI parameter from("quartz://myGroup/myTimerName?cron=0/1+*+*+*+*+?") .routeId("foo") .to("log:result", "mock:result"); // END SNIPPET: e1 } }; } }
QuartzStopRouteTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/FSOperations.java
{ "start": 32410, "end": 33931 }
class ____ implements FileSystemAccess.FileSystemExecutor<JSONObject> { private Path path; private short permission; private short unmaskedPermission; /** * Creates a mkdirs executor. * * @param path directory path to create. * @param permission permission to use. * @param unmaskedPermission unmasked permissions for the directory */ public FSMkdirs(String path, short permission, short unmaskedPermission) { this.path = new Path(path); this.permission = permission; this.unmaskedPermission = unmaskedPermission; } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return <code>true</code> if the mkdirs operation was successful, * <code>false</code> otherwise. * * @throws IOException thrown if an IO error occurred. */ @Override public JSONObject execute(FileSystem fs) throws IOException { FsPermission fsPermission = new FsPermission(permission); if (unmaskedPermission != -1) { fsPermission = FsCreateModes.create(fsPermission, new FsPermission(unmaskedPermission)); } boolean mkdirs = fs.mkdirs(path, fsPermission); HttpFSServerWebApp.get().getMetrics().incrOpsMkdir(); return toJSON(HttpFSFileSystem.MKDIRS_JSON, mkdirs); } } /** * Executor that performs a open FileSystemAccess files system operation. */ @InterfaceAudience.Private public static
FSMkdirs
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java
{ "start": 1767, "end": 1937 }
class ____ org.apache.logging.log4j.core because it is used from LogEvent. * </p> * <p> * TODO: Deserialize: Try to rebuild Throwable if the target exception is in this
to
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conversion/bignumbers/BigIntegerMapper.java
{ "start": 285, "end": 520 }
interface ____ { BigIntegerMapper INSTANCE = Mappers.getMapper( BigIntegerMapper.class ); BigIntegerTarget sourceToTarget(BigIntegerSource source); BigIntegerSource targetToSource(BigIntegerTarget target); }
BigIntegerMapper
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeFilterSingle.java
{ "start": 1109, "end": 1577 }
class ____<T> extends Maybe<T> { final SingleSource<T> source; final Predicate<? super T> predicate; public MaybeFilterSingle(SingleSource<T> source, Predicate<? super T> predicate) { this.source = source; this.predicate = predicate; } @Override protected void subscribeActual(MaybeObserver<? super T> observer) { source.subscribe(new FilterMaybeObserver<>(observer, predicate)); } static final
MaybeFilterSingle
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/DoubleWritable.java
{ "start": 2301, "end": 2840 }
class ____ extends WritableComparator { public Comparator() { super(DoubleWritable.class); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { double thisValue = readDouble(b1, s1); double thatValue = readDouble(b2, s2); return Double.compare(thisValue, thatValue); } } static { // register this comparator WritableComparator.define(DoubleWritable.class, new Comparator()); } }
Comparator
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/writeClassName/WriteClassNameTest6.java
{ "start": 323, "end": 1001 }
class ____ extends TestCase { public void test_for_writeClassName() throws Exception { String json = "{\"@type\":\"java.util.HashMap\",\"@type\":\"com.alibaba.json.bvt.writeClassName.WriteClassNameTest6$Model\",\"id\":1001}"; Model model = (Model) JSON.parse(json); assertNotNull(model); } public void test_for_writeClassName_1() throws Exception { String json = "{\"@type\":\"java.util.HashMap\",\"@type\":\"com.alibaba.json.bvt.writeClassName.WriteClassNameTest6$Model\",\"id\":1001}"; Model model = JSON.parseObject(json, Model.class); assertNotNull(model); } @JSONType public static
WriteClassNameTest6
java
spring-projects__spring-security
access/src/main/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityMetadataSourceAdvisor.java
{ "start": 1860, "end": 2450 }
class ____ allows the use of Spring's {@code DefaultAdvisorAutoProxyCreator}, * which makes configuration easier than setup a <code>ProxyFactoryBean</code> for each * object requiring security. Note that autoproxying is not supported for BeanFactory * implementations, as post-processing is automatic only for application contexts. * <p> * Based on Spring's TransactionAttributeSourceAdvisor. * * @author Ben Alex * @author Luke Taylor * @deprecated Use {@link EnableMethodSecurity} or publish interceptors directly */ @NullUnmarked @Deprecated @SuppressWarnings("serial") public
also
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java
{ "start": 3715, "end": 19792 }
interface ____ { } static Stream<Arguments> clientHttpRequestFactories() { return Stream.of( argumentSet("JDK HttpURLConnection", new SimpleClientHttpRequestFactory()), argumentSet("HttpComponents", new HttpComponentsClientHttpRequestFactory()), argumentSet("Jetty", new JettyClientHttpRequestFactory()), argumentSet("JDK HttpClient", new JdkClientHttpRequestFactory()), argumentSet("Reactor Netty", new ReactorClientHttpRequestFactory()) ); } private RestTemplate template; private ClientHttpRequestFactory clientHttpRequestFactory; /** * Custom JUnit Jupiter extension that handles exceptions thrown by test methods. * * <p>If the test method throws an {@link HttpServerErrorException}, this * extension will throw an {@link AssertionError} that wraps the * {@code HttpServerErrorException} using the * {@link HttpServerErrorException#getResponseBodyAsString() response body} * as the failure message. * * <p>This mechanism provides an actually meaningful failure message if the * test fails due to an {@code AssertionError} on the server. */ @RegisterExtension TestExecutionExceptionHandler serverErrorToAssertionErrorConverter = (context, throwable) -> { if (throwable instanceof HttpServerErrorException ex) { String responseBody = ex.getResponseBodyAsString(); String prefix = AssertionError.class.getName() + ": "; if (responseBody.startsWith(prefix)) { responseBody = responseBody.substring(prefix.length()); } throw new AssertionError(responseBody, ex); } // Else throw as-is in order to comply with the contract of TestExecutionExceptionHandler. throw throwable; }; private void setUpClient(ClientHttpRequestFactory clientHttpRequestFactory) { this.clientHttpRequestFactory = clientHttpRequestFactory; this.template = new RestTemplate(this.clientHttpRequestFactory); } @ParameterizedRestTemplateTest void getString(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); String s = template.getForObject(baseUrl + "/{method}", String.class, "get"); assertThat(s).as("Invalid content").isEqualTo(helloWorld); } @ParameterizedRestTemplateTest void getEntity(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); ResponseEntity<String> entity = template.getForEntity(baseUrl + "/{method}", String.class, "get"); assertThat(entity.getBody()).as("Invalid content").isEqualTo(helloWorld); assertThat(entity.getHeaders().isEmpty()).as("No headers").isFalse(); assertThat(entity.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(textContentType); assertThat(entity.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); } @ParameterizedRestTemplateTest void getNoResponse(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); String s = template.getForObject(baseUrl + "/get/nothing", String.class); assertThat(s).as("Invalid content").isNull(); } @ParameterizedRestTemplateTest void getNoContentTypeHeader(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); byte[] bytes = template.getForObject(baseUrl + "/get/nocontenttype", byte[].class); assertThat(bytes).as("Invalid content").isEqualTo(helloWorld.getBytes(StandardCharsets.UTF_8)); } @ParameterizedRestTemplateTest void getNoContent(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); String s = template.getForObject(baseUrl + "/status/nocontent", String.class); assertThat(s).as("Invalid content").isNull(); ResponseEntity<String> entity = template.getForEntity(baseUrl + "/status/nocontent", String.class); assertThat(entity.getStatusCode()).as("Invalid response code").isEqualTo(HttpStatus.NO_CONTENT); assertThat(entity.getBody()).as("Invalid content").isNull(); } @ParameterizedRestTemplateTest void getNotModified(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); String s = template.getForObject(baseUrl + "/status/notmodified", String.class); assertThat(s).as("Invalid content").isNull(); ResponseEntity<String> entity = template.getForEntity(baseUrl + "/status/notmodified", String.class); assertThat(entity.getStatusCode()).as("Invalid response code").isEqualTo(HttpStatus.NOT_MODIFIED); assertThat(entity.getBody()).as("Invalid content").isNull(); } @ParameterizedRestTemplateTest void postForLocation(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); URI location = template.postForLocation(baseUrl + "/{method}", helloWorld, "post"); assertThat(location).as("Invalid location").isEqualTo(URI.create(baseUrl + "/post/1")); } @ParameterizedRestTemplateTest void postForLocationEntity(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.ISO_8859_1)); HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders); URI location = template.postForLocation(baseUrl + "/{method}", entity, "post"); assertThat(location).as("Invalid location").isEqualTo(URI.create(baseUrl + "/post/1")); } @ParameterizedRestTemplateTest void postForObject(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); String s = template.postForObject(baseUrl + "/{method}", helloWorld, String.class, "post"); assertThat(s).as("Invalid content").isEqualTo(helloWorld); } @ParameterizedRestTemplateTest void patchForObject(ClientHttpRequestFactory clientHttpRequestFactory) { assumeFalse(clientHttpRequestFactory instanceof SimpleClientHttpRequestFactory, "HttpURLConnection does not support the PATCH method"); setUpClient(clientHttpRequestFactory); String s = template.patchForObject(baseUrl + "/{method}", helloWorld, String.class, "patch"); assertThat(s).as("Invalid content").isEqualTo(helloWorld); } @ParameterizedRestTemplateTest void notFound(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); String url = baseUrl + "/status/notfound"; assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> template.execute(url, HttpMethod.GET, null, null)) .satisfies(ex -> { assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(ex.getStatusText()).isNotNull(); assertThat(ex.getResponseBodyAsString()).isNotNull(); assertThat(ex.getMessage()).containsSubsequence("404", "on GET request for \"" + url + "\": [no body]"); assumeFalse(clientHttpRequestFactory instanceof JdkClientHttpRequestFactory, "JDK HttpClient does not expose status text"); assertThat(ex.getMessage()).isEqualTo("404 Client Error on GET request for \"" + url + "\": [no body]"); }); } @ParameterizedRestTemplateTest void badRequest(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); String url = baseUrl + "/status/badrequest"; assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> template.execute(url, HttpMethod.GET, null, null)) .satisfies(ex -> { assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); assertThat(ex.getMessage()).containsSubsequence("400", "on GET request for \""+url+ "\": [no body]"); assumeFalse(clientHttpRequestFactory instanceof JdkClientHttpRequestFactory, "JDK HttpClient does not expose status text"); assertThat(ex.getMessage()).isEqualTo("400 Client Error on GET request for \""+url+ "\": [no body]"); }); } @ParameterizedRestTemplateTest void serverError(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); String url = baseUrl + "/status/server"; assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() -> template.execute(url, HttpMethod.GET, null, null)) .satisfies(ex -> { assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); assertThat(ex.getStatusText()).isNotNull(); assertThat(ex.getResponseBodyAsString()).isNotNull(); assertThat(ex.getMessage()).containsSubsequence("500", "on GET request for \"" + url + "\": [no body]"); assumeFalse(clientHttpRequestFactory instanceof JdkClientHttpRequestFactory, "JDK HttpClient does not expose status text"); assertThat(ex.getMessage()).isEqualTo("500 Server Error on GET request for \"" + url + "\": [no body]"); }); } @ParameterizedRestTemplateTest void optionsForAllow(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); Set<HttpMethod> allowed = template.optionsForAllow(URI.create(baseUrl + "/get")); assertThat(allowed).as("Invalid response").isEqualTo(Set.of(HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.HEAD, HttpMethod.TRACE)); } @ParameterizedRestTemplateTest void uri(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); String result = template.getForObject(baseUrl + "/uri/{query}", String.class, "Z\u00fcrich"); assertThat(result).as("Invalid request URI").isEqualTo("/uri/Z%C3%BCrich"); result = template.getForObject(baseUrl + "/uri/query={query}", String.class, "foo@bar"); assertThat(result).as("Invalid request URI").isEqualTo("/uri/query=foo@bar"); result = template.getForObject(baseUrl + "/uri/query={query}", String.class, "T\u014dky\u014d"); assertThat(result).as("Invalid request URI").isEqualTo("/uri/query=T%C5%8Dky%C5%8D"); } @ParameterizedRestTemplateTest void multipartFormData(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); template.postForLocation(baseUrl + "/multipartFormData", createMultipartParts()); } @ParameterizedRestTemplateTest void multipartMixed(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MULTIPART_MIXED); template.postForLocation(baseUrl + "/multipartMixed", new HttpEntity<>(createMultipartParts(), requestHeaders)); } @ParameterizedRestTemplateTest void multipartRelated(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); addSupportedMediaTypeToFormHttpMessageConverter(MULTIPART_RELATED); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MULTIPART_RELATED); template.postForLocation(baseUrl + "/multipartRelated", new HttpEntity<>(createMultipartParts(), requestHeaders)); } private MultiValueMap<String, Object> createMultipartParts() { MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(); parts.add("name 1", "value 1"); parts.add("name 2", "value 2+1"); parts.add("name 2", "value 2+2"); Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg"); parts.add("logo", logo); return parts; } private void addSupportedMediaTypeToFormHttpMessageConverter(MediaType mediaType) { this.template.getMessageConverters().stream() .filter(FormHttpMessageConverter.class::isInstance) .map(FormHttpMessageConverter.class::cast) .findFirst() .orElseThrow(() -> new IllegalStateException("Failed to find FormHttpMessageConverter")) .addSupportedMediaTypes(mediaType); } @ParameterizedRestTemplateTest void form(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add("name 1", "value 1"); form.add("name 2", "value 2+1"); form.add("name 2", "value 2+2"); template.postForLocation(baseUrl + "/form", form); } @ParameterizedRestTemplateTest void exchangeGet(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("MyHeader", "MyValue"); HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders); ResponseEntity<String> response = template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get"); assertThat(response.getBody()).as("Invalid content").isEqualTo(helloWorld); } @ParameterizedRestTemplateTest void exchangePost(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("MyHeader", "MyValue"); requestHeaders.setContentType(MediaType.TEXT_PLAIN); HttpEntity<String> entity = new HttpEntity<>(helloWorld, requestHeaders); HttpEntity<Void> result = template.exchange(baseUrl + "/{method}", POST, entity, Void.class, "post"); assertThat(result.getHeaders().getLocation()).as("Invalid location").isEqualTo(URI.create(baseUrl + "/post/1")); assertThat(result.hasBody()).isFalse(); } @ParameterizedRestTemplateTest void jsonPostForObject(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.setContentType(new MediaType("application", "json", StandardCharsets.UTF_8)); MySampleBean bean = new MySampleBean(); bean.setWith1("with"); bean.setWith2("with"); bean.setWithout("without"); HttpEntity<MySampleBean> entity = new HttpEntity<>(bean, entityHeaders); String s = template.postForObject(baseUrl + "/jsonpost", entity, String.class); assertThat(s).contains("\"with1\":\"with\""); assertThat(s).contains("\"with2\":\"with\""); assertThat(s).contains("\"without\":\"without\""); } @ParameterizedRestTemplateTest @Disabled("Use RestClient + upcoming hint management instead") @SuppressWarnings("removal") void jsonPostForObjectWithJacksonJsonView(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.setContentType(new MediaType("application", "json", StandardCharsets.UTF_8)); MySampleBean bean = new MySampleBean("with", "with", "without"); MappingJacksonValue jacksonValue = new MappingJacksonValue(bean); jacksonValue.setSerializationView(MyJacksonView1.class); HttpEntity<MappingJacksonValue> entity = new HttpEntity<>(jacksonValue, entityHeaders); String s = template.postForObject(baseUrl + "/jsonpost", entity, String.class); assertThat(s).contains("\"with1\":\"with\""); assertThat(s).doesNotContain("\"with2\":\"with\""); assertThat(s).doesNotContain("\"without\":\"without\""); } @ParameterizedRestTemplateTest // SPR-12123 void serverPort(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); String s = template.getForObject("http://localhost:{port}/get", String.class, port); assertThat(s).as("Invalid content").isEqualTo(helloWorld); } @ParameterizedRestTemplateTest // SPR-13154 void jsonPostForObjectWithJacksonTypeInfoList(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); List<ParentClass> list = new ArrayList<>(); list.add(new Foo("foo")); list.add(new Bar("bar")); ParameterizedTypeReference<?> typeReference = new ParameterizedTypeReference<List<ParentClass>>() {}; RequestEntity<List<ParentClass>> entity = RequestEntity .post(URI.create(baseUrl + "/jsonpost")) .contentType(new MediaType("application", "json", StandardCharsets.UTF_8)) .body(list, typeReference.getType()); String content = template.exchange(entity, String.class).getBody(); assertThat(content).contains("\"type\":\"foo\""); assertThat(content).contains("\"type\":\"bar\""); } @ParameterizedRestTemplateTest // SPR-15015 void postWithoutBody(ClientHttpRequestFactory clientHttpRequestFactory) { setUpClient(clientHttpRequestFactory); assertThat(template.postForObject(baseUrl + "/jsonpost", null, String.class)).isNull(); } public
ParameterizedRestTemplateTest
java
elastic__elasticsearch
x-pack/plugin/eql/qa/multi-cluster-with-security/src/javaRestTest/java/org/elasticsearch/xpack/eql/EqlSpecIT.java
{ "start": 972, "end": 1987 }
class ____ extends EqlSpecTestCase { @ClassRule public static TestRule clusterRule = RuleChain.outerRule(REMOTE_CLUSTER).around(LOCAL_CLUSTER); @Override protected String getTestRestCluster() { return LOCAL_CLUSTER.getHttpAddresses(); } @Override protected String getRemoteCluster() { return REMOTE_CLUSTER.getHttpAddresses(); } public EqlSpecIT( String query, String name, List<long[]> eventIds, String[] joinKeys, Integer size, Integer maxSamplesPerKey, Boolean allowPartialSearchResults, Boolean allowPartialSequenceResults, Boolean expectShardFailures ) { super( remoteClusterIndex(TEST_INDEX), query, name, eventIds, joinKeys, size, maxSamplesPerKey, allowPartialSearchResults, allowPartialSequenceResults, expectShardFailures ); } }
EqlSpecIT
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/webapp/TestRMWithCSRFFilter.java
{ "start": 2819, "end": 3322 }
class ____ extends JerseyTestBase { private static MockRM rm; @Override protected Application configure() { ResourceConfig config = new ResourceConfig(); config.register(new JerseyBinder()); config.register(RMWebServices.class); config.register(GenericExceptionHandler.class); config.register(new JettisonFeature()).register(JAXBContextResolver.class); forceSet(TestProperties.CONTAINER_PORT, JERSEY_RANDOM_PORT); return config; } private static
TestRMWithCSRFFilter
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/ui/Model.java
{ "start": 1012, "end": 3189 }
interface ____ { /** * Add the supplied attribute under the supplied name. * @param attributeName the name of the model attribute (never {@code null}) * @param attributeValue the model attribute value (can be {@code null}) */ Model addAttribute(String attributeName, @Nullable Object attributeValue); /** * Add the supplied attribute to this {@code Map} using a * {@link org.springframework.core.Conventions#getVariableName generated name}. * <p><i>Note: Empty {@link java.util.Collection Collections} are not added to * the model when using this method because we cannot correctly determine * the true convention name. View code should check for {@code null} rather * than for empty collections as is already done by JSTL tags.</i> * @param attributeValue the model attribute value (never {@code null}) */ Model addAttribute(Object attributeValue); /** * Copy all attributes in the supplied {@code Collection} into this * {@code Map}, using attribute name generation for each element. * @see #addAttribute(Object) */ Model addAllAttributes(Collection<?> attributeValues); /** * Copy all attributes in the supplied {@code Map} into this {@code Map}. * @see #addAttribute(String, Object) */ Model addAllAttributes(Map<String, ?> attributes); /** * Copy all attributes in the supplied {@code Map} into this {@code Map}, * with existing objects of the same name taking precedence (i.e. not getting * replaced). */ Model mergeAttributes(Map<String, ?> attributes); /** * Does this model contain an attribute of the given name? * @param attributeName the name of the model attribute (never {@code null}) * @return whether this model contains a corresponding attribute */ boolean containsAttribute(String attributeName); /** * Return the attribute value for the given name, if any. * @param attributeName the name of the model attribute (never {@code null}) * @return the corresponding attribute value, or {@code null} if none * @since 5.2 */ @Nullable Object getAttribute(String attributeName); /** * Return the current set of model attributes as a Map. */ Map<String, Object> asMap(); }
Model
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/web/resources/TestWebHdfsDataLocality.java
{ "start": 2513, "end": 10588 }
class ____ { static final Logger LOG = LoggerFactory.getLogger(TestWebHdfsDataLocality.class); { DFSTestUtil.setNameNodeLogLevel(Level.TRACE); } private static final String RACK0 = "/rack0"; private static final String RACK1 = "/rack1"; private static final String RACK2 = "/rack2"; private static final String LOCALHOST = InetAddress.getLoopbackAddress().getHostName(); @Test public void testDataLocality() throws Exception { final Configuration conf = WebHdfsTestUtil.createConf(); final String[] racks = {RACK0, RACK0, RACK1, RACK1, RACK2, RACK2}; final int nDataNodes = racks.length; LOG.info("nDataNodes=" + nDataNodes + ", racks=" + Arrays.asList(racks)); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(nDataNodes) .racks(racks) .build(); try { cluster.waitActive(); final DistributedFileSystem dfs = cluster.getFileSystem(); final NameNode namenode = cluster.getNameNode(); final DatanodeManager dm = namenode.getNamesystem().getBlockManager( ).getDatanodeManager(); LOG.info("dm=" + dm); final long blocksize = DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT; final String f = "/foo"; { //test CREATE for(int i = 0; i < nDataNodes; i++) { //set client address to a particular datanode final DataNode dn = cluster.getDataNodes().get(i); final String ipAddr = dm.getDatanode(dn.getDatanodeId()).getIpAddr(); //The chosen datanode must be the same as the client address final DatanodeInfo chosen = NamenodeWebHdfsMethods.chooseDatanode( namenode, f, PutOpParam.Op.CREATE, -1L, blocksize, null, LOCALHOST, null); assertEquals(ipAddr, chosen.getIpAddr()); } } //create a file with one replica. final Path p = new Path(f); final FSDataOutputStream out = dfs.create(p, (short)1); out.write(1); out.close(); //get replica location. final LocatedBlocks locatedblocks = NameNodeAdapter.getBlockLocations( namenode, f, 0, 1); final List<LocatedBlock> lb = locatedblocks.getLocatedBlocks(); assertEquals(1, lb.size()); final DatanodeInfo[] locations = lb.get(0).getLocations(); assertEquals(1, locations.length); final DatanodeInfo expected = locations[0]; //For GETFILECHECKSUM, OPEN and APPEND, //the chosen datanode must be the same as the replica location. { //test GETFILECHECKSUM final HdfsFileStatus status = dfs.getClient().getFileInfo(f); final DatanodeInfo chosen = NamenodeWebHdfsMethods.chooseDatanode( namenode, f, GetOpParam.Op.GETFILECHECKSUM, -1L, blocksize, null, LOCALHOST, status); assertEquals(expected, chosen); } { //test OPEN final HdfsFileStatus status = dfs.getClient().getFileInfo(f); final DatanodeInfo chosen = NamenodeWebHdfsMethods.chooseDatanode( namenode, f, GetOpParam.Op.OPEN, 0, blocksize, null, LOCALHOST, status); assertEquals(expected, chosen); } { //test APPEND final HdfsFileStatus status = dfs.getClient().getFileInfo(f); final DatanodeInfo chosen = NamenodeWebHdfsMethods.chooseDatanode( namenode, f, PostOpParam.Op.APPEND, -1L, blocksize, null, LOCALHOST, status); assertEquals(expected, chosen); } } finally { cluster.shutdown(); } } @Test public void testExcludeDataNodes() throws Exception { final Configuration conf = WebHdfsTestUtil.createConf(); final String[] racks = {RACK0, RACK0, RACK1, RACK1, RACK2, RACK2}; final String[] hosts = {"DataNode1", "DataNode2", "DataNode3","DataNode4","DataNode5","DataNode6"}; final int nDataNodes = hosts.length; LOG.info("nDataNodes=" + nDataNodes + ", racks=" + Arrays.asList(racks) + ", hosts=" + Arrays.asList(hosts)); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .hosts(hosts).numDataNodes(nDataNodes).racks(racks).build(); try { cluster.waitActive(); final DistributedFileSystem dfs = cluster.getFileSystem(); final NameNode namenode = cluster.getNameNode(); final DatanodeManager dm = namenode.getNamesystem().getBlockManager( ).getDatanodeManager(); LOG.info("dm=" + dm); final long blocksize = DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT; final String f = "/foo"; //create a file with three replica. final Path p = new Path(f); final FSDataOutputStream out = dfs.create(p, (short)3); out.write(1); out.close(); //get replica location. final LocatedBlocks locatedblocks = NameNodeAdapter.getBlockLocations( namenode, f, 0, 1); final List<LocatedBlock> lb = locatedblocks.getLocatedBlocks(); assertEquals(1, lb.size()); final DatanodeInfo[] locations = lb.get(0).getLocations(); assertEquals(3, locations.length); //For GETFILECHECKSUM, OPEN and APPEND, //the chosen datanode must be different with exclude nodes. StringBuilder sb = new StringBuilder(); for (int i = 0; i < 2; i++) { sb.append(locations[i].getXferAddr()); { // test GETFILECHECKSUM final HdfsFileStatus status = dfs.getClient().getFileInfo(f); final DatanodeInfo chosen = NamenodeWebHdfsMethods.chooseDatanode( namenode, f, GetOpParam.Op.GETFILECHECKSUM, -1L, blocksize, sb.toString(), LOCALHOST, status); for (int j = 0; j <= i; j++) { assertNotEquals(locations[j].getHostName(), chosen.getHostName()); } } { // test OPEN final HdfsFileStatus status = dfs.getClient().getFileInfo(f); final DatanodeInfo chosen = NamenodeWebHdfsMethods.chooseDatanode( namenode, f, GetOpParam.Op.OPEN, 0, blocksize, sb.toString(), LOCALHOST, status); for (int j = 0; j <= i; j++) { assertNotEquals(locations[j].getHostName(), chosen.getHostName()); } } { // test APPEND final HdfsFileStatus status = dfs.getClient().getFileInfo(f); final DatanodeInfo chosen = NamenodeWebHdfsMethods .chooseDatanode(namenode, f, PostOpParam.Op.APPEND, -1L, blocksize, sb.toString(), LOCALHOST, status); for (int j = 0; j <= i; j++) { assertNotEquals(locations[j].getHostName(), chosen.getHostName()); } } sb.append(","); } } finally { cluster.shutdown(); } } @Test public void testExcludeWrongDataNode() throws Exception { final Configuration conf = WebHdfsTestUtil.createConf(); final String[] racks = {RACK0}; final String[] hosts = {"DataNode1"}; final int nDataNodes = hosts.length; final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .hosts(hosts).numDataNodes(nDataNodes).racks(racks).build(); try { cluster.waitActive(); final NameNode namenode = cluster.getNameNode(); NamenodeWebHdfsMethods.chooseDatanode( namenode, "/path", PutOpParam.Op.CREATE, 0, DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT, "DataNode2", LOCALHOST, null); } catch (Exception e) { fail("Failed to exclude DataNode2" + e.getMessage()); } finally { cluster.shutdown(); } } @Test public void testChooseDatanodeBeforeNamesystemInit() throws Exception { NameNode nn = mock(NameNode.class); when(nn.getNamesystem()).thenReturn(null); IOException ex = assertThrows(IOException.class, () -> { NamenodeWebHdfsMethods.chooseDatanode(nn, "/path", PutOpParam.Op.CREATE, 0, DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT, null, LOCALHOST, null); }); assertTrue(ex.getMessage().contains("Namesystem has not been initialized yet.")); } }
TestWebHdfsDataLocality
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/aggs/kstest/SamplingMethod.java
{ "start": 3455, "end": 4138 }
class ____ extends SamplingMethod { public static final String NAME = "uniform"; private static final double[] CDF_POINTS; static { CDF_POINTS = new double[UpperTail.CDF_POINTS.length]; final double interval = 1.0 / (UpperTail.CDF_POINTS.length + 1); CDF_POINTS[0] = interval; for (int i = 1; i < CDF_POINTS.length; i++) { CDF_POINTS[i] = CDF_POINTS[i - 1] + interval; } } @Override public String getName() { return NAME; } @Override protected double[] cdfPoints() { return CDF_POINTS; } } }
Uniform
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 41390, "end": 41425 }
interface ____ extends Base {}
IntfA
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/notfound/exception/NotFoundExceptionLogicalOneToOneTest.java
{ "start": 12560, "end": 13293 }
class ____ { private Integer id; private String name; private Currency currency; public Coin() { } public Coin(Integer id, String name, Currency currency) { this.id = id; this.name = name; this.currency = currency; } @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToOne(fetch = FetchType.EAGER) @NotFound(action = NotFoundAction.EXCEPTION) public Currency getCurrency() { return currency; } public void setCurrency(Currency currency) { this.currency = currency; } } @Entity(name = "Currency") public static
Coin
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/CompositeIdRepeatedQueryTest.java
{ "start": 3745, "end": 4181 }
class ____ { @Id private String id; private String corporateName; public Corporation() { } public Corporation(String id, String corporateName) { this.id = id; this.corporateName = corporateName; } public String getId() { return id; } public String getCorporateName() { return corporateName; } } @Entity(name = "CorporationUser") @Table(name = "corporation_person_xref") public static
Corporation