language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__camel
components/camel-cxf/camel-cxf-rest/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerServiceResource.java
{ "start": 1129, "end": 1677 }
interface ____ { @GET @Path("/customers/{id}/") Customer getCustomer(@PathParam("id") String id); @PUT @Path("/customers/") Response updateCustomer(Customer customer); @Path("/{id}") @PUT() @Consumes({ "application/xml", "text/plain", "application/json" }) @Produces({ "application/xml", "text/plain", "application/json" }) Object invoke( @PathParam("id") String id, String payload); } // END SNIPPET: example
CustomerServiceResource
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/constructor/visibility/SimpleWithPublicConstructorMapper.java
{ "start": 567, "end": 1072 }
class ____ { private final String name; private final int age; protected Person() { this( "From Constructor", -1 ); } protected Person(String name) { this( name, -1 ); } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } }
Person
java
spring-projects__spring-framework
spring-jms/src/main/java/org/springframework/jms/listener/endpoint/StandardJmsActivationSpecFactory.java
{ "start": 2325, "end": 4923 }
class ____ for the target * provider (for example, "org.apache.activemq.ra.ActiveMQActivationSpec"). */ public void setActivationSpecClass(Class<?> activationSpecClass) { this.activationSpecClass = activationSpecClass; } /** * Specify custom default properties, with String keys and String values. * <p>Applied to each ActivationSpec object before it gets populated with * listener-specific settings. Allows for configuring vendor-specific properties * beyond the Spring-defined settings in {@link JmsActivationSpecConfig}. */ public void setDefaultProperties(Map<String, String> defaultProperties) { this.defaultProperties = defaultProperties; } /** * Set the DestinationResolver to use for resolving destination names * into the JCA 1.5 ActivationSpec "destination" property. * <p>If not specified, destination names will simply be passed in as Strings. * If specified, destination names will be resolved into Destination objects first. * <p>Note that a DestinationResolver for use with this factory must be * able to work <i>without</i> an active JMS Session: for example, * {@link org.springframework.jms.support.destination.JndiDestinationResolver} * or {@link org.springframework.jms.support.destination.BeanFactoryDestinationResolver} * but not {@link org.springframework.jms.support.destination.SimpleDestinationResolver} * or {@link org.springframework.jms.support.destination.DynamicDestinationResolver}. */ public void setDestinationResolver(@Nullable DestinationResolver destinationResolver) { this.destinationResolver = destinationResolver; } /** * Return the {@link DestinationResolver} to use for resolving destinations names. */ public @Nullable DestinationResolver getDestinationResolver() { return this.destinationResolver; } @Override public ActivationSpec createActivationSpec(ResourceAdapter adapter, JmsActivationSpecConfig config) { Class<?> activationSpecClassToUse = this.activationSpecClass; if (activationSpecClassToUse == null) { activationSpecClassToUse = determineActivationSpecClass(adapter); if (activationSpecClassToUse == null) { throw new IllegalStateException("Property 'activationSpecClass' is required"); } } ActivationSpec spec = (ActivationSpec) BeanUtils.instantiateClass(activationSpecClassToUse); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(spec); if (this.defaultProperties != null) { bw.setPropertyValues(this.defaultProperties); } populateActivationSpecProperties(bw, config); return spec; } /** * Determine the ActivationSpec
name
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/indices/stats/FieldUsageStatsAction.java
{ "start": 576, "end": 880 }
class ____ extends ActionType<FieldUsageStatsResponse> { public static final FieldUsageStatsAction INSTANCE = new FieldUsageStatsAction(); public static final String NAME = "indices:monitor/field_usage_stats"; private FieldUsageStatsAction() { super(NAME); } }
FieldUsageStatsAction
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/usertype/hhh18787/SomeEntity.java
{ "start": 457, "end": 907 }
class ____ { @Id @GeneratedValue private Long id; @Column private CustomData[] customData; public SomeEntity() { } public SomeEntity(CustomData[] customData) { this.customData = customData; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public CustomData[] getCustomData() { return customData; } public void setCustomData(CustomData[] custom) { this.customData = custom; } }
SomeEntity
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/ondemandload/OnDemandLoadTest.java
{ "start": 6413, "end": 7050 }
class ____ { @Id Long id; String name; @OneToMany( mappedBy = "store", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) List<Inventory> inventories = new ArrayList<>(); @Version Integer version; Store() { } Store(long id) { this.id = id; } Store setName(String name) { this.name = name; return this; } Inventory addInventoryProduct(Product product) { Inventory inventory = new Inventory( this, product ); inventories.add( inventory ); return inventory; } public List<Inventory> getInventories() { return inventories; } } @Entity @Table( name = "INVENTORY" ) static
Store
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/CachingOfDeserTest.java
{ "start": 1069, "end": 3890 }
class ____ extends StdDeserializer<Integer> { public CustomDeserializer735() { super(Integer.class); } @Override public Integer deserialize(JsonParser p, DeserializationContext ctxt) { return 100 * p.getValueAsInt(); } } /* /********************************************************** /* Unit tests /********************************************************** */ final static String MAP_INPUT = "{\"map\":{\"a\":1}}"; final static String LIST_INPUT = "{\"list\":[1]}"; // Ok: first, use custom-annotated instance first, then standard @Test public void testCustomMapCaching1() throws Exception { ObjectMapper mapper = new ObjectMapper(); TestMapWithCustom mapC = mapper.readValue(MAP_INPUT, TestMapWithCustom.class); TestMapNoCustom mapStd = mapper.readValue(MAP_INPUT, TestMapNoCustom.class); assertNotNull(mapC.map); assertNotNull(mapStd.map); assertEquals(Integer.valueOf(100), mapC.map.get("a")); assertEquals(Integer.valueOf(1), mapStd.map.get("a")); } // And then standard first, custom next @Test public void testCustomMapCaching2() throws Exception { ObjectMapper mapper = new ObjectMapper(); TestMapNoCustom mapStd = mapper.readValue(MAP_INPUT, TestMapNoCustom.class); TestMapWithCustom mapC = mapper.readValue(MAP_INPUT, TestMapWithCustom.class); assertNotNull(mapStd.map); assertNotNull(mapC.map); assertEquals(Integer.valueOf(1), mapStd.map.get("a")); assertEquals(Integer.valueOf(100), mapC.map.get("a")); } // Ok: first, use custom-annotated instance first, then standard @Test public void testCustomListCaching1() throws Exception { ObjectMapper mapper = new ObjectMapper(); TestListWithCustom listC = mapper.readValue(LIST_INPUT, TestListWithCustom.class); TestListNoCustom listStd = mapper.readValue(LIST_INPUT, TestListNoCustom.class); assertNotNull(listC.list); assertNotNull(listStd.list); assertEquals(Integer.valueOf(100), listC.list.get(0)); assertEquals(Integer.valueOf(1), listStd.list.get(0)); } // First custom-annotated, then standard @Test public void testCustomListCaching2() throws Exception { ObjectMapper mapper = new ObjectMapper(); TestListNoCustom listStd = mapper.readValue(LIST_INPUT, TestListNoCustom.class); TestListWithCustom listC = mapper.readValue(LIST_INPUT, TestListWithCustom.class); assertNotNull(listC.list); assertNotNull(listStd.list); assertEquals(Integer.valueOf(100), listC.list.get(0)); assertEquals(Integer.valueOf(1), listStd.list.get(0)); } }
CustomDeserializer735
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ClockFactoryTest.java
{ "start": 3258, "end": 3590 }
class ____ implements Clock { @Override public long currentTimeMillis() { return 42; } } @Test void testCustomClock() { System.setProperty(ClockFactory.PROPERTY_NAME, MyClock.class.getName()); assertSame(MyClock.class, ClockFactory.getClock().getClass()); } }
MyClock
java
elastic__elasticsearch
x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/cleaner/CleanerService.java
{ "start": 1197, "end": 4364 }
class ____ extends AbstractLifecycleComponent { private static final Logger logger = LogManager.getLogger(CleanerService.class); private final ThreadPool threadPool; private final Executor genericExecutor; private final ExecutionScheduler executionScheduler; private final List<Listener> listeners = new CopyOnWriteArrayList<>(); private final IndicesCleaner runnable; private volatile TimeValue globalRetention; @SuppressWarnings("this-escape") CleanerService(Settings settings, ClusterSettings clusterSettings, ThreadPool threadPool, ExecutionScheduler executionScheduler) { this.threadPool = threadPool; this.genericExecutor = threadPool.generic(); this.executionScheduler = executionScheduler; this.globalRetention = MonitoringField.HISTORY_DURATION.get(settings); this.runnable = new IndicesCleaner(); // the validation is performed by the setting's object itself clusterSettings.addSettingsUpdateConsumer(MonitoringField.HISTORY_DURATION, this::setGlobalRetention); } public CleanerService(Settings settings, ClusterSettings clusterSettings, ThreadPool threadPool) { this(settings, clusterSettings, threadPool, new DefaultExecutionScheduler()); } @Override protected void doStart() { logger.debug("starting cleaning service"); threadPool.schedule(runnable, executionScheduler.nextExecutionDelay(ZonedDateTime.now(Clock.systemDefaultZone())), genericExecutor); logger.debug("cleaning service started"); } @Override protected void doStop() { logger.debug("stopping cleaning service"); listeners.clear(); logger.debug("cleaning service stopped"); } @Override protected void doClose() { logger.debug("closing cleaning service"); runnable.cancel(); logger.debug("cleaning service closed"); } private static String executorName() { return ThreadPool.Names.GENERIC; } /** * Get the retention that can be used. * * @return Never {@code null} */ public TimeValue getRetention() { return globalRetention; } /** * Set the global retention. This is expected to be used by the cluster settings to dynamically control the global retention time. * * @param globalRetention The global retention to use dynamically. */ public void setGlobalRetention(TimeValue globalRetention) { this.globalRetention = globalRetention; } /** * Add a {@code listener} that is executed by the internal {@code IndicesCleaner} given the {@link #getRetention() retention} time. * * @param listener A listener used to control retention */ public void add(Listener listener) { listeners.add(listener); } /** * Remove a {@code listener}. * * @param listener A listener used to control retention * @see #add(Listener) */ public void remove(Listener listener) { listeners.remove(listener); } /** * Listener that get called when indices must be cleaned */ public
CleanerService
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/property/access/spi/Setter.java
{ "start": 416, "end": 695 }
interface ____ extends Serializable { void set(Object target, @Nullable Object value); /** * Optional operation (may return {@code null}) */ @Nullable String getMethodName(); /** * Optional operation (may return {@code null}) */ @Nullable Method getMethod(); }
Setter
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java
{ "start": 84464, "end": 84614 }
class ____ { } @EnableConfigurationProperties(ConstructorParameterWithUnitProperties.class) static
ConstructorParameterEmptyDefaultValueConfiguration
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/legacy/RecursiveComparisonAssert_isNotEqualTo_with_record_Test.java
{ "start": 774, "end": 1308 }
class ____ extends WithLegacyIntrospectionStrategyBaseTest { // https://github.com/assertj/assertj/issues/3539 @Test void should_compare_records_with_component_named_as_boolean_accessor() { // GIVEN record Record(String field, boolean isField) { } Record actual = new Record("value1", true); Record other = new Record("value2", true); // WHEN/THEN then(actual).usingRecursiveComparison(recursiveComparisonConfiguration).isNotEqualTo(other); } }
RecursiveComparisonAssert_isNotEqualTo_with_record_Test
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/tier/remote/TestingAvailabilityNotifier.java
{ "start": 2178, "end": 3011 }
class ____ { private BiFunction< TieredStoragePartitionId, TieredStorageInputChannelId, CompletableFuture<Void>> notifyFunction = (partitionId, subpartitionId) -> new CompletableFuture<>(); public Builder() {} public Builder setNotifyFunction( BiFunction< TieredStoragePartitionId, TieredStorageInputChannelId, CompletableFuture<Void>> notifyFunction) { this.notifyFunction = notifyFunction; return this; } public TestingAvailabilityNotifier build() { return new TestingAvailabilityNotifier(notifyFunction); } } }
Builder
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/dispatcher/DispatcherResourceCleanupTest.java
{ "start": 4452, "end": 30281 }
class ____ extends TestLogger { @ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule public final TestingFatalErrorHandlerResource testingFatalErrorHandlerResource = new TestingFatalErrorHandlerResource(); private static final Duration timeout = Duration.ofSeconds(10L); private static TestingRpcService rpcService; private JobID jobId; private JobGraph jobGraph; private TestingDispatcher dispatcher; private DispatcherGateway dispatcherGateway; private BlobServer blobServer; private CompletableFuture<JobID> localCleanupFuture; private CompletableFuture<JobID> globalCleanupFuture; @BeforeClass public static void setupClass() { rpcService = new TestingRpcService(); } @Before public void setup() throws Exception { jobGraph = JobGraphTestUtils.singleNoOpJobGraph(); jobId = jobGraph.getJobID(); globalCleanupFuture = new CompletableFuture<>(); localCleanupFuture = new CompletableFuture<>(); blobServer = BlobUtils.createBlobServer( new Configuration(), Reference.owned(temporaryFolder.newFolder()), new TestingBlobStoreBuilder().createTestingBlobStore()); } private TestingJobManagerRunnerFactory startDispatcherAndSubmitJob() throws Exception { return startDispatcherAndSubmitJob(0); } private TestingJobManagerRunnerFactory startDispatcherAndSubmitJob( int numBlockingJobManagerRunners) throws Exception { return startDispatcherAndSubmitJob( createTestingDispatcherBuilder(), numBlockingJobManagerRunners); } private TestingJobManagerRunnerFactory startDispatcherAndSubmitJob( TestingDispatcher.Builder dispatcherBuilder, int numBlockingJobManagerRunners) throws Exception { final TestingJobMasterServiceLeadershipRunnerFactory testingJobManagerRunnerFactoryNG = new TestingJobMasterServiceLeadershipRunnerFactory(numBlockingJobManagerRunners); startDispatcher(dispatcherBuilder, testingJobManagerRunnerFactoryNG); submitJobAndWait(); return testingJobManagerRunnerFactoryNG; } private void startDispatcher(JobManagerRunnerFactory jobManagerRunnerFactory) throws Exception { startDispatcher(createTestingDispatcherBuilder(), jobManagerRunnerFactory); } private void startDispatcher( TestingDispatcher.Builder dispatcherBuilder, JobManagerRunnerFactory jobManagerRunnerFactory) throws Exception { dispatcher = dispatcherBuilder .setJobManagerRunnerFactory(jobManagerRunnerFactory) .build(rpcService); dispatcher.start(); dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); } private TestingDispatcher.Builder createTestingDispatcherBuilder() { final JobManagerRunnerRegistry jobManagerRunnerRegistry = new DefaultJobManagerRunnerRegistry(2); return TestingDispatcher.builder() .setBlobServer(blobServer) .setJobManagerRunnerRegistry(jobManagerRunnerRegistry) .setFatalErrorHandler(testingFatalErrorHandlerResource.getFatalErrorHandler()) .setResourceCleanerFactory( TestingResourceCleanerFactory.builder() // JobManagerRunnerRegistry needs to be added explicitly // because cleaning it will trigger the closeAsync latch // provided by TestingJobManagerRunner .withLocallyCleanableResource(jobManagerRunnerRegistry) .withGloballyCleanableResource( (jobId, ignoredExecutor) -> { globalCleanupFuture.complete(jobId); return FutureUtils.completedVoidFuture(); }) .withLocallyCleanableResource( (jobId, ignoredExecutor) -> { localCleanupFuture.complete(jobId); return FutureUtils.completedVoidFuture(); }) .build()); } @After public void teardown() throws Exception { if (dispatcher != null) { dispatcher.close(); } if (blobServer != null) { blobServer.close(); } } @AfterClass public static void teardownClass() throws ExecutionException, InterruptedException { if (rpcService != null) { rpcService.closeAsync().get(); } } @Test public void testGlobalCleanupWhenJobFinished() throws Exception { final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob(); // complete the job finishJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner()); assertGlobalCleanupTriggered(jobId); } @Test public void testGlobalCleanupWhenJobCanceled() throws Exception { final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob(); // complete the job cancelJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner()); assertGlobalCleanupTriggered(jobId); } private CompletableFuture<Acknowledge> submitJob() { return dispatcherGateway.submitJob(jobGraph, timeout); } private void submitJobAndWait() { submitJob().join(); } @Test public void testLocalCleanupWhenJobNotFinished() throws Exception { final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob(); // job not finished final TestingJobManagerRunner testingJobManagerRunner = jobManagerRunnerFactory.takeCreatedJobManagerRunner(); suspendJob(testingJobManagerRunner); assertLocalCleanupTriggered(jobId); } @Test public void testGlobalCleanupWhenJobSubmissionFails() throws Exception { startDispatcher(new FailingJobManagerRunnerFactory(new FlinkException("Test exception"))); final CompletableFuture<Acknowledge> submissionFuture = submitJob(); assertThatThrownBy(submissionFuture::get).hasCauseInstanceOf(JobSubmissionException.class); assertGlobalCleanupTriggered(jobId); } @Test public void testLocalCleanupWhenClosingDispatcher() throws Exception { startDispatcherAndSubmitJob(); dispatcher.closeAsync().get(); assertLocalCleanupTriggered(jobId); } @Test public void testGlobalCleanupWhenJobFinishedWhileClosingDispatcher() throws Exception { final TestingJobManagerRunner testingJobManagerRunner = TestingJobManagerRunner.newBuilder() .setBlockingTermination(true) .setJobId(jobId) .build(); final Queue<JobManagerRunner> jobManagerRunners = new ArrayDeque<>(Arrays.asList(testingJobManagerRunner)); startDispatcher(new QueueJobManagerRunnerFactory(jobManagerRunners)); submitJobAndWait(); final CompletableFuture<Void> dispatcherTerminationFuture = dispatcher.closeAsync(); testingJobManagerRunner.getCloseAsyncCalledLatch().await(); testingJobManagerRunner.completeResultFuture( new ExecutionGraphInfo( new ArchivedExecutionGraphBuilder() .setJobID(jobId) .setState(JobStatus.FINISHED) .build())); testingJobManagerRunner.completeTerminationFuture(); // check that no exceptions have been thrown dispatcherTerminationFuture.get(); assertGlobalCleanupTriggered(jobId); } @Test public void testJobBeingMarkedAsDirtyBeforeCleanup() throws Exception { final OneShotLatch markAsDirtyLatch = new OneShotLatch(); final TestingDispatcher.Builder dispatcherBuilder = createTestingDispatcherBuilder() .setJobResultStore( TestingJobResultStore.builder() .withCreateDirtyResultConsumer( ignoredJobResultEntry -> { try { markAsDirtyLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return FutureUtils.completedExceptionally( e); } return FutureUtils.completedVoidFuture(); }) .build()); final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob(dispatcherBuilder, 0); finishJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner()); assertThatNoCleanupWasTriggered(); markAsDirtyLatch.trigger(); assertGlobalCleanupTriggered(jobId); } @Test public void testJobBeingMarkedAsCleanAfterCleanup() throws Exception { final CompletableFuture<JobID> markAsCleanFuture = new CompletableFuture<>(); final JobResultStore jobResultStore = TestingJobResultStore.builder() .withMarkResultAsCleanConsumer( jobID -> { markAsCleanFuture.complete(jobID); return FutureUtils.completedVoidFuture(); }) .build(); final OneShotLatch localCleanupLatch = new OneShotLatch(); final OneShotLatch globalCleanupLatch = new OneShotLatch(); final TestingResourceCleanerFactory resourceCleanerFactory = TestingResourceCleanerFactory.builder() .withLocallyCleanableResource( (ignoredJobId, ignoredExecutor) -> { try { localCleanupLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } return FutureUtils.completedVoidFuture(); }) .withGloballyCleanableResource( (ignoredJobId, ignoredExecutor) -> { try { globalCleanupLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } return FutureUtils.completedVoidFuture(); }) .build(); final TestingDispatcher.Builder dispatcherBuilder = createTestingDispatcherBuilder() .setJobResultStore(jobResultStore) .setResourceCleanerFactory(resourceCleanerFactory); final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob(dispatcherBuilder, 0); finishJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner()); assertThat(markAsCleanFuture.isDone(), is(false)); localCleanupLatch.trigger(); assertThat(markAsCleanFuture.isDone(), is(false)); globalCleanupLatch.trigger(); assertThat(markAsCleanFuture.get(), is(jobId)); } /** * Tests that the previous JobManager needs to be completely terminated before a new job with * the same {@link JobID} is started. */ @Test public void testJobSubmissionUnderSameJobId() throws Exception { final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob(1); final TestingJobManagerRunner testingJobManagerRunner = jobManagerRunnerFactory.takeCreatedJobManagerRunner(); suspendJob(testingJobManagerRunner); // wait until termination JobManagerRunner closeAsync has been called. // this is necessary to avoid race conditions with completion of the 1st job and the // submission of the 2nd job (DuplicateJobSubmissionException). testingJobManagerRunner.getCloseAsyncCalledLatch().await(); final CompletableFuture<Acknowledge> submissionFuture = dispatcherGateway.submitJob(jobGraph, timeout); try { submissionFuture.get(10L, TimeUnit.MILLISECONDS); fail( "The job submission future should not complete until the previous JobManager " + "termination future has been completed."); } catch (TimeoutException ignored) { // expected } finally { testingJobManagerRunner.completeTerminationFuture(); } assertThat(submissionFuture.get(), equalTo(Acknowledge.get())); } /** * Tests that a duplicate job submission won't delete any job meta data (submitted job graphs, * blobs, etc.). */ @Test public void testDuplicateJobSubmissionDoesNotDeleteJobMetaData() throws Exception { final TestingJobManagerRunnerFactory testingJobManagerRunnerFactoryNG = startDispatcherAndSubmitJob(); final CompletableFuture<Acknowledge> submissionFuture = dispatcherGateway.submitJob(jobGraph, timeout); try { try { submissionFuture.get(); fail("Expected a DuplicateJobSubmissionFailure."); } catch (ExecutionException ee) { assertThat( ExceptionUtils.findThrowable(ee, DuplicateJobSubmissionException.class) .isPresent(), is(true)); } assertThatNoCleanupWasTriggered(); } finally { finishJob(testingJobManagerRunnerFactoryNG.takeCreatedJobManagerRunner()); } assertGlobalCleanupTriggered(jobId); } private void finishJob(TestingJobManagerRunner takeCreatedJobManagerRunner) { terminateJobWithState(takeCreatedJobManagerRunner, JobStatus.FINISHED); } private void suspendJob(TestingJobManagerRunner takeCreatedJobManagerRunner) { terminateJobWithState(takeCreatedJobManagerRunner, JobStatus.SUSPENDED); } private void cancelJob(TestingJobManagerRunner takeCreatedJobManagerRunner) { terminateJobWithState(takeCreatedJobManagerRunner, JobStatus.CANCELED); } private void terminateJobWithState( TestingJobManagerRunner takeCreatedJobManagerRunner, JobStatus state) { takeCreatedJobManagerRunner.completeResultFuture( new ExecutionGraphInfo( new ArchivedExecutionGraphBuilder() .setJobID(jobId) .setState(state) .build())); } private void assertThatNoCleanupWasTriggered() { assertThat(globalCleanupFuture.isDone(), is(false)); assertThat(localCleanupFuture.isDone(), is(false)); } @Test public void testDispatcherTerminationTerminatesRunningJobMasters() throws Exception { final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob(); dispatcher.closeAsync().get(); final TestingJobManagerRunner jobManagerRunner = jobManagerRunnerFactory.takeCreatedJobManagerRunner(); assertThat(jobManagerRunner.getTerminationFuture().isDone(), is(true)); } /** Tests that terminating the Dispatcher will wait for all JobMasters to be terminated. */ @Test public void testDispatcherTerminationWaitsForJobMasterTerminations() throws Exception { final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob(1); final CompletableFuture<Void> dispatcherTerminationFuture = dispatcher.closeAsync(); try { dispatcherTerminationFuture.get(10L, TimeUnit.MILLISECONDS); fail("We should not terminate before all running JobMasters have terminated."); } catch (TimeoutException ignored) { // expected } finally { jobManagerRunnerFactory.takeCreatedJobManagerRunner().completeTerminationFuture(); } dispatcherTerminationFuture.get(); } private void assertLocalCleanupTriggered(JobID jobId) throws ExecutionException, InterruptedException, TimeoutException { assertThat(localCleanupFuture.get(), equalTo(jobId)); assertThat(globalCleanupFuture.isDone(), is(false)); } private void assertGlobalCleanupTriggered(JobID jobId) throws ExecutionException, InterruptedException, TimeoutException { assertThat(localCleanupFuture.isDone(), is(false)); assertThat(globalCleanupFuture.get(), equalTo(jobId)); } @Test public void testFatalErrorIfJobCannotBeMarkedDirtyInJobResultStore() throws Exception { final JobResultStore jobResultStore = TestingJobResultStore.builder() .withCreateDirtyResultConsumer( jobResult -> FutureUtils.completedExceptionally( new IOException("Expected IOException."))) .build(); final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob( createTestingDispatcherBuilder().setJobResultStore(jobResultStore), 0); ArchivedExecutionGraph executionGraph = new ArchivedExecutionGraphBuilder() .setJobID(jobId) .setState(JobStatus.FINISHED) .build(); final TestingJobManagerRunner testingJobManagerRunner = jobManagerRunnerFactory.takeCreatedJobManagerRunner(); testingJobManagerRunner.completeResultFuture(new ExecutionGraphInfo(executionGraph)); final CompletableFuture<? extends Throwable> errorFuture = this.testingFatalErrorHandlerResource.getFatalErrorHandler().getErrorFuture(); assertThat(errorFuture.get(), IsInstanceOf.instanceOf(FlinkException.class)); testingFatalErrorHandlerResource.getFatalErrorHandler().clearError(); } @Test public void testErrorHandlingIfJobCannotBeMarkedAsCleanInJobResultStore() throws Exception { final CompletableFuture<JobResultEntry> dirtyJobFuture = new CompletableFuture<>(); final JobResultStore jobResultStore = TestingJobResultStore.builder() .withCreateDirtyResultConsumer( jobResultEntry -> { dirtyJobFuture.complete(jobResultEntry); return FutureUtils.completedVoidFuture(); }) .withMarkResultAsCleanConsumer( jobId -> FutureUtils.completedExceptionally( new IOException("Expected IOException."))) .build(); final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob( createTestingDispatcherBuilder().setJobResultStore(jobResultStore), 0); ArchivedExecutionGraph executionGraph = new ArchivedExecutionGraphBuilder() .setJobID(jobId) .setState(JobStatus.FINISHED) .build(); final TestingJobManagerRunner testingJobManagerRunner = jobManagerRunnerFactory.takeCreatedJobManagerRunner(); testingJobManagerRunner.completeResultFuture(new ExecutionGraphInfo(executionGraph)); final CompletableFuture<? extends Throwable> errorFuture = this.testingFatalErrorHandlerResource.getFatalErrorHandler().getErrorFuture(); try { final Throwable unexpectedError = errorFuture.get(100, TimeUnit.MILLISECONDS); fail( "No error should have been reported but an " + unexpectedError.getClass() + " was handled."); } catch (TimeoutException e) { // expected } assertThat(dirtyJobFuture.get().getJobId(), is(jobId)); } /** Tests that a failing {@link JobManagerRunner} will be properly cleaned up. */ @Test public void testFailingJobManagerRunnerCleanup() throws Exception { final FlinkException testException = new FlinkException("Test exception."); final ArrayBlockingQueue<Optional<Exception>> queue = new ArrayBlockingQueue<>(2); final BlockingJobManagerRunnerFactory blockingJobManagerRunnerFactory = new BlockingJobManagerRunnerFactory( () -> { final Optional<Exception> maybeException = queue.take(); if (maybeException.isPresent()) { throw maybeException.get(); } }); startDispatcher(blockingJobManagerRunnerFactory); final DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); // submit and fail during job master runner construction queue.offer(Optional.of(testException)); assertThatThrownBy(() -> dispatcherGateway.submitJob(jobGraph, Duration.ofMinutes(1)).get()) .hasCauseInstanceOf(FlinkException.class) .hasRootCauseMessage(testException.getMessage()); // make sure we've cleaned up in correct order (including HA) assertGlobalCleanupTriggered(jobId); // don't fail this time queue.offer(Optional.empty()); // submit job again dispatcherGateway.submitJob(jobGraph, Duration.ofMinutes(1L)).get(); blockingJobManagerRunnerFactory.setJobStatus(JobStatus.RUNNING); // Ensure job is running awaitStatus(dispatcherGateway, jobId, JobStatus.RUNNING); } @Test public void testArchivingFinishedJobToHistoryServer() throws Exception { final CompletableFuture<Acknowledge> archiveFuture = new CompletableFuture<>(); final TestingDispatcher.Builder testingDispatcherBuilder = createTestingDispatcherBuilder() .setHistoryServerArchivist(executionGraphInfo -> archiveFuture); final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob(testingDispatcherBuilder, 0); finishJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner()); // Before the archiving is finished, the cleanup is not finished and the job is not // terminated assertThatNoCleanupWasTriggered(); final CompletableFuture<Void> jobTerminationFuture = dispatcher.getJobTerminationFuture(jobId, Duration.ofHours(1)); assertFalse(jobTerminationFuture.isDone()); archiveFuture.complete(Acknowledge.get()); // Once the archive is finished, the cleanup is finished and the job is terminated. assertGlobalCleanupTriggered(jobId); jobTerminationFuture.join(); } @Test public void testNotArchivingSuspendedJobToHistoryServer() throws Exception { final AtomicBoolean isArchived = new AtomicBoolean(false); final TestingDispatcher.Builder testingDispatcherBuilder = createTestingDispatcherBuilder() .setHistoryServerArchivist( executionGraphInfo -> { isArchived.set(true); return CompletableFuture.completedFuture(Acknowledge.get()); }); final TestingJobManagerRunnerFactory jobManagerRunnerFactory = startDispatcherAndSubmitJob(testingDispatcherBuilder, 0); suspendJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner()); assertLocalCleanupTriggered(jobId); dispatcher.getJobTerminationFuture(jobId, Duration.ofHours(1)).join(); assertFalse(isArchived.get()); } private static final
DispatcherResourceCleanupTest
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/commons/util/ReflectionUtilsWithGenericTypeHierarchiesTests.java
{ "start": 5879, "end": 6011 }
class ____ implements InterfaceExtendingNumberInterfaceWithGenericObjectMethod { } }
ClassImplementingInterfaceWithInvertedHierarchy
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelRunOn.java
{ "start": 1512, "end": 3233 }
class ____<T> extends ParallelFlowable<T> { final ParallelFlowable<? extends T> source; final Scheduler scheduler; final int prefetch; public ParallelRunOn(ParallelFlowable<? extends T> parent, Scheduler scheduler, int prefetch) { this.source = parent; this.scheduler = scheduler; this.prefetch = prefetch; } @Override public void subscribe(Subscriber<? super T>[] subscribers) { subscribers = RxJavaPlugins.onSubscribe(this, subscribers); if (!validate(subscribers)) { return; } int n = subscribers.length; @SuppressWarnings("unchecked") final Subscriber<T>[] parents = new Subscriber[n]; if (scheduler instanceof SchedulerMultiWorkerSupport) { SchedulerMultiWorkerSupport multiworker = (SchedulerMultiWorkerSupport) scheduler; multiworker.createWorkers(n, new MultiWorkerCallback(subscribers, parents)); } else { for (int i = 0; i < n; i++) { createSubscriber(i, subscribers, parents, scheduler.createWorker()); } } source.subscribe(parents); } void createSubscriber(int i, Subscriber<? super T>[] subscribers, Subscriber<T>[] parents, Scheduler.Worker worker) { Subscriber<? super T> a = subscribers[i]; SpscArrayQueue<T> q = new SpscArrayQueue<>(prefetch); if (a instanceof ConditionalSubscriber) { parents[i] = new RunOnConditionalSubscriber<>((ConditionalSubscriber<? super T>)a, prefetch, q, worker); } else { parents[i] = new RunOnSubscriber<>(a, prefetch, q, worker); } } final
ParallelRunOn
java
elastic__elasticsearch
x-pack/plugin/fleet/src/internalClusterTest/java/org/elasticsearch/xpack/fleet/action/FleetSearchRemoteIndicesDisallowedIT.java
{ "start": 780, "end": 4409 }
class ____ extends ESIntegTestCase { @Override protected boolean addMockHttpTransport() { return false; } @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Stream.of(Fleet.class, LocalStateCompositeXPackPlugin.class, IndexLifecycle.class).collect(Collectors.toList()); } public void testEndpointsShouldRejectRemoteIndices() { String remoteIndex = randomAlphaOfLength(randomIntBetween(2, 10)) + ":" + randomAlphaOfLength(randomIntBetween(2, 10)); { Request request = new Request("GET", "/" + remoteIndex + "/_fleet/_fleet_search"); ResponseException responseException = expectThrows(ResponseException.class, () -> getRestClient().performRequest(request)); assertThat( responseException.getMessage(), Matchers.containsString("Fleet search API does not support remote indices. Found: [" + remoteIndex + "]") ); } { Request request = new Request("POST", "/" + remoteIndex + "/_fleet/_fleet_msearch"); request.setJsonEntity("{}\n{}\n"); ResponseException responseException = expectThrows(ResponseException.class, () -> getRestClient().performRequest(request)); assertThat( responseException.getMessage(), Matchers.containsString("Fleet search API does not support remote indices. Found: [" + remoteIndex + "]") ); } { /* * It is possible, however, to sneak in multiple indices and a remote index if checkpoints are not specified. * Unfortunately, that's the current behaviour and the Fleet team does not want us to touch it. */ Request request = new Request("POST", "/foo,bar:baz/_fleet/_fleet_msearch"); request.setJsonEntity("{}\n{}\n"); try { getRestClient().performRequest(request); } catch (Exception e) { throw new AssertionError(e); } } { // This is fine, there are no remote indices. Request request = new Request("POST", "/foo/_fleet/_fleet_msearch"); request.setJsonEntity("{\"index\": \"bar*\"}\n{}\n"); try { getRestClient().performRequest(request); } catch (Exception e) { throw new AssertionError(e); } } { // This is not valid. We shouldn't be passing multiple indices. Request request = new Request("POST", "/foo/_fleet/_fleet_msearch"); request.setJsonEntity("{\"index\": \"bar,baz\", \"wait_for_checkpoints\": 1 }\n{}\n"); ResponseException responseException = expectThrows(ResponseException.class, () -> getRestClient().performRequest(request)); assertThat(responseException.getMessage(), Matchers.containsString("Fleet search API only supports searching a single index.")); } { // This is not valid. We shouldn't be passing remote indices. Request request = new Request("POST", "/foo/_fleet/_fleet_msearch"); request.setJsonEntity("{\"index\": \"bar:baz\", \"wait_for_checkpoints\": 1 }\n{}\n"); ResponseException responseException = expectThrows(ResponseException.class, () -> getRestClient().performRequest(request)); assertThat(responseException.getMessage(), Matchers.containsString("Fleet search API does not support remote indices. Found:")); } } }
FleetSearchRemoteIndicesDisallowedIT
java
apache__hadoop
hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-blockgen/src/main/java/org/apache/hadoop/tools/dynamometer/blockgenerator/BlockInfo.java
{ "start": 1424, "end": 3219 }
class ____ implements Writable { LongWritable getBlockId() { return blockId; } LongWritable getBlockGenerationStamp() { return blockGenerationStamp; } LongWritable getSize() { return size; } short getReplication() { return replication; } private LongWritable blockId; private LongWritable blockGenerationStamp; private LongWritable size; private transient short replication; @SuppressWarnings("unused") // Used via reflection private BlockInfo() { this.blockId = new LongWritable(); this.blockGenerationStamp = new LongWritable(); this.size = new LongWritable(); } BlockInfo(long blockid, long blockgenerationstamp, long size, short replication) { this.blockId = new LongWritable(blockid); this.blockGenerationStamp = new LongWritable(blockgenerationstamp); this.size = new LongWritable(size); this.replication = replication; } public void write(DataOutput dataOutput) throws IOException { blockId.write(dataOutput); blockGenerationStamp.write(dataOutput); size.write(dataOutput); } public void readFields(DataInput dataInput) throws IOException { blockId.readFields(dataInput); blockGenerationStamp.readFields(dataInput); size.readFields(dataInput); } @Override public boolean equals(Object o) { if (!(o instanceof BlockInfo)) { return false; } BlockInfo blkInfo = (BlockInfo) o; return blkInfo.getBlockId().equals(this.getBlockId()) && blkInfo.getBlockGenerationStamp() .equals(this.getBlockGenerationStamp()) && blkInfo.getSize().equals(this.getSize()); } @Override public int hashCode() { return blockId.hashCode() + 357 * blockGenerationStamp.hashCode() + 9357 * size.hashCode(); } }
BlockInfo
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/math/RoundDoubleNoDecimalsEvaluator.java
{ "start": 1086, "end": 3907 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(RoundDoubleNoDecimalsEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator val; private final DriverContext driverContext; private Warnings warnings; public RoundDoubleNoDecimalsEvaluator(Source source, EvalOperator.ExpressionEvaluator val, DriverContext driverContext) { this.source = source; this.val = val; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (DoubleBlock valBlock = (DoubleBlock) val.eval(page)) { DoubleVector valVector = valBlock.asVector(); if (valVector == null) { return eval(page.getPositionCount(), valBlock); } return eval(page.getPositionCount(), valVector).asBlock(); } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += val.baseRamBytesUsed(); return baseRamBytesUsed; } public DoubleBlock eval(int positionCount, DoubleBlock valBlock) { try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { switch (valBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } double val = valBlock.getDouble(valBlock.getFirstValueIndex(p)); result.appendDouble(Round.process(val)); } return result.build(); } } public DoubleVector eval(int positionCount, DoubleVector valVector) { try(DoubleVector.FixedBuilder result = driverContext.blockFactory().newDoubleVectorFixedBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { double val = valVector.getDouble(p); result.appendDouble(p, Round.process(val)); } return result.build(); } } @Override public String toString() { return "RoundDoubleNoDecimalsEvaluator[" + "val=" + val + "]"; } @Override public void close() { Releasables.closeExpectNoException(val); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
RoundDoubleNoDecimalsEvaluator
java
resilience4j__resilience4j
resilience4j-micronaut-annotation/src/main/java/io/github/resilience4j/micronaut/processor/RateLimiterAnnotationRemapper.java
{ "start": 808, "end": 1128 }
class ____ implements PackageRenameRemapper { @Override public String getTargetPackage() { return "io.github.resilience4j.micronaut.annotation"; } @Override public String getPackageName() { return "io.github.resilience4j.circuitbreaker.annotation"; } }
RateLimiterAnnotationRemapper
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java
{ "start": 2529, "end": 10946 }
class ____ { private MappingJackson2JsonView view = new MappingJackson2JsonView(); private MockHttpServletRequest request = new MockHttpServletRequest(); private MockHttpServletResponse response = new MockHttpServletResponse(); private Context jsContext = ContextFactory.getGlobal().enterContext(); private ScriptableObject jsScope = jsContext.initStandardObjects(); @Test void isExposePathVars() { assertThat(view.isExposePathVariables()).as("Must not expose path variables").isFalse(); } @Test void renderSimpleMap() throws Exception { Map<String, Object> model = new HashMap<>(); model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", "bar"); view.setUpdateContentLength(true); view.render(model, request, response); assertThat(response.getHeader("Cache-Control")).isEqualTo("no-store"); MediaType mediaType = MediaType.parseMediaType(response.getContentType()); assertThat(mediaType.isCompatibleWith(MediaType.parseMediaType(MappingJackson2JsonView.DEFAULT_CONTENT_TYPE))).isTrue(); String jsonResult = response.getContentAsString(); assertThat(jsonResult).isNotEmpty(); assertThat(response.getContentLength()).isEqualTo(jsonResult.length()); validateResult(); } @Test void renderWithSelectedContentType() throws Exception { Map<String, Object> model = new HashMap<>(); model.put("foo", "bar"); view.render(model, request, response); MediaType mediaType = MediaType.parseMediaType(response.getContentType()); assertThat(mediaType.isCompatibleWith(MediaType.APPLICATION_JSON)).isTrue(); request.setAttribute(View.SELECTED_CONTENT_TYPE, new MediaType("application", "vnd.example-v2+xml")); view.render(model, request, response); mediaType = MediaType.parseMediaType(response.getContentType()); assertThat(mediaType.isCompatibleWith(MediaType.parseMediaType("application/vnd.example-v2+xml"))).isTrue(); } @Test void renderCaching() throws Exception { view.setDisableCaching(false); Map<String, Object> model = new HashMap<>(); model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", "bar"); view.render(model, request, response); assertThat(response.getHeader("Cache-Control")).isNull(); } @Test void renderSimpleMapPrefixed() throws Exception { view.setPrefixJson(true); renderSimpleMap(); } @Test void renderSimpleBean() throws Exception { Object bean = new TestBeanSimple(); Map<String, Object> model = new HashMap<>(); model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", bean); view.setUpdateContentLength(true); view.render(model, request, response); assertThat(response.getContentAsString()).isNotEmpty(); assertThat(response.getContentLength()).isEqualTo(response.getContentAsString().length()); validateResult(); } @Test void renderWithPrettyPrint() throws Exception { ModelMap model = new ModelMap("foo", new TestBeanSimple()); view.setPrettyPrint(true); view.render(model, request, response); String result = response.getContentAsString().replace("\r\n", "\n"); assertThat(result).as("Pretty printing not applied:\n" + result).startsWith("{\n \"foo\" : {\n "); validateResult(); } @Test void renderSimpleBeanPrefixed() throws Exception { view.setPrefixJson(true); renderSimpleBean(); assertThat(response.getContentAsString()).startsWith(")]}', "); } @Test void renderSimpleBeanNotPrefixed() throws Exception { view.setPrefixJson(false); renderSimpleBean(); assertThat(response.getContentAsString()).doesNotStartWith(")]}', "); } @Test void renderWithCustomSerializerLocatedByAnnotation() throws Exception { Object bean = new TestBeanSimpleAnnotated(); Map<String, Object> model = new HashMap<>(); model.put("foo", bean); view.render(model, request, response); assertThat(response.getContentAsString()).isNotEmpty(); assertThat(response.getContentAsString()).isEqualTo("{\"foo\":{\"testBeanSimple\":\"custom\"}}"); validateResult(); } @Test void renderWithCustomSerializerLocatedByFactory() throws Exception { SerializerFactory factory = new DelegatingSerializerFactory(null); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializerFactory(factory); view.setObjectMapper(mapper); Object bean = new TestBeanSimple(); Map<String, Object> model = new HashMap<>(); model.put("foo", bean); model.put("bar", new TestChildBean()); view.render(model, request, response); String result = response.getContentAsString(); assertThat(result).isNotEmpty(); assertThat(result).contains("\"foo\":{\"testBeanSimple\":\"custom\"}"); validateResult(); } @Test void renderOnlyIncludedAttributes() throws Exception { Set<String> attrs = new HashSet<>(); attrs.add("foo"); attrs.add("baz"); attrs.add("nil"); view.setModelKeys(attrs); Map<String, Object> model = new HashMap<>(); model.put("foo", "foo"); model.put("bar", "bar"); model.put("baz", "baz"); view.render(model, request, response); String result = response.getContentAsString(); assertThat(result).isNotEmpty(); assertThat(result).contains("\"foo\":\"foo\""); assertThat(result).contains("\"baz\":\"baz\""); validateResult(); } @Test void filterSingleKeyModel() { view.setExtractValueFromSingleKeyModel(true); Map<String, Object> model = new HashMap<>(); TestBeanSimple bean = new TestBeanSimple(); model.put("foo", bean); Object actual = view.filterModel(model); assertThat(actual).isSameAs(bean); } @SuppressWarnings("rawtypes") @Test void filterTwoKeyModel() { view.setExtractValueFromSingleKeyModel(true); Map<String, Object> model = new HashMap<>(); TestBeanSimple bean1 = new TestBeanSimple(); TestBeanSimple bean2 = new TestBeanSimple(); model.put("foo1", bean1); model.put("foo2", bean2); Object actual = view.filterModel(model); assertThat(actual).isInstanceOf(Map.class); assertThat(((Map) actual).get("foo1")).isSameAs(bean1); assertThat(((Map) actual).get("foo2")).isSameAs(bean2); } @Test void renderSimpleBeanWithJsonView() throws Exception { Object bean = new TestBeanSimple(); Map<String, Object> model = new HashMap<>(); model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", bean); model.put(JsonView.class.getName(), MyJacksonView1.class); view.setUpdateContentLength(true); view.render(model, request, response); String content = response.getContentAsString(); assertThat(content).isNotEmpty(); assertThat(response.getContentLength()).isEqualTo(content.length()); assertThat(content).contains("foo"); assertThat(content).doesNotContain("boo"); assertThat(content).doesNotContain(JsonView.class.getName()); } @Test void renderSimpleBeanWithFilters() throws Exception { TestSimpleBeanFiltered bean = new TestSimpleBeanFiltered(); bean.setProperty1("value"); bean.setProperty2("value"); Map<String, Object> model = new HashMap<>(); model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", bean); FilterProvider filters = new SimpleFilterProvider().addFilter("myJacksonFilter", SimpleBeanPropertyFilter.serializeAllExcept("property2")); model.put(FilterProvider.class.getName(), filters); view.setUpdateContentLength(true); view.render(model, request, response); String content = response.getContentAsString(); assertThat(content).isNotEmpty(); assertThat(response.getContentLength()).isEqualTo(content.length()); assertThat(content).contains("\"property1\":\"value\""); assertThat(content).doesNotContain("\"property2\":\"value\""); assertThat(content).doesNotContain(FilterProvider.class.getName()); } private void validateResult() throws Exception { String json = response.getContentAsString(); DirectFieldAccessor viewAccessor = new DirectFieldAccessor(view); String jsonPrefix = (String)viewAccessor.getPropertyValue("jsonPrefix"); if (jsonPrefix != null) { json = json.substring(5); } Object jsResult = jsContext.evaluateString(jsScope, "(" + json + ")", "JSON Stream", 1, null); assertThat(jsResult).as("Json Result did not eval as valid JavaScript").isNotNull(); MediaType mediaType = MediaType.parseMediaType(response.getContentType()); assertThat(mediaType.isCompatibleWith(MediaType.APPLICATION_JSON)).isTrue(); } public
MappingJackson2JsonViewTests
java
quarkusio__quarkus
integration-tests/hibernate-orm-tenancy/connection-resolver-legacy-qualifiers/src/main/java/io/quarkus/it/hibernate/multitenancy/ConnectionConfig.java
{ "start": 288, "end": 439 }
interface ____ { String username(); String password(); @WithDefault("10") int maxPoolSizePerTenant(); } }
PuConfig
java
grpc__grpc-java
xds/src/generated/thirdparty/grpc/io/envoyproxy/envoy/service/status/v3/ClientStatusDiscoveryServiceGrpc.java
{ "start": 14870, "end": 15940 }
class ____ extends io.grpc.stub.AbstractFutureStub<ClientStatusDiscoveryServiceFutureStub> { private ClientStatusDiscoveryServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ClientStatusDiscoveryServiceFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ClientStatusDiscoveryServiceFutureStub(channel, callOptions); } /** */ public com.google.common.util.concurrent.ListenableFuture<io.envoyproxy.envoy.service.status.v3.ClientStatusResponse> fetchClientStatus( io.envoyproxy.envoy.service.status.v3.ClientStatusRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getFetchClientStatusMethod(), getCallOptions()), request); } } private static final int METHODID_FETCH_CLIENT_STATUS = 0; private static final int METHODID_STREAM_CLIENT_STATUS = 1; private static final
ClientStatusDiscoveryServiceFutureStub
java
google__gson
test-shrinker/src/main/java/com/example/NoSerializedNameMain.java
{ "start": 607, "end": 671 }
class ____ { public String s; } static
TestClassNotAbstract
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/NodeState.java
{ "start": 1062, "end": 1994 }
enum ____ { /** New node */ NEW, /** Running node */ RUNNING, /** Node is unhealthy */ UNHEALTHY, /** Node is out of service */ DECOMMISSIONED, /** Node has not sent a heartbeat for some configured time threshold*/ LOST, /** Node has rebooted */ REBOOTED, /** Node decommission is in progress */ DECOMMISSIONING, /** Node has shutdown gracefully. */ SHUTDOWN; public boolean isUnusable() { return (this == UNHEALTHY || this == DECOMMISSIONED || this == LOST || this == SHUTDOWN); } public boolean isInactiveState() { return this == NodeState.DECOMMISSIONED || this == NodeState.LOST || this == NodeState.REBOOTED || this == NodeState.SHUTDOWN; } public boolean isActiveState() { return this == NodeState.NEW || this == NodeState.RUNNING || this == NodeState.UNHEALTHY || this == NodeState.DECOMMISSIONING; } }
NodeState
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/throwables/Throwables_assertHasRootCauseExactlyInstanceOf_Test.java
{ "start": 1187, "end": 3643 }
class ____ extends ThrowablesBaseTest { private static final Throwable throwableWithCause = new Throwable(new Exception(new IllegalArgumentException())); @Test void should_pass_if_root_cause_is_exactly_instance_of_expected_type() { throwables.assertHasRootCauseExactlyInstanceOf(INFO, throwableWithCause, IllegalArgumentException.class); } @Test void should_fail_if_actual_is_null() { // GIVEN Throwable actual = null; // WHEN var error = expectAssertionError(() -> throwables.assertHasRootCauseExactlyInstanceOf(INFO, actual, IOException.class)); // THEN then(error).hasMessage(actualIsNull()); } @Test void should_throw_NullPointerException_if_given_type_is_null() { // GIVEN Class<? extends Throwable> type = null; // WHEN Throwable throwable = catchThrowable(() -> throwables.assertHasRootCauseExactlyInstanceOf(INFO, throwableWithCause, type)); // THEN then(throwable).isInstanceOf(NullPointerException.class) .hasMessage("The given type should not be null"); } @Test void should_fail_if_actual_has_no_cause() { // GIVEN Class<NullPointerException> expectedCauseType = NullPointerException.class; // WHEN expectAssertionError(() -> throwables.assertHasRootCauseExactlyInstanceOf(INFO, actual, expectedCauseType)); // THEN verify(failures).failure(INFO, shouldHaveRootCauseExactlyInstance(actual, expectedCauseType)); } @Test void should_fail_if_root_cause_is_not_instance_of_expected_type() { // GIVEN Class<NullPointerException> expectedCauseType = NullPointerException.class; // WHEN expectAssertionError(() -> throwables.assertHasRootCauseExactlyInstanceOf(INFO, throwableWithCause, expectedCauseType)); // THEN verify(failures).failure(INFO, shouldHaveRootCauseExactlyInstance(throwableWithCause, expectedCauseType)); } @Test void should_fail_if_cause_is_not_exactly_instance_of_expected_type() { // GIVEN Class<RuntimeException> expectedCauseType = RuntimeException.class; // WHEN expectAssertionError(() -> throwables.assertHasRootCauseExactlyInstanceOf(INFO, throwableWithCause, expectedCauseType)); // THEN verify(failures).failure(INFO, shouldHaveRootCauseExactlyInstance(throwableWithCause, expectedCauseType)); } }
Throwables_assertHasRootCauseExactlyInstanceOf_Test
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverters.java
{ "start": 10036, "end": 10646 }
class ____ implements TypeConverter<Level> { /** * {@inheritDoc} * @param s the string to convert * @return the resolved level * @throws NullPointerException if the given value is {@code null}. * @throws IllegalArgumentException if the given argument is not resolvable to a level */ @Override public Level convert(final String s) { return Level.valueOf(s); } } /** * Converts a {@link String} into a {@link Long}. */ @Plugin(name = "Long", category = CATEGORY) public static
LevelConverter
java
google__auto
value/src/main/java/com/google/auto/value/processor/TypeEncoder.java
{ "start": 4750, "end": 5047 }
class ____ for {@link TypeEncoder} * covers the details of annotation encoding. */ static String encodeWithAnnotations(TypeMirror type) { return encodeWithAnnotations(type, ImmutableList.of(), ImmutableSet.of()); } /** * Encodes the given type and its type annotations. The
comment
java
apache__hadoop
hadoop-tools/hadoop-gridmix/src/main/java/org/apache/hadoop/mapred/gridmix/LoadJob.java
{ "start": 8580, "end": 9445 }
class ____ extends SubjectInheritingThread { private final TaskAttemptContext context; private final Progressive progress; StatusReporter(TaskAttemptContext context, Progressive progress) { this.context = context; this.progress = progress; } @Override public void work() { LOG.info("Status reporter thread started."); try { while (!isInterrupted() && progress.getProgress() < 1) { // report progress context.progress(); // sleep for some time try { Thread.sleep(100); // sleep for 100ms } catch (Exception e) {} } LOG.info("Status reporter thread exiting"); } catch (Exception e) { LOG.info("Exception while running the status reporter thread!", e); } } } public static
StatusReporter
java
apache__maven
compat/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/ComparableVersionTest.java
{ "start": 1104, "end": 18209 }
class ____ { private ComparableVersion newComparable(String version) { ComparableVersion ret = new ComparableVersion(version); String canonical = ret.getCanonical(); String parsedCanonical = new ComparableVersion(canonical).getCanonical(); assertEquals( canonical, parsedCanonical, "canonical( " + version + " ) = " + canonical + " -> canonical: " + parsedCanonical); return ret; } private static final String[] VERSIONS_QUALIFIER = { "1-alpha2snapshot", "1-alpha2", "1-alpha-123", "1-beta-2", "1-beta123", "1-m2", "1-m11", "1-rc", "1-cr2", "1-rc123", "1-SNAPSHOT", "1", "1-sp", "1-sp2", "1-sp123", "1-abc", "1-def", "1-pom-1", "1-1-snapshot", "1-1", "1-2", "1-123" }; private static final String[] VERSIONS_NUMBER = { "2.0", "2.0.a", "2-1", "2.0.2", "2.0.123", "2.1.0", "2.1-a", "2.1b", "2.1-c", "2.1-1", "2.1.0.1", "2.2", "2.123", "11.a2", "11.a11", "11.b2", "11.b11", "11.m2", "11.m11", "11", "11.a", "11b", "11c", "11m" }; private void checkVersionsOrder(String[] versions) { Comparable[] c = new Comparable[versions.length]; for (int i = 0; i < versions.length; i++) { c[i] = newComparable(versions[i]); } for (int i = 1; i < versions.length; i++) { Comparable low = c[i - 1]; for (int j = i; j < versions.length; j++) { Comparable high = c[j]; assertTrue(low.compareTo(high) < 0, "expected " + low + " < " + high); assertTrue(high.compareTo(low) > 0, "expected " + high + " > " + low); } } } private void checkVersionsEqual(String v1, String v2) { Comparable c1 = newComparable(v1); Comparable c2 = newComparable(v2); assertEquals(0, c1.compareTo(c2), "expected " + v1 + " == " + v2); assertEquals(0, c2.compareTo(c1), "expected " + v2 + " == " + v1); assertEquals(c1.hashCode(), c2.hashCode(), "expected same hashcode for " + v1 + " and " + v2); assertEquals(c1, c2, "expected " + v1 + ".equals( " + v2 + " )"); assertEquals(c2, c1, "expected " + v2 + ".equals( " + v1 + " )"); } private void checkVersionsHaveSameOrder(String v1, String v2) { ComparableVersion c1 = new ComparableVersion(v1); ComparableVersion c2 = new ComparableVersion(v2); assertEquals(0, c1.compareTo(c2), "expected " + v1 + " == " + v2); assertEquals(0, c2.compareTo(c1), "expected " + v2 + " == " + v1); } private void checkVersionsArrayEqual(String[] array) { // compare against each other (including itself) for (int i = 0; i < array.length; ++i) { for (int j = i; j < array.length; ++j) { checkVersionsEqual(array[i], array[j]); } } } private void checkVersionsOrder(String v1, String v2) { Comparable c1 = newComparable(v1); Comparable c2 = newComparable(v2); assertTrue(c1.compareTo(c2) < 0, "expected " + v1 + " < " + v2); assertTrue(c2.compareTo(c1) > 0, "expected " + v2 + " > " + v1); } @Test void testVersionsQualifier() { checkVersionsOrder(VERSIONS_QUALIFIER); } @Test void testVersionsNumber() { checkVersionsOrder(VERSIONS_NUMBER); } @Test void testVersionsEqual() { newComparable("1.0-alpha"); checkVersionsEqual("1", "1"); checkVersionsEqual("1", "1.0"); checkVersionsEqual("1", "1.0.0"); checkVersionsEqual("1.0", "1.0.0"); checkVersionsEqual("1", "1-0"); checkVersionsEqual("1", "1.0-0"); checkVersionsEqual("1.0", "1.0-0"); // no separator between number and character checkVersionsEqual("1a", "1-a"); checkVersionsEqual("1a", "1.0-a"); checkVersionsEqual("1a", "1.0.0-a"); checkVersionsEqual("1.0a", "1-a"); checkVersionsEqual("1.0.0a", "1-a"); checkVersionsEqual("1x", "1-x"); checkVersionsEqual("1x", "1.0-x"); checkVersionsEqual("1x", "1.0.0-x"); checkVersionsEqual("1.0x", "1-x"); checkVersionsEqual("1.0.0x", "1-x"); checkVersionsEqual("1cr", "1rc"); // special "aliases" a, b and m for alpha, beta and milestone checkVersionsEqual("1a1", "1-alpha-1"); checkVersionsEqual("1b2", "1-beta-2"); checkVersionsEqual("1m3", "1-milestone-3"); // case insensitive checkVersionsEqual("1X", "1x"); checkVersionsEqual("1A", "1a"); checkVersionsEqual("1B", "1b"); checkVersionsEqual("1M", "1m"); checkVersionsEqual("1Cr", "1Rc"); checkVersionsEqual("1cR", "1rC"); checkVersionsEqual("1m3", "1Milestone3"); checkVersionsEqual("1m3", "1MileStone3"); checkVersionsEqual("1m3", "1MILESTONE3"); } @Test void testVersionsHaveSameOrderButAreNotEqual() { checkVersionsHaveSameOrder("1ga", "1"); checkVersionsHaveSameOrder("1release", "1"); checkVersionsHaveSameOrder("1final", "1"); checkVersionsHaveSameOrder("1Ga", "1"); checkVersionsHaveSameOrder("1GA", "1"); checkVersionsHaveSameOrder("1RELEASE", "1"); checkVersionsHaveSameOrder("1release", "1"); checkVersionsHaveSameOrder("1RELeaSE", "1"); checkVersionsHaveSameOrder("1Final", "1"); checkVersionsHaveSameOrder("1FinaL", "1"); checkVersionsHaveSameOrder("1FINAL", "1"); } @Test void testVersionComparing() { checkVersionsOrder("1", "2"); checkVersionsOrder("1.5", "2"); checkVersionsOrder("1", "2.5"); checkVersionsOrder("1.0", "1.1"); checkVersionsOrder("1.1", "1.2"); checkVersionsOrder("1.0.0", "1.1"); checkVersionsOrder("1.0.1", "1.1"); checkVersionsOrder("1.1", "1.2.0"); checkVersionsOrder("1.0-alpha-1", "1.0"); checkVersionsOrder("1.0-alpha-1", "1.0-alpha-2"); checkVersionsOrder("1.0-alpha-1", "1.0-beta-1"); checkVersionsOrder("1.0-beta-1", "1.0-SNAPSHOT"); checkVersionsOrder("1.0-SNAPSHOT", "1.0"); checkVersionsOrder("1.0-alpha-1-SNAPSHOT", "1.0-alpha-1"); checkVersionsOrder("1.0", "1.0-1"); checkVersionsOrder("1.0-1", "1.0-2"); checkVersionsOrder("1.0.0", "1.0-1"); checkVersionsOrder("2.0-1", "2.0.1"); checkVersionsOrder("2.0.1-klm", "2.0.1-lmn"); checkVersionsOrder("2.0.1", "2.0.1-xyz"); checkVersionsOrder("2.0.1", "2.0.1-123"); checkVersionsOrder("2.0.1-xyz", "2.0.1-123"); } @Test void testLeadingZeroes() { checkVersionsOrder("0.7", "2"); checkVersionsOrder("0.2", "1.0.7"); } @Test void testDigitGreaterThanNonAscii() { ComparableVersion c1 = new ComparableVersion("1"); ComparableVersion c2 = new ComparableVersion("é"); assertTrue(c1.compareTo(c2) > 0, "expected " + "1" + " > " + "\uD835\uDFE4"); assertTrue(c2.compareTo(c1) < 0, "expected " + "\uD835\uDFE4" + " < " + "1"); } @Test void testDigitGreaterThanNonBmpCharacters() { ComparableVersion c1 = new ComparableVersion("1"); // MATHEMATICAL SANS-SERIF DIGIT TWO ComparableVersion c2 = new ComparableVersion("\uD835\uDFE4"); assertTrue(c1.compareTo(c2) > 0, "expected " + "1" + " > " + "\uD835\uDFE4"); assertTrue(c2.compareTo(c1) < 0, "expected " + "\uD835\uDFE4" + " < " + "1"); } @Test void testGetCanonical() { // MNG-7700 newComparable("0.x"); newComparable("0-x"); newComparable("0.rc"); newComparable("0-1"); ComparableVersion version = new ComparableVersion("0.x"); assertEquals("x", version.getCanonical()); ComparableVersion version2 = new ComparableVersion("0.2"); assertEquals("0.2", version2.getCanonical()); } @Test void testLexicographicASCIISortOrder() { // Required by Semver 1.0 ComparableVersion lower = new ComparableVersion("1.0.0-alpha1"); ComparableVersion upper = new ComparableVersion("1.0.0-ALPHA1"); // Lower case is equal to upper case. This is *NOT* what Semver 1.0 // specifies. Here we are explicitly deviating from Semver 1.0. assertTrue(upper.compareTo(lower) == 0, "expected 1.0.0-ALPHA1 == 1.0.0-alpha1"); assertTrue(lower.compareTo(upper) == 0, "expected 1.0.0-alpha1 == 1.0.0-ALPHA1"); } @Test void testCompareLowerCaseToUpperCaseASCII() { ComparableVersion lower = new ComparableVersion("1.a"); ComparableVersion upper = new ComparableVersion("1.A"); // Lower case is equal to upper case assertTrue(upper.compareTo(lower) == 0, "expected 1.A == 1.a"); assertTrue(lower.compareTo(upper) == 0, "expected 1.a == 1.A"); } @Test void testCompareLowerCaseToUpperCaseNonASCII() { ComparableVersion lower = new ComparableVersion("1.é"); ComparableVersion upper = new ComparableVersion("1.É"); // Lower case is equal to upper case assertTrue(upper.compareTo(lower) == 0, "expected 1.É < 1.é"); assertTrue(lower.compareTo(upper) == 0, "expected 1.é > 1.É"); } @Test void testCompareDigitToLetter() { ComparableVersion seven = new ComparableVersion("7"); ComparableVersion capitalJ = new ComparableVersion("J"); ComparableVersion lowerCaseC = new ComparableVersion("c"); // Digits are greater than letters assertTrue(seven.compareTo(capitalJ) > 0, "expected 7 > J"); assertTrue(capitalJ.compareTo(seven) < 0, "expected J < 1"); assertTrue(seven.compareTo(lowerCaseC) > 0, "expected 7 > c"); assertTrue(lowerCaseC.compareTo(seven) < 0, "expected c < 7"); } @Test void testNonAsciiDigits() { // These should not be treated as digits. ComparableVersion asciiOne = new ComparableVersion("1"); ComparableVersion arabicEight = new ComparableVersion("\u0668"); ComparableVersion asciiNine = new ComparableVersion("9"); assertTrue(asciiOne.compareTo(arabicEight) > 0, "expected " + "1" + " > " + "\u0668"); assertTrue(arabicEight.compareTo(asciiOne) < 0, "expected " + "\u0668" + " < " + "1"); assertTrue(asciiNine.compareTo(arabicEight) > 0, "expected " + "9" + " > " + "\u0668"); assertTrue(arabicEight.compareTo(asciiNine) < 0, "expected " + "\u0668" + " < " + "9"); } @Test void testLexicographicOrder() { ComparableVersion aardvark = new ComparableVersion("aardvark"); ComparableVersion zebra = new ComparableVersion("zebra"); assertTrue(zebra.compareTo(aardvark) > 0); assertTrue(aardvark.compareTo(zebra) < 0); // Greek zebra ComparableVersion greek = new ComparableVersion("ζέβρα"); assertTrue(greek.compareTo(zebra) > 0); assertTrue(zebra.compareTo(greek) < 0); } /** * Test <a href="https://issues.apache.org/jira/browse/MNG-5568">MNG-5568</a> edge case * which was showing transitive inconsistency: since A &gt; B and B &gt; C then we should have A &gt; C * otherwise sorting a list of ComparableVersions() will in some cases throw runtime exception; * see Netbeans issues <a href="https://netbeans.org/bugzilla/show_bug.cgi?id=240845">240845</a> and * <a href="https://netbeans.org/bugzilla/show_bug.cgi?id=226100">226100</a> */ @Test void testMng5568() { String a = "6.1.0"; String b = "6.1.0rc3"; String c = "6.1H.5-beta"; // this is the unusual version string, with 'H' in the middle checkVersionsOrder(b, a); // classical checkVersionsOrder(b, c); // now b < c, but before MNG-5568, we had b > c checkVersionsOrder(a, c); } /** * Test <a href="https://jira.apache.org/jira/browse/MNG-6572">MNG-6572</a> optimization. */ @Test void testMng6572() { String a = "20190126.230843"; // resembles a SNAPSHOT String b = "1234567890.12345"; // 10 digit number String c = "123456789012345.1H.5-beta"; // 15 digit number String d = "12345678901234567890.1H.5-beta"; // 20 digit number checkVersionsOrder(a, b); checkVersionsOrder(b, c); checkVersionsOrder(a, c); checkVersionsOrder(c, d); checkVersionsOrder(b, d); checkVersionsOrder(a, d); } /** * Test all versions are equal when starting with many leading zeroes regardless of string length * (related to MNG-6572 optimization) */ @Test void testVersionEqualWithLeadingZeroes() { // versions with string lengths from 1 to 19 String[] arr = new String[] { "0000000000000000001", "000000000000000001", "00000000000000001", "0000000000000001", "000000000000001", "00000000000001", "0000000000001", "000000000001", "00000000001", "0000000001", "000000001", "00000001", "0000001", "000001", "00001", "0001", "001", "01", "1" }; checkVersionsArrayEqual(arr); } /** * Test all "0" versions are equal when starting with many leading zeroes regardless of string length * (related to MNG-6572 optimization) */ @Test void testVersionZeroEqualWithLeadingZeroes() { // versions with string lengths from 1 to 19 String[] arr = new String[] { "0000000000000000000", "000000000000000000", "00000000000000000", "0000000000000000", "000000000000000", "00000000000000", "0000000000000", "000000000000", "00000000000", "0000000000", "000000000", "00000000", "0000000", "000000", "00000", "0000", "000", "00", "0" }; checkVersionsArrayEqual(arr); } /** * Test <a href="https://issues.apache.org/jira/browse/MNG-6964">MNG-6964</a> edge cases * for qualifiers that start with "-0.", which was showing A == C and B == C but A &lt; B. */ @Test void testMng6964() { String a = "1-0.alpha"; String b = "1-0.beta"; String c = "1"; checkVersionsOrder(a, c); // Now a < c, but before MNG-6964 they were equal checkVersionsOrder(b, c); // Now b < c, but before MNG-6964 they were equal checkVersionsOrder(a, b); // Should still be true } @Test void testLocaleIndependent() { Locale orig = Locale.getDefault(); Locale[] locales = {Locale.ENGLISH, new Locale("tr"), Locale.getDefault()}; try { for (Locale locale : locales) { Locale.setDefault(locale); checkVersionsEqual("1-abcdefghijklmnopqrstuvwxyz", "1-ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } } finally { Locale.setDefault(orig); } } @Test void testReuse() { ComparableVersion c1 = new ComparableVersion("1"); c1.parseVersion("2"); Comparable<?> c2 = newComparable("2"); assertEquals(c1, c2, "reused instance should be equivalent to new instance"); } /** * Test <a href="https://issues.apache.org/jira/browse/MNG-7644">MNG-7644</a> edge cases * 1.0.0.RC1 &lt; 1.0.0-RC2 and more generally: * 1.0.0.X1 &lt; 1.0.0-X2 for any string X */ @Test void testMng7644() { for (String x : new String[] {"abc", "alpha", "a", "beta", "b", "def", "milestone", "m", "RC"}) { // 1.0.0.X1 < 1.0.0-X2 for any string x checkVersionsOrder("1.0.0." + x + "1", "1.0.0-" + x + "2"); // 2.0.X == 2-X == 2.0.0.X for any string x checkVersionsEqual("2-" + x, "2.0." + x); // previously ordered, now equals checkVersionsEqual("2-" + x, "2.0.0." + x); // previously ordered, now equals checkVersionsEqual("2.0." + x, "2.0.0." + x); // previously ordered, now equals } } @Test public void testMng7714() { ComparableVersion f = new ComparableVersion("1.0.final-redhat"); ComparableVersion sp1 = new ComparableVersion("1.0-sp1-redhat"); ComparableVersion sp2 = new ComparableVersion("1.0-sp-1-redhat"); ComparableVersion sp3 = new ComparableVersion("1.0-sp.1-redhat"); assertTrue(f.compareTo(sp1) < 0, "expected " + f + " < " + sp1); assertTrue(f.compareTo(sp2) < 0, "expected " + f + " < " + sp2); assertTrue(f.compareTo(sp3) < 0, "expected " + f + " < " + sp3); } }
ComparableVersionTest
java
grpc__grpc-java
services/src/generated/test/grpc/io/grpc/reflection/testing/AnotherDynamicServiceGrpc.java
{ "start": 10061, "end": 11842 }
class ____<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final AsyncService serviceImpl; private final int methodId; MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_METHOD: serviceImpl.method((io.grpc.reflection.testing.DynamicRequest) request, (io.grpc.stub.StreamObserver<io.grpc.reflection.testing.DynamicReply>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getMethodMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< io.grpc.reflection.testing.DynamicRequest, io.grpc.reflection.testing.DynamicReply>( service, METHODID_METHOD))) .build(); } private static abstract
MethodHandlers
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SqlEndpointBuilderFactory.java
{ "start": 91316, "end": 102806 }
interface ____ extends AdvancedSqlEndpointConsumerBuilder, AdvancedSqlEndpointProducerBuilder { default SqlEndpointBuilder basic() { return (SqlEndpointBuilder) this; } /** * If enabled then the populateStatement method from * org.apache.camel.component.sql.SqlPrepareStatementStrategy is always * invoked, also if there is no expected parameters to be prepared. When * this is false then the populateStatement is only invoked if there is * 1 or more expected parameters to be set; for example this avoids * reading the message body/headers for SQL queries with no parameters. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param alwaysPopulateStatement the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder alwaysPopulateStatement(boolean alwaysPopulateStatement) { doSetProperty("alwaysPopulateStatement", alwaysPopulateStatement); return this; } /** * If enabled then the populateStatement method from * org.apache.camel.component.sql.SqlPrepareStatementStrategy is always * invoked, also if there is no expected parameters to be prepared. When * this is false then the populateStatement is only invoked if there is * 1 or more expected parameters to be set; for example this avoids * reading the message body/headers for SQL queries with no parameters. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param alwaysPopulateStatement the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder alwaysPopulateStatement(String alwaysPopulateStatement) { doSetProperty("alwaysPopulateStatement", alwaysPopulateStatement); return this; } /** * Gives the JDBC driver a hint as to the number of rows that should be * fetched from the database when more rows are needed for ResultSet * objects generated by this Statement. If the value specified is zero, * then the hint is ignored. The default value is zero. This is * important for processing large result sets: Setting this higher than * the default value will increase processing speed at the cost of * memory consumption; setting this lower can avoid transferring row * data that will never be read by the application. * * The option is a: <code>int</code> type. * * Group: advanced * * @param fetchSize the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder fetchSize(int fetchSize) { doSetProperty("fetchSize", fetchSize); return this; } /** * Gives the JDBC driver a hint as to the number of rows that should be * fetched from the database when more rows are needed for ResultSet * objects generated by this Statement. If the value specified is zero, * then the hint is ignored. The default value is zero. This is * important for processing large result sets: Setting this higher than * the default value will increase processing speed at the cost of * memory consumption; setting this lower can avoid transferring row * data that will never be read by the application. * * The option will be converted to a <code>int</code> type. * * Group: advanced * * @param fetchSize the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder fetchSize(String fetchSize) { doSetProperty("fetchSize", fetchSize); return this; } /** * If set greater than zero, then Camel will use this count value of * parameters to replace instead of querying via JDBC metadata API. This * is useful if the JDBC vendor could not return correct parameters * count, then user may override instead. * * The option is a: <code>int</code> type. * * Group: advanced * * @param parametersCount the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder parametersCount(int parametersCount) { doSetProperty("parametersCount", parametersCount); return this; } /** * If set greater than zero, then Camel will use this count value of * parameters to replace instead of querying via JDBC metadata API. This * is useful if the JDBC vendor could not return correct parameters * count, then user may override instead. * * The option will be converted to a <code>int</code> type. * * Group: advanced * * @param parametersCount the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder parametersCount(String parametersCount) { doSetProperty("parametersCount", parametersCount); return this; } /** * Specifies a character that will be replaced to in SQL query. Notice, * that it is simple String.replaceAll() operation and no SQL parsing is * involved (quoted strings will also change). * * The option is a: <code>java.lang.String</code> type. * * Default: # * Group: advanced * * @param placeholder the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder placeholder(String placeholder) { doSetProperty("placeholder", placeholder); return this; } /** * Allows to plugin to use a custom * org.apache.camel.component.sql.SqlPrepareStatementStrategy to control * preparation of the query and prepared statement. * * The option is a: * <code>org.apache.camel.component.sql.SqlPrepareStatementStrategy</code> type. * * Group: advanced * * @param prepareStatementStrategy the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder prepareStatementStrategy(org.apache.camel.component.sql.SqlPrepareStatementStrategy prepareStatementStrategy) { doSetProperty("prepareStatementStrategy", prepareStatementStrategy); return this; } /** * Allows to plugin to use a custom * org.apache.camel.component.sql.SqlPrepareStatementStrategy to control * preparation of the query and prepared statement. * * The option will be converted to a * <code>org.apache.camel.component.sql.SqlPrepareStatementStrategy</code> type. * * Group: advanced * * @param prepareStatementStrategy the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder prepareStatementStrategy(String prepareStatementStrategy) { doSetProperty("prepareStatementStrategy", prepareStatementStrategy); return this; } /** * Factory for creating RowMapper. * * The option is a: * <code>org.apache.camel.component.sql.RowMapperFactory</code> type. * * Group: advanced * * @param rowMapperFactory the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder rowMapperFactory(org.apache.camel.component.sql.RowMapperFactory rowMapperFactory) { doSetProperty("rowMapperFactory", rowMapperFactory); return this; } /** * Factory for creating RowMapper. * * The option will be converted to a * <code>org.apache.camel.component.sql.RowMapperFactory</code> type. * * Group: advanced * * @param rowMapperFactory the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder rowMapperFactory(String rowMapperFactory) { doSetProperty("rowMapperFactory", rowMapperFactory); return this; } /** * Configures the Spring JdbcTemplate with the key/values from the Map. * This is a multi-value option with prefix: template. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * templateOptions(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: advanced * * @param key the option key * @param value the option value * @return the dsl builder */ default AdvancedSqlEndpointBuilder templateOptions(String key, Object value) { doSetMultiValueProperty("templateOptions", "template." + key, value); return this; } /** * Configures the Spring JdbcTemplate with the key/values from the Map. * This is a multi-value option with prefix: template. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * templateOptions(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: advanced * * @param values the values * @return the dsl builder */ default AdvancedSqlEndpointBuilder templateOptions(Map values) { doSetMultiValueProperties("templateOptions", "template.", values); return this; } /** * Sets whether to use placeholder and replace all placeholder * characters with sign in the SQL queries. * * The option is a: <code>boolean</code> type. * * Default: true * Group: advanced * * @param usePlaceholder the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder usePlaceholder(boolean usePlaceholder) { doSetProperty("usePlaceholder", usePlaceholder); return this; } /** * Sets whether to use placeholder and replace all placeholder * characters with sign in the SQL queries. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: advanced * * @param usePlaceholder the value to set * @return the dsl builder */ default AdvancedSqlEndpointBuilder usePlaceholder(String usePlaceholder) { doSetProperty("usePlaceholder", usePlaceholder); return this; } } public
AdvancedSqlEndpointBuilder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AlreadyCheckedTest.java
{ "start": 9001, "end": 9516 }
class ____ { public int test(int a, int b) { if (a == 1) { if (a == b) { return 3; } // BUG: Diagnostic contains: return a != 1 ? 1 : 2; } return 0; } } """) .doTest(); } @Test public void checkedTwiceWithinTernary() { helper .addSourceLines( "Test.java", """
Test
java
apache__camel
components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/AccountEndpointConfigurationConfigurer.java
{ "start": 730, "end": 3295 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("ApiName", org.apache.camel.component.twilio.internal.TwilioApiName.class); map.put("MethodName", java.lang.String.class); map.put("PathSid", java.lang.String.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.twilio.AccountEndpointConfiguration target = (org.apache.camel.component.twilio.AccountEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "apiName": target.setApiName(property(camelContext, org.apache.camel.component.twilio.internal.TwilioApiName.class, value)); return true; case "methodname": case "methodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true; case "pathsid": case "pathSid": target.setPathSid(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "apiName": return org.apache.camel.component.twilio.internal.TwilioApiName.class; case "methodname": case "methodName": return java.lang.String.class; case "pathsid": case "pathSid": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.twilio.AccountEndpointConfiguration target = (org.apache.camel.component.twilio.AccountEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "apiName": return target.getApiName(); case "methodname": case "methodName": return target.getMethodName(); case "pathsid": case "pathSid": return target.getPathSid(); default: return null; } } }
AccountEndpointConfigurationConfigurer
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timeline-pluginstorage/src/main/java/org/apache/hadoop/yarn/server/timeline/EntityGroupFSTimelineStore.java
{ "start": 12247, "end": 28700 }
class ____ for " + name, e); } LOG.info("Load plugin class {}", cacheIdPlugin.getClass().getName()); pluginList.add(cacheIdPlugin); } return pluginList; } private TimelineStore createSummaryStore() { return ReflectionUtils.newInstance(getConfig().getClass( YarnConfiguration.TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_SUMMARY_STORE, LeveldbTimelineStore.class, TimelineStore.class), getConfig()); } @Override protected void serviceStart() throws Exception { super.serviceStart(); LOG.info("Starting {}", getName()); summaryStore.start(); Configuration conf = getConfig(); aclManager = new TimelineACLsManager(conf); aclManager.setTimelineStore(summaryStore); summaryTdm = new TimelineDataManager(summaryStore, aclManager); summaryTdm.init(conf); addService(summaryTdm); // start child services that aren't already started super.serviceStart(); if (!fs.exists(activeRootPath)) { fs.mkdirs(activeRootPath); fs.setPermission(activeRootPath, ACTIVE_DIR_PERMISSION); } if (!fs.exists(doneRootPath)) { fs.mkdirs(doneRootPath); fs.setPermission(doneRootPath, DONE_DIR_PERMISSION); } // Recover the lastProcessedTime and offset for logfiles if (recoveryEnabled && fs.exists(checkpointFile)) { try (FSDataInputStream in = fs.open(checkpointFile)) { recoveredLogs.putAll(recoverLogFiles(in)); } catch (IOException e) { LOG.warn("Failed to recover summarylog files from the checkpointfile", e); } } objMapper = new ObjectMapper(); objMapper.setAnnotationIntrospector( new JaxbAnnotationIntrospector(TypeFactory.defaultInstance())); jsonFactory = new MappingJsonFactory(objMapper); final long scanIntervalSecs = conf.getLong( YarnConfiguration .TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_SCAN_INTERVAL_SECONDS, YarnConfiguration .TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_SCAN_INTERVAL_SECONDS_DEFAULT ); final long cleanerIntervalSecs = conf.getLong( YarnConfiguration .TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_CLEANER_INTERVAL_SECONDS, YarnConfiguration .TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_CLEANER_INTERVAL_SECONDS_DEFAULT ); final int numThreads = conf.getInt( YarnConfiguration.TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_THREADS, YarnConfiguration .TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_THREADS_DEFAULT); LOG.info("Scanning active directory {} every {} seconds", activeRootPath, scanIntervalSecs); LOG.info("Cleaning logs every {} seconds", cleanerIntervalSecs); executor = new ScheduledThreadPoolExecutor(numThreads, new ThreadFactoryBuilder().setNameFormat("EntityLogPluginWorker #%d") .build()); executor.scheduleAtFixedRate(new EntityLogScanner(), 0, scanIntervalSecs, TimeUnit.SECONDS); executor.scheduleAtFixedRate(new EntityLogCleaner(), cleanerIntervalSecs, cleanerIntervalSecs, TimeUnit.SECONDS); } @Override protected void serviceStop() throws Exception { LOG.info("Stopping {}", getName()); stopExecutors.set(true); if (executor != null) { executor.shutdown(); if (executor.isTerminating()) { LOG.info("Waiting for executor to terminate"); boolean terminated = executor.awaitTermination(10, TimeUnit.SECONDS); if (terminated) { LOG.info("Executor terminated"); } else { LOG.warn("Executor did not terminate"); executor.shutdownNow(); } } } synchronized (cachedLogs) { for (EntityCacheItem cacheItem : cachedLogs.values()) { ServiceOperations.stopQuietly(cacheItem.getStore()); } } CallerContext.setCurrent(null); super.serviceStop(); } /* Returns Map of SummaryLog files. The Value Pair has lastProcessedTime and offset */ HashMap<String, Pair<Long, Long>> recoverLogFiles( DataInputStream in) throws IOException { HashMap<String, Pair<Long, Long>> logFiles = new HashMap<>(); long totalEntries = in.readLong(); for (long i = 0; i < totalEntries; i++) { Text attemptDirName = new Text(); attemptDirName.readFields(in); Text fileName = new Text(); fileName.readFields(in); LongWritable lastProcessedTime = new LongWritable(); lastProcessedTime.readFields(in); LongWritable offset = new LongWritable(); offset.readFields(in); Pair<Long, Long> pair = Pair.of(lastProcessedTime.get(), offset.get()); logFiles.put(attemptDirName + Path.SEPARATOR + fileName, pair); } LOG.info("Recovered {} summarylog files", totalEntries); return logFiles; } // Stores set of SummaryLog files void storeLogFiles(Collection<AppLogs> appLogs, DataOutputStream checkPointStream) throws IOException { long totalEntries = 0L; for (AppLogs appLog : appLogs) { totalEntries += appLog.summaryLogs.size(); } checkPointStream.writeLong(totalEntries); for (AppLogs appLog : appLogs) { for (LogInfo summaryLog : appLog.summaryLogs) { new Text(summaryLog.getAttemptDirName()).write(checkPointStream); new Text(summaryLog.getFilename()).write(checkPointStream); new LongWritable(summaryLog.getLastProcessedTime()).write(checkPointStream); new LongWritable(summaryLog.getOffset()).write(checkPointStream); } } LOG.info("Stored {} summarylog files into checkPointFile", totalEntries); } @InterfaceAudience.Private @VisibleForTesting int scanActiveLogs() throws IOException { long startTime = Time.monotonicNow(); // Store the Last Processed Time and Offset if (recoveryEnabled && appIdLogMap.size() > 0) { try (FSDataOutputStream checkPointStream = fs.create(checkpointFile, true)) { storeLogFiles(appIdLogMap.values(), checkPointStream); } catch (Exception e) { LOG.warn("Failed to checkpoint the summarylog files", e); } } int logsToScanCount = scanActiveLogs(activeRootPath); metrics.addActiveLogDirScanTime(Time.monotonicNow() - startTime); return logsToScanCount; } int scanActiveLogs(Path dir) throws IOException { RemoteIterator<FileStatus> iter = list(dir); int logsToScanCount = 0; while (iter.hasNext()) { FileStatus stat = iter.next(); String name = stat.getPath().getName(); ApplicationId appId = parseApplicationId(name); if (appId != null) { LOG.debug("scan logs for {} in {}", appId, stat.getPath()); logsToScanCount++; AppLogs logs = getAndSetActiveLog(appId, stat.getPath()); executor.execute(new ActiveLogParser(logs)); } else { if (stat.isDirectory()) { logsToScanCount += scanActiveLogs(stat.getPath()); } else { LOG.warn("Ignoring unexpected file in active directory {}", stat.getPath()); } } } return logsToScanCount; } /** * List a directory, returning an iterator which will fail fast if this * service has been stopped * @param path path to list * @return an iterator over the contents of the directory * @throws IOException */ private RemoteIterator<FileStatus> list(Path path) throws IOException { return new StoppableRemoteIterator(fs.listStatusIterator(path)); } private AppLogs createAndPutAppLogsIfAbsent(ApplicationId appId, Path appDirPath, AppState appState) { AppLogs appLogs = new AppLogs(appId, appDirPath, appState); AppLogs oldAppLogs = appIdLogMap.putIfAbsent(appId, appLogs); if (oldAppLogs != null) { appLogs = oldAppLogs; } return appLogs; } private AppLogs getAndSetActiveLog(ApplicationId appId, Path appDirPath) { AppLogs appLogs = appIdLogMap.get(appId); if (appLogs == null) { appLogs = createAndPutAppLogsIfAbsent(appId, appDirPath, AppState.ACTIVE); } return appLogs; } // searches for the app logs and returns it if found else null private AppLogs getAndSetAppLogs(ApplicationId applicationId) throws IOException { LOG.debug("Looking for app logs mapped for app id {}", applicationId); AppLogs appLogs = appIdLogMap.get(applicationId); if (appLogs == null) { AppState appState = AppState.UNKNOWN; Path appDirPath = getDoneAppPath(applicationId); if (fs.exists(appDirPath)) { appState = AppState.COMPLETED; } else { appDirPath = getActiveAppPath(applicationId); if (fs.exists(appDirPath)) { appState = AppState.ACTIVE; } else { // check for user directory inside active path RemoteIterator<FileStatus> iter = list(activeRootPath); while (iter.hasNext()) { Path child = new Path(iter.next().getPath().getName(), applicationId.toString()); appDirPath = new Path(activeRootPath, child); if (fs.exists(appDirPath)) { appState = AppState.ACTIVE; break; } } } } if (appState != AppState.UNKNOWN) { LOG.debug("Create and try to add new appLogs to appIdLogMap for {}", applicationId); appLogs = createAndPutAppLogsIfAbsent( applicationId, appDirPath, appState); } } return appLogs; } /** * Main function for entity log cleaner. This method performs depth first * search from a given dir path for all application log dirs. Once found, it * will decide if the directory should be cleaned up and then clean them. * * @param dirpath the root directory the cleaner should start with. Note that * dirpath should be a directory that contains a set of * application log directories. The cleaner method will not * work if the given dirpath itself is an application log dir. * @param retainMillis * @throws IOException */ @InterfaceAudience.Private @VisibleForTesting void cleanLogs(Path dirpath, long retainMillis) throws IOException { long now = Time.now(); RemoteIterator<FileStatus> iter = list(dirpath); while (iter.hasNext()) { FileStatus stat = iter.next(); if (isValidClusterTimeStampDir(stat)) { Path clusterTimeStampPath = stat.getPath(); MutableBoolean appLogDirPresent = new MutableBoolean(false); cleanAppLogDir(clusterTimeStampPath, retainMillis, appLogDirPresent); if (appLogDirPresent.isFalse() && (now - stat.getModificationTime() > retainMillis)) { deleteDir(clusterTimeStampPath); } } } } private void cleanAppLogDir(Path dirpath, long retainMillis, MutableBoolean appLogDirPresent) throws IOException { long now = Time.now(); // Depth first search from root directory for all application log dirs RemoteIterator<FileStatus> iter = list(dirpath); while (iter.hasNext()) { FileStatus stat = iter.next(); Path childPath = stat.getPath(); if (stat.isDirectory()) { // If current is an application log dir, decide if we need to remove it // and remove if necessary. // Otherwise, keep iterating into it. ApplicationId appId = parseApplicationId(childPath.getName()); if (appId != null) { // Application log dir appLogDirPresent.setTrue(); if (shouldCleanAppLogDir(childPath, now, fs, retainMillis)) { deleteDir(childPath); } } else { // Keep cleaning inside cleanAppLogDir(childPath, retainMillis, appLogDirPresent); } } } } private void deleteDir(Path path) { try { LOG.info("Deleting {}", path); if (fs.delete(path, true)) { metrics.incrLogsDirsCleaned(); } else { LOG.error("Unable to remove {}", path); } } catch (IOException e) { LOG.error("Unable to remove {}", path, e); } } private boolean isValidClusterTimeStampDir(FileStatus stat) { return stat.isDirectory() && StringUtils.isNumeric(stat.getPath().getName()); } private static boolean shouldCleanAppLogDir(Path appLogPath, long now, FileSystem fs, long logRetainMillis) throws IOException { RemoteIterator<FileStatus> iter = fs.listStatusIterator(appLogPath); while (iter.hasNext()) { FileStatus stat = iter.next(); if (now - stat.getModificationTime() <= logRetainMillis) { // found a dir entry that is fresh enough to prevent // cleaning this directory. LOG.debug("{} not being cleaned due to {}", appLogPath, stat.getPath()); return false; } // Otherwise, keep searching files inside for directories. if (stat.isDirectory()) { if (!shouldCleanAppLogDir(stat.getPath(), now, fs, logRetainMillis)) { return false; } } } return true; } // converts the String to an ApplicationId or null if conversion failed private static ApplicationId parseApplicationId(String appIdStr) { try { return ApplicationId.fromString(appIdStr); } catch (IllegalArgumentException e) { return null; } } private static ClassLoader createPluginClassLoader( final String appClasspath, final String[] systemClasses) throws IOException { try { return AccessController.doPrivileged( new PrivilegedExceptionAction<ClassLoader>() { @Override public ClassLoader run() throws MalformedURLException { return new ApplicationClassLoader(appClasspath, EntityGroupFSTimelineStore.class.getClassLoader(), Arrays.asList(systemClasses)); } } ); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof MalformedURLException) { throw (MalformedURLException) t; } throw new IOException(e); } } private Path getActiveAppPath(ApplicationId appId) { return new Path(activeRootPath, appId.toString()); } private Path getDoneAppPath(ApplicationId appId) { // cut up the app ID into mod(1000) buckets int appNum = appId.getId(); appNum /= 1000; int bucket2 = appNum % 1000; int bucket1 = appNum / 1000; return new Path(doneRootPath, String.format(APP_DONE_DIR_PREFIX_FORMAT, appId.getClusterTimestamp(), bucket1, bucket2, appId.toString())); } /** * Create and initialize the YARN Client. Tests may override/mock this. * If they return null, then {@link #getAppState(ApplicationId)} MUST * also be overridden * @param conf configuration * @return the yarn client, or null. * */ @VisibleForTesting protected YarnClient createAndInitYarnClient(Configuration conf) { YarnClient client = YarnClient.createYarnClient(); client.init(conf); return client; } /** * Get the application state. * @param appId application ID * @return the state or {@link AppState#UNKNOWN} if it could not * be determined * @throws IOException on IO problems */ @VisibleForTesting protected AppState getAppState(ApplicationId appId) throws IOException { return getAppState(appId, yarnClient); } /** * Get all plugins for tests. * @return all plugins */ @VisibleForTesting List<TimelineEntityGroupPlugin> getPlugins() { return cacheIdPlugins; } /** * Ask the RM for the state of the application. * This method has to be synchronized to control traffic to RM * @param appId application ID * @param yarnClient * @return the state or {@link AppState#UNKNOWN} if it could not * be determined * @throws IOException */ private static synchronized AppState getAppState(ApplicationId appId, YarnClient yarnClient) throws IOException { AppState appState = AppState.ACTIVE; try { ApplicationReport report = yarnClient.getApplicationReport(appId); if (Apps.isApplicationFinalState(report.getYarnApplicationState())) { appState = AppState.COMPLETED; } } catch (ApplicationNotFoundException e) { appState = AppState.UNKNOWN; } catch (YarnException e) { throw new IOException(e); } return appState; } /** * Application states, */ @InterfaceAudience.Private @VisibleForTesting public
defined
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/blocking/beans/BeanReturningMessages.java
{ "start": 450, "end": 1033 }
class ____ { private final AtomicInteger count = new AtomicInteger(); private final List<String> threads = new CopyOnWriteArrayList<>(); @Blocking @Outgoing("infinite-producer-msg") public Message<Integer> create() { try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } threads.add(Thread.currentThread().getName()); return Message.of(count.incrementAndGet()); } public List<String> threads() { return threads; } }
BeanReturningMessages
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e4/c/DerivedIdentitySimpleParentSimpleDepSecondPassOrderingTest.java
{ "start": 5004, "end": 5312 }
class ____ { @Id private Integer id; public EntityWithSimpleId() { } public EntityWithSimpleId(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } @Entity(name = "oto_derived") public static
EntityWithSimpleId
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/inject/visitor/TypeElementQuery.java
{ "start": 2321, "end": 2920 }
enum ____. * * @return this query */ TypeElementQuery excludeEnumConstants(); /** * Include all. * * @return this query */ TypeElementQuery includeAll(); /** * Exclude all. * * @return this query */ TypeElementQuery excludeAll(); /** * @return Is includes methods? */ boolean includesMethods(); /** * @return Is includes fields? */ boolean includesFields(); /** * @return Is includes constructors? */ boolean includesConstructors(); /** * @return Is
constants
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java
{ "start": 3501, "end": 3593 }
class ____ { @GET public String test() { return "test"; } } } }
TestEndpoint
java
spring-projects__spring-framework
spring-web/src/testFixtures/java/org/springframework/web/testfixture/http/client/reactive/MockClientHttpResponse.java
{ "start": 1694, "end": 4222 }
class ____ implements ClientHttpResponse { private final HttpStatusCode statusCode; private final HttpHeaders headers = new HttpHeaders(); private final MultiValueMap<String, ResponseCookie> cookies = new LinkedMultiValueMap<>(); private Flux<DataBuffer> body = Flux.empty(); public MockClientHttpResponse(int status) { this(HttpStatusCode.valueOf(status)); } public MockClientHttpResponse(HttpStatusCode status) { Assert.notNull(status, "HttpStatusCode is required"); this.statusCode = status; } @Override public HttpStatusCode getStatusCode() { return this.statusCode; } @Override public HttpHeaders getHeaders() { if (!getCookies().isEmpty() && this.headers.get(HttpHeaders.SET_COOKIE) == null) { getCookies().values().stream().flatMap(Collection::stream) .forEach(cookie -> this.headers.add(HttpHeaders.SET_COOKIE, cookie.toString())); } return this.headers; } @Override public MultiValueMap<String, ResponseCookie> getCookies() { return this.cookies; } public void setBody(Publisher<DataBuffer> body) { this.body = Flux.from(body); } public void setBody(String body) { setBody(body, StandardCharsets.UTF_8); } public void setBody(String body, Charset charset) { DataBuffer buffer = toDataBuffer(body, charset); this.body = Flux.just(buffer); } private DataBuffer toDataBuffer(String body, Charset charset) { byte[] bytes = body.getBytes(charset); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); return DefaultDataBufferFactory.sharedInstance.wrap(byteBuffer); } @Override public Flux<DataBuffer> getBody() { return this.body; } /** * Return the response body aggregated and converted to a String using the * charset of the Content-Type response or otherwise as "UTF-8". */ public Mono<String> getBodyAsString() { return DataBufferUtils.join(getBody()) .map(buffer -> { String s = buffer.toString(getCharset()); DataBufferUtils.release(buffer); return s; }) .defaultIfEmpty(""); } private Charset getCharset() { Charset charset = null; MediaType contentType = getHeaders().getContentType(); if (contentType != null) { charset = contentType.getCharset(); } return (charset != null ? charset : StandardCharsets.UTF_8); } @Override public String toString() { if (this.statusCode instanceof HttpStatus status) { return status.name() + "(" + this.statusCode + ")" + this.headers; } else { return "Status (" + this.statusCode + ")" + this.headers; } } }
MockClientHttpResponse
java
apache__flink
flink-rpc/flink-rpc-core/src/test/java/org/apache/flink/runtime/rpc/RpcSystemTest.java
{ "start": 2026, "end": 2408 }
class ____ implements RpcSystemLoader { @Override public int getLoadPriority() { return 0; } @Override public RpcSystem loadRpcSystem(Configuration config) { return new DummyTestRpcSystem(); } } /** Test {@link RpcSystemLoader} with a low priority. */ public static final
HighPriorityRpcSystemLoader
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/MedianAbsoluteDeviationFloatGroupingAggregatorFunctionTests.java
{ "start": 909, "end": 3145 }
class ____ extends GroupingAggregatorFunctionTestCase { @Override protected SourceOperator simpleInput(BlockFactory blockFactory, int end) { Float[][] samples = new Float[][] { { 1.2f, 1.25f, 2.0f, 2.0f, 4.3f, 6.0f, 9.0f }, { 0.1f, 1.5f, 2.0f, 3.0f, 4.0f, 7.5f, 100.0f }, { 0.2f, 1.75f, 2.0f, 2.5f }, { 0.5f, 3.0f, 3.0f, 3.0f, 4.3f }, { 0.25f, 1.5f, 3.0f } }; List<Tuple<Long, Float>> values = new ArrayList<>(); for (int i = 0; i < samples.length; i++) { List<Float> list = Arrays.stream(samples[i]).collect(Collectors.toList()); Randomness.shuffle(list); for (float v : list) { values.add(Tuple.tuple((long) i, v)); } } return new LongFloatTupleBlockSourceOperator(blockFactory, values.subList(0, Math.min(values.size(), end))); } @Override protected AggregatorFunctionSupplier aggregatorFunction() { return new MedianAbsoluteDeviationFloatAggregatorFunctionSupplier(); } @Override protected String expectedDescriptionOfAggregator() { return "median_absolute_deviation of floats"; } @Override protected void assertSimpleGroup(List<Page> input, Block result, int position, Long group) { double medianAbsoluteDeviation = medianAbsoluteDeviation(input.stream().flatMap(p -> allFloats(p, group))); assertThat(((DoubleBlock) result).getDouble(position), closeTo(medianAbsoluteDeviation, medianAbsoluteDeviation * .000001)); } static double medianAbsoluteDeviation(Stream<Float> s) { Float[] data = s.toArray(Float[]::new); float median = median(Arrays.stream(data)); return median(Arrays.stream(data).map(d -> Math.abs(median - d))); } static float median(Stream<Float> s) { // The input data is small enough that tdigest will find the actual median. Float[] data = s.sorted().toArray(Float[]::new); if (data.length == 0) { return 0; } int c = data.length / 2; return data.length % 2 == 0 ? (data[c - 1] + data[c]) / 2 : data[c]; } }
MedianAbsoluteDeviationFloatGroupingAggregatorFunctionTests
java
apache__spark
launcher/src/test/java/org/apache/spark/launcher/CommandBuilderUtilsSuite.java
{ "start": 1072, "end": 4837 }
class ____ { @Test public void testValidOptionStrings() { testOpt("a b c d e", Arrays.asList("a", "b", "c", "d", "e")); testOpt("a 'b c' \"d\" e", Arrays.asList("a", "b c", "d", "e")); testOpt("a 'b\\\"c' \"'d'\" e", Arrays.asList("a", "b\\\"c", "'d'", "e")); testOpt("a 'b\"c' \"\\\"d\\\"\" e", Arrays.asList("a", "b\"c", "\"d\"", "e")); testOpt(" a b c \\\\ ", Arrays.asList("a", "b", "c", "\\")); // Following tests ported from UtilsSuite.scala. testOpt("", new ArrayList<>()); testOpt("a", Arrays.asList("a")); testOpt("aaa", Arrays.asList("aaa")); testOpt("a b c", Arrays.asList("a", "b", "c")); testOpt(" a b\t c ", Arrays.asList("a", "b", "c")); testOpt("a 'b c'", Arrays.asList("a", "b c")); testOpt("a 'b c' d", Arrays.asList("a", "b c", "d")); testOpt("'b c'", Arrays.asList("b c")); testOpt("a \"b c\"", Arrays.asList("a", "b c")); testOpt("a \"b c\" d", Arrays.asList("a", "b c", "d")); testOpt("\"b c\"", Arrays.asList("b c")); testOpt("a 'b\" c' \"d' e\"", Arrays.asList("a", "b\" c", "d' e")); testOpt("a\t'b\nc'\nd", Arrays.asList("a", "b\nc", "d")); testOpt("a \"b\\\\c\"", Arrays.asList("a", "b\\c")); testOpt("a \"b\\\"c\"", Arrays.asList("a", "b\"c")); testOpt("a 'b\\\"c'", Arrays.asList("a", "b\\\"c")); testOpt("'a'b", Arrays.asList("ab")); testOpt("'a''b'", Arrays.asList("ab")); testOpt("\"a\"b", Arrays.asList("ab")); testOpt("\"a\"\"b\"", Arrays.asList("ab")); testOpt("''", Arrays.asList("")); testOpt("\"\"", Arrays.asList("")); } @Test public void testInvalidOptionStrings() { testInvalidOpt("\\"); testInvalidOpt("\"abcde"); testInvalidOpt("'abcde"); } @Test public void testRedactCommandLineArgs() { assertEquals(redact("secret"), "secret"); assertEquals(redact("-Dk=v"), "-Dk=v"); assertEquals(redact("-Dk=secret"), "-Dk=secret"); assertEquals(redact("-DsecretKey=my-secret"), "-DsecretKey=*********(redacted)"); assertEquals(redactCommandLineArgs(Arrays.asList("-DsecretKey=my-secret")), Arrays.asList("-DsecretKey=*********(redacted)")); } @Test public void testWindowsBatchQuoting() { assertEquals("abc", quoteForBatchScript("abc")); assertEquals("\"a b c\"", quoteForBatchScript("a b c")); assertEquals("\"a \"\"b\"\" c\"", quoteForBatchScript("a \"b\" c")); assertEquals("\"a\"\"b\"\"c\"", quoteForBatchScript("a\"b\"c")); assertEquals("\"ab=\"\"cd\"\"\"", quoteForBatchScript("ab=\"cd\"")); assertEquals("\"a,b,c\"", quoteForBatchScript("a,b,c")); assertEquals("\"a;b;c\"", quoteForBatchScript("a;b;c")); assertEquals("\"a,b,c\\\\\"", quoteForBatchScript("a,b,c\\")); } @Test public void testPythonArgQuoting() { assertEquals("\"abc\"", quoteForCommandString("abc")); assertEquals("\"a b c\"", quoteForCommandString("a b c")); assertEquals("\"a \\\"b\\\" c\"", quoteForCommandString("a \"b\" c")); } @Test public void testJavaMajorVersion() { assertEquals(6, javaMajorVersion("1.6.0_50")); assertEquals(7, javaMajorVersion("1.7.0_79")); assertEquals(8, javaMajorVersion("1.8.0_66")); assertEquals(9, javaMajorVersion("9-ea")); assertEquals(9, javaMajorVersion("9+100")); assertEquals(9, javaMajorVersion("9")); assertEquals(9, javaMajorVersion("9.1.0")); assertEquals(10, javaMajorVersion("10")); } private static void testOpt(String opts, List<String> expected) { assertEquals(expected, parseOptionString(opts), String.format("test string failed to parse: [[ %s ]]", opts)); } private static void testInvalidOpt(String opts) { assertThrows(IllegalArgumentException.class, () -> parseOptionString(opts)); } }
CommandBuilderUtilsSuite
java
quarkusio__quarkus
integration-tests/grpc-interceptors/src/main/java/io/quarkus/grpc/examples/interceptors/CopycatService.java
{ "start": 262, "end": 868 }
class ____ extends MutinyCopycatGrpc.CopycatImplBase { private HelloReply getReply(HelloRequest request) { String name = request.getName(); if (name.equals("Fail")) { throw new HelloException(name); } return HelloReply.newBuilder().setMessage("Hello " + name).build(); } @Override public Uni<HelloReply> sayCat(HelloRequest request) { return Uni.createFrom().item(getReply(request)); } @Override public Multi<HelloReply> multiCat(Multi<HelloRequest> request) { return request.map(this::getReply); } }
CopycatService
java
apache__rocketmq
example/src/main/java/org/apache/rocketmq/example/simple/LitePullConsumerSubscribe.java
{ "start": 1061, "end": 1760 }
class ____ { public static volatile boolean running = true; public static void main(String[] args) throws Exception { DefaultLitePullConsumer litePullConsumer = new DefaultLitePullConsumer("lite_pull_consumer_test"); litePullConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); litePullConsumer.subscribe("TopicTest", "*"); litePullConsumer.start(); try { while (running) { List<MessageExt> messageExts = litePullConsumer.poll(); System.out.printf("%s%n", messageExts); } } finally { litePullConsumer.shutdown(); } } }
LitePullConsumerSubscribe
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/TransportStopDatafeedAction.java
{ "start": 3183, "end": 28917 }
class ____ extends TransportTasksAction< TransportStartDatafeedAction.DatafeedTask, StopDatafeedAction.Request, StopDatafeedAction.Response, StopDatafeedAction.Response> { private static final int MAX_ATTEMPTS = 10; private static final Logger logger = LogManager.getLogger(TransportStopDatafeedAction.class); private final ThreadPool threadPool; private final PersistentTasksService persistentTasksService; private final DatafeedConfigProvider datafeedConfigProvider; private final AnomalyDetectionAuditor auditor; private final OriginSettingClient client; @Inject public TransportStopDatafeedAction( TransportService transportService, ThreadPool threadPool, ActionFilters actionFilters, ClusterService clusterService, PersistentTasksService persistentTasksService, DatafeedConfigProvider datafeedConfigProvider, AnomalyDetectionAuditor auditor, Client client ) { super( StopDatafeedAction.NAME, clusterService, transportService, actionFilters, StopDatafeedAction.Request::new, StopDatafeedAction.Response::new, threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME) ); this.threadPool = Objects.requireNonNull(threadPool); this.persistentTasksService = Objects.requireNonNull(persistentTasksService); this.datafeedConfigProvider = Objects.requireNonNull(datafeedConfigProvider); this.auditor = Objects.requireNonNull(auditor); this.client = new OriginSettingClient(client, ML_ORIGIN); } /** * Sort the datafeed IDs the their task state and add to one * of the list arguments depending on the state. * * @param expandedDatafeedIds The expanded set of IDs * @param tasks Persistent task meta data * @param startedDatafeedIds Started datafeed ids are added to this list * @param stoppingDatafeedIds Stopping datafeed ids are added to this list * @param notStoppedDatafeedIds Datafeed ids are added to this list for all datafeeds that are not stopped */ static void sortDatafeedIdsByTaskState( Collection<String> expandedDatafeedIds, PersistentTasksCustomMetadata tasks, List<String> startedDatafeedIds, List<String> stoppingDatafeedIds, List<String> notStoppedDatafeedIds ) { for (String expandedDatafeedId : expandedDatafeedIds) { addDatafeedTaskIdAccordingToState( expandedDatafeedId, MlTasks.getDatafeedState(expandedDatafeedId, tasks), startedDatafeedIds, stoppingDatafeedIds, notStoppedDatafeedIds ); } } private static void addDatafeedTaskIdAccordingToState( String datafeedId, DatafeedState datafeedState, List<String> startedDatafeedIds, List<String> stoppingDatafeedIds, List<String> notStoppedDatafeedIds ) { switch (datafeedState) { // Treat STARTING like STARTED for stop API behaviour. case STARTING: case STARTED: startedDatafeedIds.add(datafeedId); notStoppedDatafeedIds.add(datafeedId); break; case STOPPED: break; case STOPPING: stoppingDatafeedIds.add(datafeedId); notStoppedDatafeedIds.add(datafeedId); break; default: assert false : "Unexpected datafeed state " + datafeedState; break; } } @Override protected void doExecute(Task task, StopDatafeedAction.Request request, ActionListener<StopDatafeedAction.Response> listener) { doExecute(task, request, listener, 1); } private void doExecute( Task task, StopDatafeedAction.Request request, ActionListener<StopDatafeedAction.Response> listener, int attempt ) { final ClusterState state = clusterService.state(); final DiscoveryNodes nodes = state.nodes(); if (nodes.isLocalNodeElectedMaster() == false) { // Delegates stop datafeed to elected master node, so it becomes the coordinating node. // See comment in TransportStartDatafeedAction for more information. if (nodes.getMasterNode() == null) { listener.onFailure(new MasterNotDiscoveredException()); } else { transportService.sendRequest( nodes.getMasterNode(), actionName, request, new ActionListenerResponseHandler<>( listener, StopDatafeedAction.Response::new, TransportResponseHandler.TRANSPORT_WORKER ) ); } } else { PersistentTasksCustomMetadata tasks = PersistentTasksCustomMetadata.get(state.metadata().getDefaultProject()); datafeedConfigProvider.expandDatafeedIds( request.getDatafeedId(), request.allowNoMatch(), tasks, request.isForce(), null, ActionListener.wrap(expandedIds -> { List<String> startedDatafeeds = new ArrayList<>(); List<String> stoppingDatafeeds = new ArrayList<>(); List<String> notStoppedDatafeeds = new ArrayList<>(); sortDatafeedIdsByTaskState(expandedIds, tasks, startedDatafeeds, stoppingDatafeeds, notStoppedDatafeeds); if (startedDatafeeds.isEmpty() && stoppingDatafeeds.isEmpty()) { listener.onResponse(new StopDatafeedAction.Response(true)); return; } if (request.isForce()) { forceStopDatafeed(request, listener, tasks, nodes, notStoppedDatafeeds); } else { normalStopDatafeed(task, request, listener, tasks, nodes, startedDatafeeds, stoppingDatafeeds, attempt); } }, listener::onFailure) ); } } private void normalStopDatafeed( Task task, StopDatafeedAction.Request request, ActionListener<StopDatafeedAction.Response> listener, PersistentTasksCustomMetadata tasks, DiscoveryNodes nodes, List<String> startedDatafeeds, List<String> stoppingDatafeeds, int attempt ) { final Set<String> executorNodes = new HashSet<>(); final List<String> startedDatafeedsJobs = new ArrayList<>(); final List<String> resolvedStartedDatafeeds = new ArrayList<>(); final List<PersistentTasksCustomMetadata.PersistentTask<?>> allDataFeedsToWaitFor = new ArrayList<>(); for (String datafeedId : startedDatafeeds) { PersistentTasksCustomMetadata.PersistentTask<?> datafeedTask = MlTasks.getDatafeedTask(datafeedId, tasks); if (datafeedTask == null) { // This should not happen, because startedDatafeeds was derived from the same tasks that is passed to this method String msg = "Requested datafeed [" + datafeedId + "] be stopped, but datafeed's task could not be found."; assert datafeedTask != null : msg; logger.error(msg); } else if (PersistentTasksClusterService.needsReassignment(datafeedTask.getAssignment(), nodes) == false) { startedDatafeedsJobs.add(((StartDatafeedAction.DatafeedParams) datafeedTask.getParams()).getJobId()); resolvedStartedDatafeeds.add(datafeedId); executorNodes.add(datafeedTask.getExecutorNode()); allDataFeedsToWaitFor.add(datafeedTask); } else { // This is the easy case - the datafeed is not currently assigned to a valid node, // so can be gracefully stopped simply by removing its persistent task. (Usually // a graceful stop cannot be achieved by simply removing the persistent task, but // if the datafeed has no running code then graceful/forceful are the same.) // The listener here doesn't need to call the final listener, as waitForDatafeedStopped() // already waits for these persistent tasks to disappear. persistentTasksService.sendRemoveRequest( datafeedTask.getId(), MachineLearning.HARD_CODED_MACHINE_LEARNING_MASTER_NODE_TIMEOUT, ActionListener.wrap( r -> auditDatafeedStopped(datafeedTask), e -> logger.error("[" + datafeedId + "] failed to remove task to stop unassigned datafeed", e) ) ); allDataFeedsToWaitFor.add(datafeedTask); } } for (String datafeedId : stoppingDatafeeds) { PersistentTasksCustomMetadata.PersistentTask<?> datafeedTask = MlTasks.getDatafeedTask(datafeedId, tasks); assert datafeedTask != null : "Requested datafeed [" + datafeedId + "] be stopped, but datafeed's task could not be found."; allDataFeedsToWaitFor.add(datafeedTask); } request.setResolvedStartedDatafeedIds(resolvedStartedDatafeeds.toArray(new String[0])); request.setNodes(executorNodes.toArray(new String[0])); final Set<String> movedDatafeeds = ConcurrentCollections.newConcurrentSet(); ActionListener<StopDatafeedAction.Response> finalListener = ActionListener.wrap( response -> waitForDatafeedStopped(allDataFeedsToWaitFor, request, response, ActionListener.wrap(finished -> { for (String datafeedId : movedDatafeeds) { PersistentTasksCustomMetadata.PersistentTask<?> datafeedTask = MlTasks.getDatafeedTask(datafeedId, tasks); persistentTasksService.sendRemoveRequest( datafeedTask.getId(), MachineLearning.HARD_CODED_MACHINE_LEARNING_MASTER_NODE_TIMEOUT, ActionListener.wrap(r -> auditDatafeedStopped(datafeedTask), e -> { if (ExceptionsHelper.unwrapCause(e) instanceof ResourceNotFoundException) { logger.debug("[{}] relocated datafeed task already removed", datafeedId); } else { logger.error("[" + datafeedId + "] failed to remove task to stop relocated datafeed", e); } }) ); } if (startedDatafeedsJobs.isEmpty()) { listener.onResponse(finished); return; } client.admin() .indices() .prepareRefresh(startedDatafeedsJobs.stream().map(AnomalyDetectorsIndex::jobResultsAliasedName).toArray(String[]::new)) .execute(ActionListener.wrap(_unused -> listener.onResponse(finished), ex -> { logger.warn( () -> format( "failed to refresh job [%s] results indices when stopping datafeeds [%s]", startedDatafeedsJobs, startedDatafeeds ), ex ); listener.onResponse(finished); })); }, listener::onFailure), movedDatafeeds), e -> { Throwable unwrapped = ExceptionsHelper.unwrapCause(e); if (unwrapped instanceof FailedNodeException) { // A node has dropped out of the cluster since we started executing the requests. // Since stopping an already stopped datafeed is not an error we can try again. // The datafeeds that were running on the node that dropped out of the cluster // will just have their persistent tasks cancelled. Datafeeds that were stopped // by the previous attempt will be noops in the subsequent attempt. if (attempt <= MAX_ATTEMPTS) { logger.warn( "Node [{}] failed while processing stop datafeed request - retrying", ((FailedNodeException) unwrapped).nodeId() ); doExecute(task, request, listener, attempt + 1); } else { listener.onFailure(e); } } else if (unwrapped instanceof RetryStopDatafeedException) { // This is for the case where a local task wasn't yet running at the moment a // request to stop it arrived at its node. This can happen when the cluster // state says a persistent task should be running on a particular node but that // node hasn't yet had time to start the corresponding local task. if (attempt <= MAX_ATTEMPTS) { logger.info( "Insufficient responses while processing stop datafeed request [{}] - retrying", unwrapped.getMessage() ); // Unlike the failed node case above, in this case we should wait a little // before retrying because we need to allow time for the local task to // start on the node it's supposed to be running on. threadPool.schedule( () -> doExecute(task, request, listener, attempt + 1), TimeValue.timeValueMillis(100L * attempt), EsExecutors.DIRECT_EXECUTOR_SERVICE ); } else { listener.onFailure( ExceptionsHelper.serverError( "Failed to stop datafeed [" + request.getDatafeedId() + "] after " + MAX_ATTEMPTS + " due to inconsistencies between local and persistent tasks within the cluster" ) ); } } else { listener.onFailure(e); } } ); super.doExecute(task, request, finalListener); } private void auditDatafeedStopped(PersistentTasksCustomMetadata.PersistentTask<?> datafeedTask) { @SuppressWarnings("unchecked") String jobId = ((PersistentTasksCustomMetadata.PersistentTask<StartDatafeedAction.DatafeedParams>) datafeedTask).getParams() .getJobId(); auditor.info(jobId, Messages.getMessage(Messages.JOB_AUDIT_DATAFEED_STOPPED)); } private void forceStopDatafeed( final StopDatafeedAction.Request request, final ActionListener<StopDatafeedAction.Response> listener, PersistentTasksCustomMetadata tasks, DiscoveryNodes nodes, final List<String> notStoppedDatafeeds ) { final AtomicInteger counter = new AtomicInteger(); final AtomicArray<Exception> failures = new AtomicArray<>(notStoppedDatafeeds.size()); for (String datafeedId : notStoppedDatafeeds) { PersistentTasksCustomMetadata.PersistentTask<?> datafeedTask = MlTasks.getDatafeedTask(datafeedId, tasks); if (datafeedTask != null) { persistentTasksService.sendRemoveRequest( datafeedTask.getId(), MachineLearning.HARD_CODED_MACHINE_LEARNING_MASTER_NODE_TIMEOUT, ActionListener.wrap(persistentTask -> { // For force stop, only audit here if the datafeed was unassigned at the time of the stop, hence inactive. // If the datafeed was active then it audits itself on being cancelled. if (PersistentTasksClusterService.needsReassignment(datafeedTask.getAssignment(), nodes)) { auditDatafeedStopped(datafeedTask); } if (counter.incrementAndGet() == notStoppedDatafeeds.size()) { sendResponseOrFailure(request.getDatafeedId(), listener, failures); } }, e -> { final int slot = counter.incrementAndGet(); // We validated that the datafeed names supplied in the request existed when we started processing the action. // If the related tasks don't exist at this point then they must have been stopped by a simultaneous stop // request. // This is not an error. if (ExceptionsHelper.unwrapCause(e) instanceof ResourceNotFoundException == false) { failures.set(slot - 1, e); } if (slot == notStoppedDatafeeds.size()) { sendResponseOrFailure(request.getDatafeedId(), listener, failures); } }) ); } else { // This should not happen, because startedDatafeeds and stoppingDatafeeds // were derived from the same tasks that were passed to this method String msg = "Requested datafeed [" + datafeedId + "] be force-stopped, but datafeed's task could not be found."; assert datafeedTask != null : msg; logger.error(msg); final int slot = counter.incrementAndGet(); failures.set(slot - 1, new RuntimeException(msg)); if (slot == notStoppedDatafeeds.size()) { sendResponseOrFailure(request.getDatafeedId(), listener, failures); } } } } @Override protected void taskOperation( CancellableTask actionTask, StopDatafeedAction.Request request, TransportStartDatafeedAction.DatafeedTask datafeedTask, ActionListener<StopDatafeedAction.Response> listener ) { DatafeedState taskState = DatafeedState.STOPPING; datafeedTask.updatePersistentTaskState(taskState, ActionListener.wrap(task -> { // we need to fork because we are now on a network threadpool threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME).execute(new AbstractRunnable() { @Override public void onFailure(Exception e) { // We validated that the datafeed names supplied in the request existed when we started processing the action. // If the related task for one of them doesn't exist at this point then it must have been removed by a // simultaneous force stop request. This is not an error. if (ExceptionsHelper.unwrapCause(e) instanceof ResourceNotFoundException) { listener.onResponse(new StopDatafeedAction.Response(true)); } else { listener.onFailure(e); } } @Override protected void doRun() { datafeedTask.stop("stop_datafeed (api)", request.getStopTimeout()); listener.onResponse(new StopDatafeedAction.Response(true)); } }); }, e -> { if (ExceptionsHelper.unwrapCause(e) instanceof ResourceNotFoundException) { // the task has disappeared so must have stopped listener.onResponse(new StopDatafeedAction.Response(true)); } else { listener.onFailure(e); } })); } private static void sendResponseOrFailure( String datafeedId, ActionListener<StopDatafeedAction.Response> listener, AtomicArray<Exception> failures ) { List<Exception> caughtExceptions = failures.asList(); if (caughtExceptions.isEmpty()) { listener.onResponse(new StopDatafeedAction.Response(true)); return; } String msg = "Failed to stop datafeed [" + datafeedId + "] with [" + caughtExceptions.size() + "] failures, rethrowing first. All Exceptions: [" + caughtExceptions.stream().map(Exception::getMessage).collect(Collectors.joining(", ")) + "]"; ElasticsearchStatusException e = exceptionArrayToStatusException(failures, msg); listener.onFailure(e); } /** * Wait for datafeed to be marked as stopped in cluster state, which means the datafeed persistent task has been removed. * This api returns when task has been cancelled, but that doesn't mean the persistent task has been removed from cluster state, * so wait for that to happen here. * * Since the stop datafeed action consists of a chain of async callbacks, it's possible that datafeeds have moved nodes since we * decided what to do with them at the beginning of the chain. We cannot simply wait for these, as the request to stop them will * have been sent to the wrong node and ignored there, so we'll just spin until the timeout expires. */ void waitForDatafeedStopped( List<PersistentTasksCustomMetadata.PersistentTask<?>> datafeedPersistentTasks, StopDatafeedAction.Request request, StopDatafeedAction.Response response, ActionListener<StopDatafeedAction.Response> listener, Set<String> movedDatafeeds ) { @FixForMultiProject final var projectId = Metadata.DEFAULT_PROJECT_ID; persistentTasksService.waitForPersistentTasksCondition(projectId, persistentTasksCustomMetadata -> { if (persistentTasksCustomMetadata == null) { return true; } for (PersistentTasksCustomMetadata.PersistentTask<?> originalPersistentTask : datafeedPersistentTasks) { String originalPersistentTaskId = originalPersistentTask.getId(); PersistentTasksCustomMetadata.PersistentTask<?> currentPersistentTask = persistentTasksCustomMetadata.getTask( originalPersistentTaskId ); if (currentPersistentTask != null) { if (Objects.equals(originalPersistentTask.getExecutorNode(), currentPersistentTask.getExecutorNode()) && originalPersistentTask.getAllocationId() == currentPersistentTask.getAllocationId()) { return false; } StartDatafeedAction.DatafeedParams params = (StartDatafeedAction.DatafeedParams) originalPersistentTask.getParams(); if (movedDatafeeds.add(params.getDatafeedId())) { logger.info("Datafeed [{}] changed assignment while waiting for it to be stopped", params.getDatafeedId()); } } } return true; }, request.getTimeout(), listener.safeMap(result -> response)); } @Override protected StopDatafeedAction.Response newResponse( StopDatafeedAction.Request request, List<StopDatafeedAction.Response> tasks, List<TaskOperationFailure> taskOperationFailures, List<FailedNodeException> failedNodeExceptions ) { // number of resolved (i.e. running on a node) started data feeds should be equal to the number of // tasks, otherwise something went wrong if (request.getResolvedStartedDatafeedIds().length != tasks.size()) { if (taskOperationFailures.isEmpty() == false) { throw ExceptionsHelper.taskOperationFailureToStatusException(taskOperationFailures.get(0)); } else if (failedNodeExceptions.isEmpty() == false) { throw failedNodeExceptions.get(0); } else { // This can happen when the local task in the node no longer exists, // which means the datafeed(s) have already been stopped. It can // also happen if the local task hadn't yet been created when the // stop request hit the executor node. In this second case we need // to retry, otherwise the wait for completion will wait until it // times out. We cannot tell which case it is, but it doesn't hurt // to retry in both cases since stopping a stopped datafeed is a // no-op. throw new RetryStopDatafeedException(request.getResolvedStartedDatafeedIds().length, tasks.size()); } } return new StopDatafeedAction.Response(tasks.stream().allMatch(StopDatafeedAction.Response::isStopped)); } /** * A special exception to indicate that we should retry stopping the datafeeds. * This exception is not transportable, so should only be thrown in situations * where it will be caught on the same node. */ static
TransportStopDatafeedAction
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/certReload/MainHttpServerTlsPKCS12CertificateReloadWithTlsRegistryAndUpdateEventTest.java
{ "start": 1750, "end": 6327 }
class ____ { @TestHTTPResource(value = "/hello", ssl = true) URL url; public static final File temp = new File("target/test-certificates-" + UUID.randomUUID()); @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar.addClasses(MyBean.class)) .overrideConfigKey("quarkus.http.insecure-requests", "redirect") .overrideConfigKey("quarkus.http.tls-configuration-name", "http") .overrideConfigKey("quarkus.tls.http.key-store.p12.path", temp.getAbsolutePath() + "/tls.p12") .overrideConfigKey("quarkus.tls.http.key-store.p12.password", "password") .overrideConfigKey("loc", temp.getAbsolutePath()) .setBeforeAllCustomizer(() -> { try { // Prepare a random directory to store the certificates. temp.mkdirs(); Files.copy(new File("target/certificates/reload-A-keystore.p12").toPath(), new File(temp, "/tls.p12").toPath()); } catch (Exception e) { throw new RuntimeException(e); } }) .setAfterAllCustomizer(() -> { try { Files.deleteIfExists(new File(temp, "/tls.p12").toPath()); Files.deleteIfExists(temp.toPath()); } catch (Exception e) { throw new RuntimeException(e); } }); @Inject Vertx vertx; @ConfigProperty(name = "loc") File certs; @Inject TlsConfigurationRegistry registry; @Inject Event<CertificateUpdatedEvent> event; @Test void test() throws IOException, ExecutionException, InterruptedException, TimeoutException { var options = new HttpClientOptions() .setSsl(true) .setDefaultPort(url.getPort()) .setDefaultHost(url.getHost()) .setTrustOptions( new PfxOptions().setPath("target/certificates/reload-A-truststore.p12").setPassword("password")); String response1 = vertx.createHttpClient(options) .request(HttpMethod.GET, "/hello") .flatMap(HttpClientRequest::send) .flatMap(HttpClientResponse::body) .map(Buffer::toString) .toCompletionStage().toCompletableFuture().join(); // Update certs Files.copy(new File("target/certificates/reload-B-keystore.p12").toPath(), new File(certs, "/tls.p12").toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING); // Trigger the reload registry.get("http").orElseThrow().reload(); event.fire(new CertificateUpdatedEvent("http", registry.get("http").orElseThrow())); // The client truststore is not updated, thus it should fail. assertThatThrownBy(() -> vertx.createHttpClient(options) .request(HttpMethod.GET, "/hello") .flatMap(HttpClientRequest::send) .flatMap(HttpClientResponse::body) .map(Buffer::toString) .toCompletionStage().toCompletableFuture().join()).hasCauseInstanceOf(SSLHandshakeException.class); var options2 = new HttpClientOptions(options) .setTrustOptions( new PfxOptions().setPath("target/certificates/reload-B-truststore.p12").setPassword("password")); var response2 = vertx.createHttpClient(options2) .request(HttpMethod.GET, "/hello") .flatMap(HttpClientRequest::send) .flatMap(HttpClientResponse::body) .map(Buffer::toString) .toCompletionStage().toCompletableFuture().join(); assertThat(response1).isNotEqualTo(response2); // Because cert duration are different. // Trigger another reload registry.get("http").orElseThrow().reload(); event.fire(new CertificateUpdatedEvent("http", registry.get("http").orElseThrow())); var response3 = vertx.createHttpClient(options2) .request(HttpMethod.GET, "/hello") .flatMap(HttpClientRequest::send) .flatMap(HttpClientResponse::body) .map(Buffer::toString) .toCompletionStage().toCompletableFuture().join(); assertThat(response2).isEqualTo(response3); } public static
MainHttpServerTlsPKCS12CertificateReloadWithTlsRegistryAndUpdateEventTest
java
quarkusio__quarkus
independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/runner/JarResource.java
{ "start": 7862, "end": 7939 }
class ____ of this extremely specific purpose. */ private static
outside
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/supersql/ast/SuperSqlObject.java
{ "start": 231, "end": 508 }
interface ____ extends SQLObject { void accept0(SuperSqlASTVisitor visitor); @Override default void accept(SQLASTVisitor visitor) { if (visitor instanceof SuperSqlASTVisitor) { accept0((SuperSqlASTVisitor) visitor); } } }
SuperSqlObject
java
spring-projects__spring-boot
module/spring-boot-jdbc/src/dockerTest/java/org/springframework/boot/jdbc/testcontainers/JdbcContainerConnectionDetailsFactoryTests.java
{ "start": 1879, "end": 2650 }
class ____ { @Container @ServiceConnection static final PostgreSQLContainer postgres = TestImage.container(PostgreSQLContainer.class); @Autowired(required = false) private JdbcConnectionDetails connectionDetails; @Autowired private DataSource dataSource; @Test void connectionCanBeMadeToJdbcContainer() { assertThat(this.connectionDetails).isNotNull(); JdbcTemplate jdbc = new JdbcTemplate(this.dataSource); String validationQuery = DatabaseDriver.POSTGRESQL.getValidationQuery(); assertThat(validationQuery).isNotNull(); assertThatNoException().isThrownBy(() -> jdbc.execute(validationQuery)); } @Configuration(proxyBeanMethods = false) @ImportAutoConfiguration(DataSourceAutoConfiguration.class) static
JdbcContainerConnectionDetailsFactoryTests
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/ITestS3AStorageClass.java
{ "start": 8699, "end": 8786 }
class ____ object %s", path) .isEqualToIgnoringCase(expectedStorageClass); } }
of
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
{ "start": 514, "end": 3474 }
class ____ implements ClassCreatingMockMaker, InlineMockMaker, Instantiator { private final InlineDelegateByteBuddyMockMaker inlineDelegateByteBuddyMockMaker; public InlineByteBuddyMockMaker() { try { inlineDelegateByteBuddyMockMaker = new InlineDelegateByteBuddyMockMaker(); } catch (NoClassDefFoundError e) { Reporter.missingByteBuddyDependency(e); throw e; } } InlineByteBuddyMockMaker(InlineDelegateByteBuddyMockMaker inlineDelegateByteBuddyMockMaker) { this.inlineDelegateByteBuddyMockMaker = inlineDelegateByteBuddyMockMaker; } @Override public <T> T newInstance(Class<T> cls) { return inlineDelegateByteBuddyMockMaker.newInstance(cls); } @Override public <T> Class<? extends T> createMockType(MockCreationSettings<T> settings) { return inlineDelegateByteBuddyMockMaker.createMockType(settings); } @Override public void clearMock(Object mock) { inlineDelegateByteBuddyMockMaker.clearMock(mock); } @Override public void clearAllMocks() { inlineDelegateByteBuddyMockMaker.clearAllMocks(); } @Override public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) { return inlineDelegateByteBuddyMockMaker.createMock(settings, handler); } @Override public <T> Optional<T> createSpy( MockCreationSettings<T> settings, MockHandler handler, T instance) { return inlineDelegateByteBuddyMockMaker.createSpy(settings, handler, instance); } @Override public MockHandler getHandler(Object mock) { return inlineDelegateByteBuddyMockMaker.getHandler(mock); } @Override public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) { inlineDelegateByteBuddyMockMaker.resetMock(mock, newHandler, settings); } @Override public TypeMockability isTypeMockable(Class<?> type) { return inlineDelegateByteBuddyMockMaker.isTypeMockable(type); } @Override public <T> StaticMockControl<T> createStaticMock( Class<T> type, MockCreationSettings<T> settings, MockHandler handler) { return inlineDelegateByteBuddyMockMaker.createStaticMock(type, settings, handler); } @Override public <T> ConstructionMockControl<T> createConstructionMock( Class<T> type, Function<MockedConstruction.Context, MockCreationSettings<T>> settingsFactory, Function<MockedConstruction.Context, MockHandler<T>> handlerFactory, MockedConstruction.MockInitializer<T> mockInitializer) { return inlineDelegateByteBuddyMockMaker.createConstructionMock( type, settingsFactory, handlerFactory, mockInitializer); } @Override public void clearAllCaches() { inlineDelegateByteBuddyMockMaker.clearAllCaches(); } }
InlineByteBuddyMockMaker
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo2.java
{ "start": 245, "end": 623 }
class ____ extends TestCase { protected void setUp() throws Exception { ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_dubbo2"); } public void test_emptyHashMap() throws Exception { VO vo = new VO(); vo.setValue(new HashMap()); String text = JSON.toJSONString(vo, SerializerFeature.WriteClassName); JSON.parse(text); } public static
Bug_for_dubbo2
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/OnDeleteCascadeToElementCollectionTest.java
{ "start": 6485, "end": 6778 }
class ____ { @Id @GeneratedValue public Long id; @ElementCollection @OnDelete(action = OnDeleteAction.CASCADE) public Set<String> labels; @ElementCollection @OnDelete(action = OnDeleteAction.CASCADE) public Map<String, Ticket> tickets; } @Embeddable public static
Cascading
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/style/ToStringCreator.java
{ "start": 766, "end": 1038 }
class ____ builds pretty-printing {@code toString()} methods * with pluggable styling conventions. By default, ToStringCreator adheres * to Spring's {@code toString()} styling conventions. * * @author Keith Donald * @author Juergen Hoeller * @since 1.2.2 */ public
that
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/support/Validation.java
{ "start": 7409, "end": 7649 }
class ____ { private final String message; private Error(String message) { this.message = message; } @Override public String toString() { return message; } } }
Error
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/ApprovalManualIT.java
{ "start": 1693, "end": 5086 }
class ____ extends AbstractApprovalManualIT { @Parameter private String format; public ApprovalManualIT() { super(5); } @Test public void shouldSubmitAndFetchApprovals() { final ApprovalResult approvalResult = template.requestBody(String.format("salesforce:approval?"// + "format=%s"// + "&approvalActionType=Submit"// + "&approvalContextId=%s"// + "&approvalNextApproverIds=%s"// + "&approvalComments=Integration test"// + "&approvalProcessDefinitionNameOrId=Test_Account_Process", format, accountIds.get(0), userId), NOT_USED, ApprovalResult.class); assertNotNull(approvalResult, "Approval should have resulted in value"); assertEquals(1, approvalResult.size(), "There should be one Account waiting approval"); assertEquals("Pending", approvalResult.iterator().next().getInstanceStatus(), "Instance status of the item in approval result should be `Pending`"); // as it stands on 18.11.2016. the GET method on // /vXX.X/process/approvals/ with Accept other than // `application/json` results in HTTP status 500, so only JSON is // supported final Approvals approvals = template.requestBody("salesforce:approvals", NOT_USED, Approvals.class); assertNotNull(approvals, "Approvals should be fetched"); final List<Info> accountApprovals = approvals.approvalsFor("Account"); assertEquals(1, accountApprovals.size(), "There should be one Account waiting approval"); } @Test public void shouldSubmitBulkApprovals() { final List<ApprovalRequest> approvalRequests = accountIds.stream().map(id -> { final ApprovalRequest request = new ApprovalRequest(); request.setContextId(id); request.setComments("Approval for " + id); request.setActionType(Action.Submit); return request; }).collect(Collectors.toList()); final ApprovalResult approvalResult = template.requestBody(String.format("salesforce:approval?"// + "format=%s"// + "&approvalActionType=Submit"// + "&approvalNextApproverIds=%s"// + "&approvalProcessDefinitionNameOrId=Test_Account_Process", format, userId), approvalRequests, ApprovalResult.class); assertEquals(approvalRequests.size(), approvalResult.size(), "Should have same number of approval results as requests"); } @Parameters public static Iterable<String> formats() { return Arrays.asList("JSON", "XML"); } }
ApprovalManualIT
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/filter/LevelRangeFilter.java
{ "start": 2526, "end": 9352 }
class ____ extends AbstractFilter { /** * The default minimum level threshold. */ public static final Level DEFAULT_MIN_LEVEL = Level.OFF; /** * THe default maximum level threshold. */ public static final Level DEFAULT_MAX_LEVEL = Level.ALL; /** * The default result on a match. */ public static final Result DEFAULT_ON_MATCH = Result.NEUTRAL; /** * The default result on a mismatch. */ public static final Result DEFAULT_ON_MISMATCH = Result.DENY; /** * Creates an instance with the provided properties. * * @param minLevel the minimum level threshold * @param maxLevel the maximum level threshold * @param onMatch the result to return on a match * @param onMismatch the result to return on a mismatch * @return a new instance */ @PluginFactory public static LevelRangeFilter createFilter( // @formatter:off @PluginAttribute("minLevel") final Level minLevel, @PluginAttribute("maxLevel") final Level maxLevel, @PluginAttribute("onMatch") final Result onMatch, @PluginAttribute("onMismatch") final Result onMismatch) { // @formatter:on final Level effectiveMinLevel = minLevel == null ? DEFAULT_MIN_LEVEL : minLevel; final Level effectiveMaxLevel = maxLevel == null ? DEFAULT_MAX_LEVEL : maxLevel; final Result effectiveOnMatch = onMatch == null ? DEFAULT_ON_MATCH : onMatch; final Result effectiveOnMismatch = onMismatch == null ? DEFAULT_ON_MISMATCH : onMismatch; return new LevelRangeFilter(effectiveMinLevel, effectiveMaxLevel, effectiveOnMatch, effectiveOnMismatch); } private final Level maxLevel; private final Level minLevel; private LevelRangeFilter( final Level minLevel, final Level maxLevel, final Result onMatch, final Result onMismatch) { super(onMatch, onMismatch); this.minLevel = minLevel; this.maxLevel = maxLevel; } private Result filter(final Level level) { return level.isInRange(minLevel, maxLevel) ? onMatch : onMismatch; } @Override public Result filter(final LogEvent event) { return filter(event.getLevel()); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final Message msg, final Throwable t) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final Object msg, final Throwable t) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object... params) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6, final Object p7) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6, final Object p7, final Object p8) { return filter(level); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6, final Object p7, final Object p8, final Object p9) { return filter(level); } /** * @return the minimum level threshold */ public Level getMinLevel() { return minLevel; } /** * @return the maximum level threshold */ public Level getMaxLevel() { return maxLevel; } @Override public String toString() { return String.format("[%s,%s]", minLevel, maxLevel); } }
LevelRangeFilter
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/sort/BinaryExternalSorter.java
{ "start": 3225, "end": 14153 }
class ____ implements Sorter<BinaryRowData> { // ------------------------------------------------------------------------ // Constants // ------------------------------------------------------------------------ /** The minimum number of segments that are required for the sort to operate. */ private static final int MIN_NUM_SORT_MEM_SEGMENTS = 10; private static final long SORTER_MIN_NUM_SORT_MEM = MIN_NUM_SORT_MEM_SEGMENTS * MemoryManager.DEFAULT_PAGE_SIZE; /** Logging. */ private static final Logger LOG = LoggerFactory.getLogger(BinaryExternalSorter.class); // ------------------------------------------------------------------------ // Threads // ------------------------------------------------------------------------ /** The currWriteBuffer that is passed as marker for the end of data. */ private static final CircularElement EOF_MARKER = new CircularElement(); /** The currWriteBuffer that is passed as marker for signaling the beginning of spilling. */ private static final CircularElement SPILLING_MARKER = new CircularElement(); /** The ChannelWithMeta that is passed as marker for signaling the final merge. */ private static final ChannelWithMeta FINAL_MERGE_MARKER = new ChannelWithMeta(null, -1, -1); // ------------------------------------------------------------------------ // Memory // ------------------------------------------------------------------------ /** * The memory segments used first for sorting and later for reading/pre-fetching during the * external merge. */ private final List<LazyMemorySegmentPool> sortReadMemory; /** Records all sort buffer. */ private final List<BinaryInMemorySortBuffer> sortBuffers; // ------------------------------------------------------------------------ // Miscellaneous Fields // ------------------------------------------------------------------------ /** The monitor which guards the iterator field. */ private final Object iteratorLock = new Object(); /** The thread that merges the buffer handed from the reading thread. */ private ThreadBase sortThread; /** The thread that handles spilling to secondary storage. */ private ThreadBase spillThread; /** The thread that handles merging from the secondary storage. */ private ThreadBase mergeThread; /** Final result iterator. */ private volatile MutableObjectIterator<BinaryRowData> iterator; /** The exception that is set, if the iterator cannot be created. */ private volatile IOException iteratorException; /** Flag indicating that the sorter was closed. */ private volatile boolean closed; /** Sort or spill thread maybe occur some exceptions. */ private ExceptionHandler<IOException> exceptionHandler; /** Queue for the communication between the threads. */ private CircularQueues circularQueues; private long bytesUntilSpilling; private CircularElement currWriteBuffer; private boolean writingDone = false; private final Object writeLock = new Object(); private final SpillChannelManager channelManager; private final BinaryExternalMerger merger; private final int memorySegmentSize; private final boolean compressionEnabled; private final BlockCompressionFactory compressionCodecFactory; private final int compressionBlockSize; private final boolean asyncMergeEnabled; // ------------------------------------------------------------------------ // Constructor & Shutdown // ------------------------------------------------------------------------ private final BinaryRowDataSerializer serializer; // metric private long numSpillFiles; private long spillInBytes; private long spillInCompressedBytes; public BinaryExternalSorter( final Object owner, MemoryManager memoryManager, long reservedMemorySize, IOManager ioManager, AbstractRowDataSerializer<RowData> inputSerializer, BinaryRowDataSerializer serializer, NormalizedKeyComputer normalizedKeyComputer, RecordComparator comparator, int maxNumFileHandles, boolean compressionEnabled, int compressionBlockSize, boolean asyncMergeEnabled) { this( owner, memoryManager, reservedMemorySize, ioManager, inputSerializer, serializer, normalizedKeyComputer, comparator, maxNumFileHandles, compressionEnabled, compressionBlockSize, asyncMergeEnabled, AlgorithmOptions.SORT_SPILLING_THRESHOLD.defaultValue()); } public BinaryExternalSorter( final Object owner, MemoryManager memoryManager, long reservedMemorySize, IOManager ioManager, AbstractRowDataSerializer<RowData> inputSerializer, BinaryRowDataSerializer serializer, NormalizedKeyComputer normalizedKeyComputer, RecordComparator comparator, int maxNumFileHandles, boolean compressionEnabled, int compressionBlockSize, boolean asyncMergeEnabled, float startSpillingFraction) { this.compressionEnabled = compressionEnabled; this.compressionCodecFactory = this.compressionEnabled ? BlockCompressionFactory.createBlockCompressionFactory( CompressionCodec.LZ4) : null; this.compressionBlockSize = compressionBlockSize; this.asyncMergeEnabled = asyncMergeEnabled; checkArgument(maxNumFileHandles >= 2); checkNotNull(ioManager); checkNotNull(normalizedKeyComputer); checkNotNull(memoryManager); this.serializer = (BinaryRowDataSerializer) serializer.duplicate(); this.memorySegmentSize = memoryManager.getPageSize(); if (reservedMemorySize < SORTER_MIN_NUM_SORT_MEM) { throw new IllegalArgumentException( "Too little memory provided to sorter to perform task. " + "Required are at least " + SORTER_MIN_NUM_SORT_MEM + " bytes. Current memory size is " + reservedMemorySize + " bytes."); } // adjust the memory quotas to the page size final int sortMemPages = (int) (reservedMemorySize / memoryManager.getPageSize()); final long sortMemory = ((long) sortMemPages) * memoryManager.getPageSize(); // decide how many sort buffers to use int numSortBuffers = 1; if (reservedMemorySize > 100 * 1024 * 1024L) { numSortBuffers = 2; } final int numSegmentsPerSortBuffer = sortMemPages / numSortBuffers; this.sortReadMemory = new ArrayList<>(); // circular circularQueues pass buffers between the threads final CircularQueues circularQueues = new CircularQueues(); LOG.info( "BinaryExternalSorter with initial memory segments {}, " + "maxNumFileHandles({}), compressionEnable({}), compressionCodecFactory({}), compressionBlockSize({}).", sortMemPages, maxNumFileHandles, compressionEnabled, compressionEnabled ? compressionCodecFactory.getClass() : null, compressionBlockSize); this.sortBuffers = new ArrayList<>(); int totalBuffers = sortMemPages; for (int i = 0; i < numSortBuffers; i++) { // grab some memory int sortSegments = Math.min( i == numSortBuffers - 1 ? Integer.MAX_VALUE : numSegmentsPerSortBuffer, totalBuffers); totalBuffers -= sortSegments; LazyMemorySegmentPool pool = new LazyMemorySegmentPool(owner, memoryManager, sortSegments); this.sortReadMemory.add(pool); final BinaryInMemorySortBuffer buffer = BinaryInMemorySortBuffer.createBuffer( normalizedKeyComputer, inputSerializer, serializer, comparator, pool); // add to empty queue CircularElement element = new CircularElement(i, buffer); circularQueues.empty.add(element); this.sortBuffers.add(buffer); } // exception handling ExceptionHandler<IOException> exceptionHandler = exception -> { // forward exception if (!closed) { setResultIteratorException(exception); close(); } }; // init adding currWriteBuffer this.exceptionHandler = exceptionHandler; this.circularQueues = circularQueues; bytesUntilSpilling = ((long) (startSpillingFraction * sortMemory)); // check if we should directly spill if (bytesUntilSpilling < 1) { bytesUntilSpilling = 0; // add the spilling marker this.circularQueues.sort.add(SPILLING_MARKER); } this.channelManager = new SpillChannelManager(); this.merger = new BinaryExternalMerger( ioManager, memoryManager.getPageSize(), maxNumFileHandles, channelManager, (BinaryRowDataSerializer) serializer.duplicate(), comparator, compressionEnabled, compressionCodecFactory, compressionBlockSize); // start the thread that sorts the buffers this.sortThread = getSortingThread(exceptionHandler, circularQueues); // start the thread that handles spilling to secondary storage this.spillThread = getSpillingThread( exceptionHandler, circularQueues, ioManager, (BinaryRowDataSerializer) serializer.duplicate(), comparator); // start the thread that handles merging from second storage this.mergeThread = getMergingThread(exceptionHandler, circularQueues, maxNumFileHandles, merger); // propagate the context
BinaryExternalSorter
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/conf/TestHAUtil.java
{ "start": 1405, "end": 8852 }
class ____ { private Configuration conf; private static final String RM1_ADDRESS_UNTRIMMED = " \t\t\n 1.2.3.4:8021 \n\t "; private static final String RM1_ADDRESS = RM1_ADDRESS_UNTRIMMED.trim(); private static final String RM2_ADDRESS = "localhost:8022"; private static final String RM3_ADDRESS = "localhost:8033"; private static final String RM1_NODE_ID_UNTRIMMED = "rm1 "; private static final String RM1_NODE_ID = RM1_NODE_ID_UNTRIMMED.trim(); private static final String RM2_NODE_ID = "rm2"; private static final String RM3_NODE_ID = "rm3"; private static final String RM_INVALID_NODE_ID = ".rm"; private static final String RM_NODE_IDS_UNTRIMMED = RM1_NODE_ID_UNTRIMMED + "," + RM2_NODE_ID; private static final String RM_NODE_IDS = RM1_NODE_ID + "," + RM2_NODE_ID; @BeforeEach public void setUp() { conf = new Configuration(); conf.set(YarnConfiguration.RM_HA_IDS, RM_NODE_IDS_UNTRIMMED); conf.set(YarnConfiguration.RM_HA_ID, RM1_NODE_ID_UNTRIMMED); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(conf)) { // configuration key itself cannot contains space/tab/return chars. conf.set(HAUtil.addSuffix(confKey, RM1_NODE_ID), RM1_ADDRESS_UNTRIMMED); conf.set(HAUtil.addSuffix(confKey, RM2_NODE_ID), RM2_ADDRESS); } } @Test void testGetRMServiceId() throws Exception { conf.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); Collection<String> rmhaIds = HAUtil.getRMHAIds(conf); assertEquals(2, rmhaIds.size()); String[] ids = rmhaIds.toArray(new String[0]); assertEquals(RM1_NODE_ID, ids[0]); assertEquals(RM2_NODE_ID, ids[1]); } @Test void testGetRMId() throws Exception { conf.set(YarnConfiguration.RM_HA_ID, RM1_NODE_ID); assertEquals(RM1_NODE_ID, HAUtil.getRMHAId(conf), "Does not honor " + YarnConfiguration.RM_HA_ID); conf.clear(); assertNull(HAUtil.getRMHAId(conf), "Return null when " + YarnConfiguration.RM_HA_ID + " is not set"); } @Test void testVerifyAndSetConfiguration() throws Exception { Configuration myConf = new Configuration(conf); try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { fail("Should not throw any exceptions."); } assertEquals(StringUtils.getStringCollection(RM_NODE_IDS), HAUtil.getRMHAIds(myConf), "Should be saved as Trimmed collection"); assertEquals(RM1_NODE_ID, HAUtil.getRMHAId(myConf), "Should be saved as Trimmed string"); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(myConf)) { assertEquals(RM1_ADDRESS, myConf.get(confKey), "RPC address not set for " + confKey); } myConf = new Configuration(conf); myConf.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID); try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { assertEquals(HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.getInvalidValueMessage(YarnConfiguration.RM_HA_IDS, myConf.get(YarnConfiguration.RM_HA_IDS) + "\nHA mode requires atleast two RMs"), e.getMessage(), "YarnRuntimeException by verifyAndSetRMHAIds()"); } myConf = new Configuration(conf); // simulate the case YarnConfiguration.RM_HA_ID is not set myConf.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(myConf)) { myConf.set(HAUtil.addSuffix(confKey, RM1_NODE_ID), RM1_ADDRESS); myConf.set(HAUtil.addSuffix(confKey, RM2_NODE_ID), RM2_ADDRESS); } try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { assertEquals(HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.getNeedToSetValueMessage(YarnConfiguration.RM_HA_ID), e.getMessage(), "YarnRuntimeException by getRMId()"); } myConf = new Configuration(conf); myConf.set(YarnConfiguration.RM_HA_ID, RM_INVALID_NODE_ID); myConf.set(YarnConfiguration.RM_HA_IDS, RM_INVALID_NODE_ID + "," + RM1_NODE_ID); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(myConf)) { // simulate xml with invalid node id myConf.set(confKey + RM_INVALID_NODE_ID, RM_INVALID_NODE_ID); } try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { assertEquals(HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.getInvalidValueMessage(YarnConfiguration.RM_HA_ID, RM_INVALID_NODE_ID), e.getMessage(), "YarnRuntimeException by addSuffix()"); } myConf = new Configuration(); // simulate the case HAUtil.RM_RPC_ADDRESS_CONF_KEYS are not set myConf.set(YarnConfiguration.RM_HA_ID, RM1_NODE_ID); myConf.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); try { HAUtil.verifyAndSetConfiguration(myConf); fail("Should throw YarnRuntimeException. by Configuration#set()"); } catch (YarnRuntimeException e) { String confKey = HAUtil.addSuffix(YarnConfiguration.RM_ADDRESS, RM1_NODE_ID); assertEquals(HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.getNeedToSetValueMessage( HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM1_NODE_ID) + " or " + confKey), e.getMessage(), "YarnRuntimeException by Configuration#set()"); } // simulate the case YarnConfiguration.RM_HA_IDS doesn't contain // the value of YarnConfiguration.RM_HA_ID myConf = new Configuration(conf); myConf.set(YarnConfiguration.RM_HA_IDS, RM2_NODE_ID + "," + RM3_NODE_ID); myConf.set(YarnConfiguration.RM_HA_ID, RM1_NODE_ID_UNTRIMMED); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(myConf)) { myConf.set(HAUtil.addSuffix(confKey, RM1_NODE_ID), RM1_ADDRESS_UNTRIMMED); myConf.set(HAUtil.addSuffix(confKey, RM2_NODE_ID), RM2_ADDRESS); myConf.set(HAUtil.addSuffix(confKey, RM3_NODE_ID), RM3_ADDRESS); } try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { assertEquals(HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.getRMHAIdNeedToBeIncludedMessage("[rm2, rm3]", RM1_NODE_ID), e.getMessage(), "YarnRuntimeException by getRMId()'s validation"); } // simulate the case that no leader election is enabled myConf = new Configuration(conf); myConf.setBoolean(YarnConfiguration.RM_HA_ENABLED, true); myConf.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, true); myConf.setBoolean(YarnConfiguration.AUTO_FAILOVER_EMBEDDED, false); myConf.setBoolean(YarnConfiguration.CURATOR_LEADER_ELECTOR, false); try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { assertEquals(HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.NO_LEADER_ELECTION_MESSAGE, e.getMessage(), "YarnRuntimeException by getRMId()'s validation"); } } @Test void testGetConfKeyForRMInstance() { assertTrue(HAUtil.getConfKeyForRMInstance(YarnConfiguration.RM_ADDRESS, conf) .contains(HAUtil.getRMHAId(conf)), "RM instance id is not suffixed"); assertFalse(HAUtil.getConfKeyForRMInstance(YarnConfiguration.NM_ADDRESS, conf) .contains(HAUtil.getRMHAId(conf)), "RM instance id is suffixed"); } }
TestHAUtil
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/FieldCanBeStaticTest.java
{ "start": 7915, "end": 8129 }
class ____ { private final Duration D = Duration.ofMillis(1); // BUG: Diagnostic contains: can be static private final int I = 42; } static
I
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/LoggerConfigAdminMBean.java
{ "start": 937, "end": 4146 }
interface ____ { /** * ObjectName pattern ({@value}) for LoggerConfigAdmin MBeans. * This pattern contains two variables, where the first is the name of the * context, the second is the name of the instrumented logger config. * <p> * You can find all registered LoggerConfigAdmin MBeans like this: * </p> * <pre> * MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); * String pattern = String.format(LoggerConfigAdminMBean.PATTERN, &quot;*&quot;, &quot;*&quot;); * Set&lt;ObjectName&gt; loggerConfigNames = mbs.queryNames(new ObjectName(pattern), null); * </pre> * <p> * Some characters are not allowed in ObjectNames. The logger context name * and logger config name may be quoted. When LoggerConfigAdmin MBeans are * registered, their ObjectNames are created using this pattern as follows: * </p> * <pre> * String ctxName = Server.escape(loggerContext.getName()); * String loggerConfigName = Server.escape(loggerConfig.getName()); * String name = String.format(PATTERN, ctxName, loggerConfigName); * ObjectName objectName = new ObjectName(name); * </pre> * @see Server#escape(String) */ String PATTERN = Server.DOMAIN + ":type=%s,component=Loggers,name=%s"; /** * Returns the name of the instrumented {@code LoggerConfig}. * * @return the name of the LoggerConfig */ String getName(); /** * Returns the {@code LoggerConfig} level as a String. * * @return the {@code LoggerConfig} level. */ String getLevel(); /** * Sets the {@code LoggerConfig} level to the specified value. * * @param level the new {@code LoggerConfig} level. * @throws IllegalArgumentException if the specified level is not one of * "OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE", * "ALL" */ void setLevel(String level); /** * Returns whether the instrumented {@code LoggerConfig} is additive. * * @return {@code true} if the LoggerConfig is additive, {@code false} * otherwise */ boolean isAdditive(); /** * Sets whether the instrumented {@code LoggerConfig} should be additive. * * @param additive {@code true} if the instrumented LoggerConfig should be * additive, {@code false} otherwise */ void setAdditive(boolean additive); /** * Returns whether the instrumented {@code LoggerConfig} is configured to * include location. * * @return whether location should be passed downstream */ boolean isIncludeLocation(); /** * Returns a string description of all filters configured for the * instrumented {@code LoggerConfig}. * * @return a string description of all configured filters for this * LoggerConfig */ String getFilter(); /** * Returns a String array with the appender refs configured for the * instrumented {@code LoggerConfig}. * * @return the appender refs for the instrumented {@code LoggerConfig}. */ String[] getAppenderRefs(); }
LoggerConfigAdminMBean
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java
{ "start": 42440, "end": 51908 }
class ____ { @OneToOne private Child biologicalChild; } fetchablePath= Mother.biologicalChild.mother this.mappedBy = "biologicalChild" parent.getFullPath() = "Mother.biologicalChild" */ final var grandparentNavigablePath = parentNavigablePath.getParent(); if ( parentNavigablePath.getLocalName().equals( CollectionPart.Nature.ELEMENT.getName() ) && grandparentNavigablePath != null && grandparentNavigablePath.isSuffix( bidirectionalAttributePath ) ) { final var parentPath = grandparentNavigablePath.getParent(); // This can be null for a collection loader if ( parentPath == null ) { return grandparentNavigablePath.getFullPath().equals( entityMappingType.findByPath( bidirectionalAttributePath ).getNavigableRole().getFullPath() ); } else { // If the parent is null, this is a simple collection fetch of a root, in which case the types must match if ( parentPath.getParent() == null ) { final String entityName = entityMappingType.getPartName(); return parentPath.getFullPath().startsWith( entityName ) && ( parentPath.getFullPath().length() == entityName.length() // Ignore a possible alias || parentPath.getFullPath().charAt( entityName.length() ) == '(' ); } // If we have a parent, we ensure that the parent is the same as the attribute name else { return parentPath.getLocalName().equals( navigableRole.getLocalName() ); } } } return false; } NavigablePath navigablePath = parentNavigablePath.trimSuffix( bidirectionalAttributePath ); if ( navigablePath != null ) { final String localName = navigablePath.getLocalName(); if ( localName.equals( EntityIdentifierMapping.ID_ROLE_NAME ) || localName.equals( ForeignKeyDescriptor.PART_NAME ) || localName.equals( ForeignKeyDescriptor.TARGET_PART_NAME ) ) { navigablePath = navigablePath.getParent(); } return creationState.resolveModelPart( navigablePath ).getPartMappingType() == entityMappingType; } return false; } private boolean isParentEmbeddedCollectionPart(DomainResultCreationState creationState, NavigablePath parentNavigablePath) { while ( parentNavigablePath != null ) { final ModelPart parentModelPart = creationState.resolveModelPart( parentNavigablePath ); if ( parentModelPart instanceof EmbeddedCollectionPart ) { return true; } else if ( parentModelPart instanceof EmbeddableValuedModelPart ) { parentNavigablePath = parentNavigablePath.getParent(); } else { return false; } } return false; } private Fetch createCircularBiDirectionalFetch( NavigablePath fetchablePath, FetchParent fetchParent, NavigablePath parentNavigablePath, FetchTiming fetchTiming, DomainResultCreationState creationState) { final NavigablePath referencedNavigablePath; final boolean hasBidirectionalFetchParent; FetchParent realFetchParent = fetchParent; // Traverse up the embeddable fetches while ( realFetchParent.getNavigablePath() != parentNavigablePath ) { realFetchParent = ( (Fetch) fetchParent ).getFetchParent(); } if ( parentNavigablePath.getParent() == null ) { referencedNavigablePath = parentNavigablePath; hasBidirectionalFetchParent = true; } else if ( CollectionPart.Nature.fromNameExact( parentNavigablePath.getLocalName() ) != null ) { referencedNavigablePath = getReferencedNavigablePath( creationState, parentNavigablePath.getParent() ); hasBidirectionalFetchParent = fetchParent instanceof Fetch fetch && fetch.getFetchParent() instanceof Fetch; } else { referencedNavigablePath = getReferencedNavigablePath( creationState, parentNavigablePath ); hasBidirectionalFetchParent = fetchParent instanceof Fetch; } // The referencedNavigablePath can be null if this is a collection initialization if ( referencedNavigablePath != null ) { // If this is the key side, we must ensure that the key is not null, so we create a domain result for it // In the CircularBiDirectionalFetchImpl we return null if the key is null instead of the bidirectional value final DomainResult<?> keyDomainResult; // For now, we don't do this if the key table is nullable to avoid an additional join if ( sideNature == ForeignKeyDescriptor.Nature.KEY && !isKeyTableNullable ) { keyDomainResult = foreignKeyDescriptor.createKeyDomainResult( fetchablePath, createTableGroupForDelayedFetch( fetchablePath, creationState.getSqlAstCreationState() .getFromClauseAccess() .findTableGroup( realFetchParent.getNavigablePath() ), null, creationState ), fetchParent, creationState ); } else { keyDomainResult = null; } if ( hasBidirectionalFetchParent ) { return new CircularBiDirectionalFetchImpl( FetchTiming.IMMEDIATE, fetchablePath, fetchParent, this, referencedNavigablePath, keyDomainResult ); } else { // A query like `select ch from Phone p join p.callHistory ch` returns collection element domain results // but detects that Call#phone is bidirectional in the query. // The problem with a bidirectional fetch though is that we can't find an initializer // because there is none, as we don't fetch the data of the parent node. // To avoid creating another join, we create a special join fetch that uses the existing joined data final var fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); final var tableGroup = fromClauseAccess.getTableGroup( referencedNavigablePath ); fromClauseAccess.registerTableGroup( fetchablePath, tableGroup ); // Register a PROJECTION usage as we're effectively selecting the bidirectional association creationState.getSqlAstCreationState().registerEntityNameUsage( tableGroup, EntityNameUse.PROJECTION, entityMappingType.getEntityName() ); return buildEntityFetchJoined( fetchParent, this, tableGroup, keyDomainResult, false, fetchablePath, creationState ); } } else { // We get here is this is a lazy collection initialization for which we know the owner is in the PC // So we create a delayed fetch, as we are sure to find the entity in the PC final var fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); final var parentTableGroup = fromClauseAccess.getTableGroup( parentNavigablePath ); final DomainResult<?> domainResult; if ( sideNature == ForeignKeyDescriptor.Nature.KEY ) { domainResult = foreignKeyDescriptor.createKeyDomainResult( fetchablePath, createTableGroupForDelayedFetch( fetchablePath, parentTableGroup, null, creationState ), fetchParent, creationState ); } else { domainResult = foreignKeyDescriptor.createTargetDomainResult( fetchablePath, parentTableGroup, fetchParent, creationState ); } if ( fetchTiming == FetchTiming.IMMEDIATE ) { return buildEntityFetchSelect( fetchParent, this, fetchablePath, domainResult, isSelectByUniqueKey( sideNature ), false, creationState ); } if ( entityMappingType.isConcreteProxy() && sideNature == ForeignKeyDescriptor.Nature.TARGET ) { createTableGroupForDelayedFetch( fetchablePath, parentTableGroup, null, creationState ); } return buildEntityDelayedFetch( fetchParent, this, fetchablePath, domainResult, isSelectByUniqueKey( sideNature ), creationState ); } } /** * For Hibernate Reactive */ protected EntityFetch buildEntityDelayedFetch( FetchParent fetchParent, ToOneAttributeMapping fetchedAttribute, NavigablePath navigablePath, DomainResult<?> keyResult, boolean selectByUniqueKey, DomainResultCreationState creationState) { return new EntityDelayedFetchImpl( fetchParent, fetchedAttribute, navigablePath, keyResult, selectByUniqueKey, creationState ); } /** * For Hibernate Reactive */ protected EntityFetch buildEntityFetchSelect( FetchParent fetchParent, ToOneAttributeMapping fetchedAttribute, NavigablePath navigablePath, DomainResult<?> keyResult, boolean selectByUniqueKey, boolean isAffectedByFilter, @SuppressWarnings("unused") DomainResultCreationState creationState) { return new EntityFetchSelectImpl( fetchParent, fetchedAttribute, navigablePath, keyResult, selectByUniqueKey, isAffectedByFilter, creationState ); } /** * For Hibernate Reactive */ protected EntityFetch buildEntityFetchJoined( FetchParent fetchParent, ToOneAttributeMapping toOneMapping, TableGroup tableGroup, DomainResult<?> keyResult, boolean isAffectedByFilter, NavigablePath navigablePath, DomainResultCreationState creationState) { return new EntityFetchJoinedImpl( fetchParent, toOneMapping, tableGroup, keyResult, isAffectedByFilter, navigablePath, creationState ); } private NavigablePath getReferencedNavigablePath( DomainResultCreationState creationState, NavigablePath parentNavigablePath) { NavigablePath referencedNavigablePath = parentNavigablePath.getParent(); MappingType partMappingType = creationState.resolveModelPart( referencedNavigablePath ).getPartMappingType(); /*
Mother
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/injectionstrategy/jakarta/field/JakartaAndJsr330FieldMapperTest.java
{ "start": 1175, "end": 1853 }
class ____ { @RegisterExtension final GeneratedSource generatedSource = new GeneratedSource(); @ProcessorTest public void shouldHaveJakartaInjection() { generatedSource.forMapper( CustomerFieldMapper.class ) .content() .contains( "import jakarta.inject.Inject;" ) .contains( "import jakarta.inject.Named;" ) .contains( "import jakarta.inject.Singleton;" ) .contains( "@Inject" + lineSeparator() + " private GenderJakartaFieldMapper" ) .doesNotContain( "public CustomerJakartaFieldMapperImpl(" ) .doesNotContain( "javax.inject" ); } }
JakartaAndJsr330FieldMapperTest
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/TransportStartDatafeedAction.java
{ "start": 33231, "end": 35087 }
class ____ implements Predicate<PersistentTasksCustomMetadata.PersistentTask<?>> { private volatile Exception exception; private volatile String node = ""; @Override public boolean test(PersistentTasksCustomMetadata.PersistentTask<?> persistentTask) { if (persistentTask == null) { return false; } PersistentTasksCustomMetadata.Assignment assignment = persistentTask.getAssignment(); if (assignment != null) { // This means we are awaiting the datafeed's job to be assigned to a node if (assignment.equals(DatafeedNodeSelector.AWAITING_JOB_ASSIGNMENT)) { return true; } // This means the node the job got assigned to was shut down in between starting the job and the datafeed - not an error if (assignment.equals(DatafeedNodeSelector.AWAITING_JOB_RELOCATION)) { return true; } if (assignment.equals(PersistentTasksCustomMetadata.INITIAL_ASSIGNMENT) == false && assignment.isAssigned() == false) { // Assignment has failed despite passing our "fast fail" validation exception = new ElasticsearchStatusException( "Could not start datafeed, allocation explanation [" + assignment.getExplanation() + "]", RestStatus.TOO_MANY_REQUESTS ); return true; } } DatafeedState datafeedState = (DatafeedState) persistentTask.getState(); if (datafeedState == DatafeedState.STARTED) { node = persistentTask.getExecutorNode(); return true; } return false; } } }
DatafeedPredicate
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/converter/ProtobufMessageConverter.java
{ "start": 2158, "end": 6930 }
class ____ extends AbstractMessageConverter { /** * The default charset used by the converter. */ public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; /** * The mime-type for protobuf {@code application/x-protobuf}. */ public static final MimeType PROTOBUF = new MimeType("application", "x-protobuf", DEFAULT_CHARSET); private static final boolean PROTOBUF_JSON_FORMAT_PRESENT = ClassUtils.isPresent("com.google.protobuf.util.JsonFormat", ProtobufMessageConverter.class.getClassLoader()); private static final Map<Class<?>, Method> methodCache = new ConcurrentReferenceHashMap<>(); final ExtensionRegistry extensionRegistry; private final @Nullable ProtobufFormatSupport protobufFormatSupport; /** * Constructor with a default instance of {@link ExtensionRegistry}. */ public ProtobufMessageConverter() { this(null, null); } /** * Constructor with a given {@code ExtensionRegistry}. */ public ProtobufMessageConverter(ExtensionRegistry extensionRegistry) { this(null, extensionRegistry); } ProtobufMessageConverter(@Nullable ProtobufFormatSupport formatSupport, @Nullable ExtensionRegistry extensionRegistry) { super(PROTOBUF, TEXT_PLAIN); if (formatSupport != null) { this.protobufFormatSupport = formatSupport; } else if (PROTOBUF_JSON_FORMAT_PRESENT) { this.protobufFormatSupport = new ProtobufJavaUtilSupport(null, null); } else { this.protobufFormatSupport = null; } if (this.protobufFormatSupport != null) { addSupportedMimeTypes(this.protobufFormatSupport.supportedMediaTypes()); } this.extensionRegistry = (extensionRegistry == null ? ExtensionRegistry.newInstance() : extensionRegistry); } @Override protected boolean supports(Class<?> clazz) { return Message.class.isAssignableFrom(clazz); } @Override protected boolean canConvertTo(Object payload, @Nullable MessageHeaders headers) { MimeType contentType = getMimeType(headers); return (super.canConvertTo(payload, headers) || this.protobufFormatSupport != null && this.protobufFormatSupport.supportsWriteOnly(contentType)); } @Override protected Object convertFromInternal(org.springframework.messaging.Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) { MimeType contentType = getMimeType(message.getHeaders()); final Object payload = message.getPayload(); if (contentType == null) { contentType = PROTOBUF; } Charset charset = contentType.getCharset(); if (charset == null) { charset = DEFAULT_CHARSET; } Message.Builder builder = getMessageBuilder(targetClass); try { if (PROTOBUF.isCompatibleWith(contentType)) { builder.mergeFrom((byte[]) payload, this.extensionRegistry); } else if (this.protobufFormatSupport != null) { this.protobufFormatSupport.merge(message, charset, contentType, this.extensionRegistry, builder); } } catch (IOException ex) { throw new MessageConversionException(message, "Could not read proto message" + ex.getMessage(), ex); } return builder.build(); } @Override protected Object convertToInternal( Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) { final Message message = (Message) payload; MimeType contentType = getMimeType(headers); if (contentType == null) { contentType = PROTOBUF; } Charset charset = contentType.getCharset(); if (charset == null) { charset = DEFAULT_CHARSET; } try { if (PROTOBUF.isCompatibleWith(contentType)) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); message.writeTo(byteArrayOutputStream); payload = byteArrayOutputStream.toByteArray(); } else if (this.protobufFormatSupport != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); this.protobufFormatSupport.print(message, outputStream, contentType, charset); payload = outputStream.toString(charset); } } catch (IOException ex) { throw new MessageConversionException("Failed to print Protobuf message: " + ex.getMessage(), ex); } return payload; } /** * Create a new {@code Message.Builder} instance for the given class. * <p>This method uses a ConcurrentReferenceHashMap for caching method lookups. */ private Message.Builder getMessageBuilder(Class<?> clazz) { try { Method method = methodCache.get(clazz); if (method == null) { method = clazz.getMethod("newBuilder"); methodCache.put(clazz, method); } return (Message.Builder) method.invoke(clazz); } catch (Exception ex) { throw new MessageConversionException( "Invalid Protobuf Message type: no invocable newBuilder() method on " + clazz, ex); } } /** * Protobuf format support. */
ProtobufMessageConverter
java
quarkusio__quarkus
extensions/redis-cache/deployment/src/main/java/io/quarkus/cache/redis/deployment/RedisCacheProcessor.java
{ "start": 1743, "end": 10266 }
class ____ { private static final Logger LOGGER = Logger.getLogger(RedisCacheProcessor.class); public static final DotName UNI = DotName.createSimple(Uni.class.getName()); @BuildStep @Record(RUNTIME_INIT) CacheManagerInfoBuildItem cacheManagerInfo(RedisCacheBuildRecorder recorder) { return new CacheManagerInfoBuildItem(recorder.getCacheManagerSupplier()); } @BuildStep UnremovableBeanBuildItem redisClientUnremoveable() { return UnremovableBeanBuildItem.beanTypes(io.vertx.redis.client.Redis.class, io.vertx.mutiny.redis.client.Redis.class); } @BuildStep RequestedRedisClientBuildItem requestedRedisClientBuildItem(RedisCachesBuildTimeConfig buildConfig) { return new RequestedRedisClientBuildItem(buildConfig.clientName().orElse(RedisConfig.DEFAULT_CLIENT_NAME)); } @BuildStep void nativeImage(BuildProducer<ReflectiveClassBuildItem> producer) { producer.produce(ReflectiveClassBuildItem.builder(CompositeCacheKey.class) .reason(getClass().getName()) .methods().build()); } @BuildStep @Record(STATIC_INIT) void determineKeyValueTypes(RedisCacheBuildRecorder recorder, CombinedIndexBuildItem combinedIndex, CacheNamesBuildItem cacheNamesBuildItem, RedisCachesBuildTimeConfig buildConfig) { Map<String, java.lang.reflect.Type> keyTypes = new HashMap<>(); RedisCacheBuildTimeConfig defaultBuildTimeConfig = buildConfig.defaultConfig(); for (String cacheName : cacheNamesBuildItem.getNames()) { RedisCacheBuildTimeConfig namedBuildTimeConfig = buildConfig.cachesConfig().get(cacheName); if (namedBuildTimeConfig != null && namedBuildTimeConfig.keyType().isPresent()) { keyTypes.put(cacheName, TypeParser.parse(namedBuildTimeConfig.keyType().get())); } else if (defaultBuildTimeConfig.keyType().isPresent()) { keyTypes.put(cacheName, TypeParser.parse(defaultBuildTimeConfig.keyType().get())); } } recorder.setCacheKeyTypes(keyTypes); Map<String, Type> resolvedValuesTypesFromAnnotations = valueTypesFromCacheResultAnnotation(combinedIndex); Map<String, java.lang.reflect.Type> valueTypes = new HashMap<>(); Optional<String> defaultValueType = buildConfig.defaultConfig().valueType(); Set<String> cacheNames = cacheNamesBuildItem.getNames(); for (String cacheName : cacheNames) { String valueType = null; RedisCacheBuildTimeConfig cacheSpecificGroup = buildConfig.cachesConfig().get(cacheName); if (cacheSpecificGroup == null) { if (defaultValueType.isPresent()) { valueType = defaultValueType.get(); } } else { if (cacheSpecificGroup.valueType().isPresent()) { valueType = cacheSpecificGroup.valueType().get(); } } if (valueType == null && resolvedValuesTypesFromAnnotations.containsKey(cacheName)) { // TODO: does it make sense to use the return type of method annotated with @CacheResult as the last resort or should it override the default cache config? valueType = typeToString(resolvedValuesTypesFromAnnotations.get(cacheName)); } if (valueType != null) { valueTypes.put(cacheName, TypeParser.parse(valueType)); } else { throw new DeploymentException("Unable to determine the value type for '" + cacheName + "' Redis cache. An appropriate configuration value for 'quarkus.cache.redis." + cacheName + ".value-type' needs to be set"); } } recorder.setCacheValueTypes(valueTypes); } private static Map<String, Type> valueTypesFromCacheResultAnnotation(CombinedIndexBuildItem combinedIndex) { Map<String, Set<Type>> valueTypesFromAnnotations = new HashMap<>(); // first go through @CacheResult instances and simply record the return types for (AnnotationInstance instance : combinedIndex.getIndex().getAnnotations(CacheDeploymentConstants.CACHE_RESULT)) { if (instance.target().kind() != METHOD) { continue; } Type methodReturnType = instance.target().asMethod().returnType(); if (methodReturnType.kind() == Type.Kind.VOID) { continue; } AnnotationValue cacheNameValue = instance.value("cacheName"); if (cacheNameValue == null) { continue; } String cacheName = cacheNameValue.asString(); Set<Type> types = valueTypesFromAnnotations.get(cacheName); if (types == null) { types = new HashSet<>(1); valueTypesFromAnnotations.put(cacheName, types); } types.add(methodReturnType); } if (valueTypesFromAnnotations.isEmpty()) { return Collections.emptyMap(); } Map<String, Type> result = new HashMap<>(); // now apply our resolution logic on the obtained types for (var entry : valueTypesFromAnnotations.entrySet()) { String cacheName = entry.getKey(); Set<Type> typeSet = entry.getValue(); if (typeSet.size() != 1) { LOGGER.debugv("Cache named '{0}' is used on methods with different result types", cacheName); // TODO: when there are multiple types for the same @CacheResult, should we fail? Should we try and be smarter in determining the type? continue; } Type type = typeSet.iterator().next(); Type resolvedType = null; if (type.kind() == Type.Kind.PARAMETERIZED_TYPE && UNI.equals(type.name())) { ParameterizedType parameterizedType = type.asParameterizedType(); List<Type> arguments = parameterizedType.arguments(); if (arguments.size() == 1) { resolvedType = arguments.get(0); } } else { resolvedType = type; } if (resolvedType != null) { result.put(cacheName, resolvedType); } else { LOGGER.debugv( "Cache named '{0}' is used on method whose return type '{1}' is not eligible for automatic resolution", cacheName, type); } } return result; } private static String typeToString(Type type) { StringBuilder result = new StringBuilder(); typeToString(type, result); return result.toString(); } private static void typeToString(Type type, StringBuilder result) { switch (type.kind()) { case VOID, PRIMITIVE, CLASS -> result.append(type.name().toString()); case ARRAY -> { typeToString(type.asArrayType().elementType(), result); result.append("[]".repeat(type.asArrayType().deepDimensions())); } case PARAMETERIZED_TYPE -> { if (type.asParameterizedType().owner() != null) { throw new IllegalArgumentException("Unsupported type: " + type); } result.append(type.name().toString()); result.append('<'); boolean first = true; for (Type typeArgument : type.asParameterizedType().arguments()) { if (!first) { result.append(", "); } typeToString(typeArgument, result); first = false; } result.append('>'); } case WILDCARD_TYPE -> { result.append('?'); if (type.asWildcardType().superBound() != null) { result.append(" super "); typeToString(type.asWildcardType().superBound(), result); } else if (type.asWildcardType().extendsBound() != ClassType.OBJECT_TYPE) { result.append(" extends "); typeToString(type.asWildcardType().extendsBound(), result); } } default -> throw new IllegalArgumentException("Unsupported type: " + type); } } }
RedisCacheProcessor
java
quarkusio__quarkus
extensions/virtual-threads/runtime/src/main/java/io/quarkus/virtual/threads/VirtualThreadsConfig.java
{ "start": 390, "end": 1627 }
interface ____ { /** * Virtual thread name prefix. The name of the virtual thread will be the prefix followed by a unique number. */ @WithDefault("quarkus-virtual-thread-") Optional<String> namePrefix(); /** * The shutdown timeout. If all pending work has not been completed by this time * then any pending tasks will be interrupted, and the shutdown process will continue */ @WithDefault("1M") Duration shutdownTimeout(); /** * The frequency at which the status of the executor service should be checked during shutdown. * Setting this key to an empty value will use the same value as the shutdown timeout. */ @WithDefault("5s") Optional<Duration> shutdownCheckInterval(); /** * A flag to explicitly disabled virtual threads, even if the JVM support them. * In this case, methods annotated with {@code @RunOnVirtualThread} are executed on the worker thread pool. * <p> * This flag is intended to be used when running with virtual threads become more expensive than plain worker threads, * because of pinning, monopolization or thread-based object pool. */ @WithDefault("true") boolean enabled(); }
VirtualThreadsConfig
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotationsPropertySourceTests.java
{ "start": 12500, "end": 12557 }
interface ____ { } @SelfAnnotating static
SelfAnnotating
java
elastic__elasticsearch
plugins/repository-hdfs/src/main/java/org/elasticsearch/repositories/hdfs/HdfsPlugin.java
{ "start": 1264, "end": 2094 }
class ____ extends Plugin implements RepositoryPlugin { // initialize some problematic classes static { eagerInitSecurityUtil(); } private static Void eagerInitSecurityUtil() { /* * Hadoop RPC wire serialization uses ProtocolBuffers. All proto classes for Hadoop * come annotated with configurations that denote information about if they support * certain security options like Kerberos, and how to send information with the * message to support that authentication method. SecurityUtil creates a service loader * in a static field during its clinit. This loader provides the implementations that * pull the security information for each proto class. The service loader sources its * services from the current thread's context
HdfsPlugin
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java
{ "start": 3233, "end": 3652 }
class ____ extends JndiLocatorSupport { private final String[] locations; public JndiLocator(String[] locations) { this.locations = locations; } public @Nullable String lookupFirstLocation() { for (String location : this.locations) { try { lookup(location); return location; } catch (NamingException ex) { // Swallow and continue } } return null; } } }
JndiLocator
java
apache__camel
components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisTestSupport.java
{ "start": 1043, "end": 3620 }
class ____ extends CamelTestSupport { protected boolean createTestData() { return true; } /** * Gets the name of the database table handling the test data. * * @return The name of the database table handling the test data. */ protected String getTableName() { return "ACCOUNT"; } /** * Gets the SQL query dropping the test data table. * * @return The SQL query dropping the test data table. */ protected String getDropStatement() { return "drop table ACCOUNT"; } /** * Gets the SQL query creating the test data table. * * @return The SQL query creating the test data table. */ protected String getCreateStatement() { return "create table ACCOUNT (ACC_ID INTEGER, ACC_FIRST_NAME VARCHAR(255), ACC_LAST_NAME VARCHAR(255), ACC_EMAIL VARCHAR(255))"; } @Override @BeforeEach public void doPostSetup() throws Exception { try (Connection connection = createConnection(); ResultSet checkTableExistResultSet = connection.getMetaData().getTables(null, null, getTableName(), null); Statement deletePreExistingTableStatement = connection.createStatement(); Statement createTableStatement = connection.createStatement()) { // delete any pre-existing ACCOUNT table if (checkTableExistResultSet.next()) { deletePreExistingTableStatement.execute(getDropStatement()); } // lets create the table... createTableStatement.execute(getCreateStatement()); connection.commit(); } if (createTestData()) { Account account1 = new Account(); account1.setId(123); account1.setFirstName("James"); account1.setLastName("Strachan"); account1.setEmailAddress("TryGuessing@gmail.com"); Account account2 = new Account(); account2.setId(456); account2.setFirstName("Claus"); account2.setLastName("Ibsen"); account2.setEmailAddress("Noname@gmail.com"); template.sendBody("mybatis:insertAccount?statementType=Insert", new Account[] { account1, account2 }); } } protected Connection createConnection() throws Exception { MyBatisComponent component = context.getComponent("mybatis", MyBatisComponent.class); return component.createSqlSessionFactory().getConfiguration().getEnvironment().getDataSource().getConnection(); } }
MyBatisTestSupport
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/typeutils/RowTypeUtilsTest.java
{ "start": 1408, "end": 3561 }
class ____ { private final RowType srcType = RowType.of( new LogicalType[] {new IntType(), new VarCharType(), new BigIntType()}, new String[] {"f0", "f1", "f2"}); @Test void testGetUniqueName() { assertThat( RowTypeUtils.getUniqueName( Arrays.asList("Dave", "Evan"), Arrays.asList("Alice", "Bob"))) .isEqualTo(Arrays.asList("Dave", "Evan")); assertThat( RowTypeUtils.getUniqueName( Arrays.asList("Bob", "Bob", "Dave", "Alice"), Arrays.asList("Alice", "Bob"))) .isEqualTo(Arrays.asList("Bob_0", "Bob_1", "Dave", "Alice_0")); } @Test void testProjectRowType() { assertThat(RowTypeUtils.projectRowType(srcType, new int[] {0})) .isEqualTo(RowType.of(new LogicalType[] {new IntType()}, new String[] {"f0"})); assertThat(RowTypeUtils.projectRowType(srcType, new int[] {0, 2})) .isEqualTo( RowType.of( new LogicalType[] {new IntType(), new BigIntType()}, new String[] {"f0", "f2"})); assertThat(RowTypeUtils.projectRowType(srcType, new int[] {0, 1, 2})).isEqualTo(srcType); } @Test void testInvalidProjectRowType() { assertThatThrownBy(() -> RowTypeUtils.projectRowType(srcType, new int[] {0, 1, 2, 3})) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Invalid projection index: 3"); assertThatThrownBy(() -> RowTypeUtils.projectRowType(srcType, new int[] {0, 1, 3})) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Invalid projection index: 3"); assertThatThrownBy(() -> RowTypeUtils.projectRowType(srcType, new int[] {0, 0, 0, 0})) .isInstanceOf(ValidationException.class) .hasMessageContaining("Field names must be unique. Found duplicates"); } }
RowTypeUtilsTest
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-guava-tests/src/test/java/org/assertj/tests/guava/api/RangeSetAssert_isNullOrEmpty_Test.java
{ "start": 1152, "end": 1861 }
class ____ { @Test void should_pass_if_actual_is_null() { // GIVEN RangeSet<Integer> actual = null; // WHEN/THEN assertThat(actual).isNullOrEmpty(); } @Test void should_pass_if_actual_is_empty() { // GIVEN RangeSet<Integer> actual = ImmutableRangeSet.of(); // THEN assertThat(actual).isNullOrEmpty(); } @Test void should_fail_if_actual_is_not_null_and_not_empty() { // GIVEN RangeSet<Integer> actual = ImmutableRangeSet.of(closed(1, 10)); // WHEN var error = expectAssertionError(() -> assertThat(actual).isNullOrEmpty()); // WHEN/THEN then(error).hasMessage(shouldBeNullOrEmpty(actual).create()); } }
RangeSetAssert_isNullOrEmpty_Test
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableLastMaybe.java
{ "start": 1419, "end": 2782 }
class ____<T> implements Observer<T>, Disposable { final MaybeObserver<? super T> downstream; Disposable upstream; T item; LastObserver(MaybeObserver<? super T> downstream) { this.downstream = downstream; } @Override public void dispose() { upstream.dispose(); upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { return upstream == DisposableHelper.DISPOSED; } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { this.upstream = d; downstream.onSubscribe(this); } } @Override public void onNext(T t) { item = t; } @Override public void onError(Throwable t) { upstream = DisposableHelper.DISPOSED; item = null; downstream.onError(t); } @Override public void onComplete() { upstream = DisposableHelper.DISPOSED; T v = item; if (v != null) { item = null; downstream.onSuccess(v); } else { downstream.onComplete(); } } } }
LastObserver
java
apache__flink
flink-python/src/main/java/org/apache/flink/client/python/PythonDriver.java
{ "start": 1584, "end": 7042 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(PythonDriver.class); public static void main(String[] args) throws Throwable { // The python job needs at least 2 args. // e.g. py a.py [user args] // e.g. pym a.b [user args] if (args.length < 2) { LOG.error( "Required at least two arguments, only python file or python module is available."); System.exit(1); } // parse args final CommandLineParser<PythonDriverOptions> commandLineParser = new CommandLineParser<>(new PythonDriverOptionsParserFactory()); PythonDriverOptions pythonDriverOptions = null; try { pythonDriverOptions = commandLineParser.parse(args); } catch (Exception e) { LOG.error("Could not parse command line arguments {}.", args, e); commandLineParser.printHelp(PythonDriver.class.getSimpleName()); System.exit(1); } // Get configuration from ContextEnvironment/OptimizerPlanEnvironment. As the configurations // of // streaming and batch environments are always set at the same time, for streaming jobs we // can // also get its configuration from batch environments. Configuration config = Configuration.fromMap( StreamExecutionEnvironment.getExecutionEnvironment() .getConfiguration() .toMap()); config.addAll(pythonDriverOptions.getPythonDependencyConfig()); // start gateway server GatewayServer gatewayServer = PythonEnvUtils.startGatewayServer(); PythonEnvUtils.setGatewayServer(gatewayServer); PythonEnvUtils.PythonProcessShutdownHook shutdownHook = null; // commands which will be exec in python progress. final List<String> commands = constructPythonCommands(pythonDriverOptions); try { // prepare the exec environment of python progress. String tmpDir = System.getProperty("java.io.tmpdir") + File.separator + "pyflink" + File.separator + UUID.randomUUID(); // start the python process. Process pythonProcess = PythonEnvUtils.launchPy4jPythonClient( gatewayServer, config, commands, pythonDriverOptions.getEntryPointScript().orElse(null), tmpDir, true); shutdownHook = new PythonEnvUtils.PythonProcessShutdownHook( pythonProcess, gatewayServer, tmpDir); Runtime.getRuntime().addShutdownHook(shutdownHook); BufferedReader in = new BufferedReader( new InputStreamReader( pythonProcess.getInputStream(), StandardCharsets.UTF_8)); LOG.info( "--------------------------- Python Process Started --------------------------"); // print the python process output to stdout and log file while (true) { String line = in.readLine(); if (line == null) { break; } else { System.out.println(line); LOG.info(line); } } int exitCode = pythonProcess.waitFor(); LOG.info( "--------------------------- Python Process Exited ---------------------------"); if (exitCode != 0) { throw new RuntimeException("Python process exits with code: " + exitCode); } } catch (Throwable e) { LOG.error("Run python process failed", e); if (PythonEnvUtils.capturedJavaException != null) { throw PythonEnvUtils.capturedJavaException; } else { // throw ProgramAbortException if the caller is interested in the program plan, // there is no harm to throw ProgramAbortException even if it is not the case. throw new ProgramAbortException(e); } } finally { PythonEnvUtils.setGatewayServer(null); if (shutdownHook != null && Runtime.getRuntime().removeShutdownHook(shutdownHook)) { shutdownHook.run(); } } } /** * Constructs the Python commands which will be executed in python process. * * @param pythonDriverOptions parsed Python command options */ static List<String> constructPythonCommands(final PythonDriverOptions pythonDriverOptions) { final List<String> commands = new ArrayList<>(); // disable output buffer commands.add("-u"); if (pythonDriverOptions.getEntryPointScript().isPresent()) { commands.add(pythonDriverOptions.getEntryPointScript().get()); } else { commands.add("-m"); commands.add(pythonDriverOptions.getEntryPointModule()); } commands.addAll(pythonDriverOptions.getProgramArgs()); return commands; } }
PythonDriver
java
quarkusio__quarkus
integration-tests/oidc/src/main/java/io/quarkus/it/keycloak/UsersResource.java
{ "start": 816, "end": 1028 }
class ____ { private final String userName; User(String name) { this.userName = name; } public String getUserName() { return userName; } } }
User
java
micronaut-projects__micronaut-core
http-client-core/src/main/java/io/micronaut/http/client/ProxyRequestOptions.java
{ "start": 2196, "end": 3436 }
class ____ { private boolean retainHostHeader = false; private Builder() { } /** * Build an immutable {@link ProxyRequestOptions} with the options configured in this builder. * * @return The options */ public ProxyRequestOptions build() { return new ProxyRequestOptions(this); } /** * If {@code true}, retain the host header from the given request. If {@code false}, it will be recomputed * based on the request URI (same behavior as {@link ProxyHttpClient#proxy(io.micronaut.http.HttpRequest)}). * * @param retainHostHeader Whether to retain the host header from the proxy request instead of recomputing it * based on URL. * @return This builder. */ public Builder retainHostHeader(boolean retainHostHeader) { this.retainHostHeader = retainHostHeader; return this; } /** * Equivalent to {@link #retainHostHeader(boolean)}. * * @return This builder. */ public Builder retainHostHeader() { return retainHostHeader(true); } } }
Builder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
{ "start": 19032, "end": 19501 }
class ____<T> { // BUG: Diagnostic contains: 'T' is a mutable type variable private final T t = null; } """) .doTest(); } @Test public void transitiveSuperSubstitutionMutable() { compilationHelper .addSourceLines( "SuperMostType.java", """ import com.google.errorprone.annotations.Immutable; @Immutable(containerOf = "N") public
Test
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/validator/ValidatorBeanCallTest.java
{ "start": 1200, "end": 2756 }
class ____ extends ContextTestSupport { protected MockEndpoint validEndpoint; protected MockEndpoint invalidEndpoint; @Test public void testCallBean() throws Exception { validEndpoint.expectedMessageCount(1); invalidEndpoint.expectedMessageCount(0); template .sendBody("direct:rootPath", "<report xmlns='http://foo.com/report' xmlns:rb='http://foo.com/report-base'><author><rb:name>Knuth</rb:name></author><content><rb:chapter><rb:subject></rb:subject>" + "<rb:abstract></rb:abstract><rb:body></rb:body></rb:chapter></content></report>"); MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint); } @Override @BeforeEach public void setUp() throws Exception { super.setUp(); validEndpoint = resolveMandatoryEndpoint("mock:valid", MockEndpoint.class); invalidEndpoint = resolveMandatoryEndpoint("mock:invalid", MockEndpoint.class); } @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("myBean", new MyValidatorBean()); return jndi; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:rootPath").to("validator:bean:myBean.loadFile").to("mock:valid"); } }; } public static
ValidatorBeanCallTest
java
apache__rocketmq
filter/src/main/java/org/apache/rocketmq/filter/expression/MQFilterException.java
{ "start": 880, "end": 1532 }
class ____ extends Exception { private static final long serialVersionUID = 1L; private final int responseCode; private final String errorMessage; public MQFilterException(String errorMessage, Throwable cause) { super(cause); this.responseCode = -1; this.errorMessage = errorMessage; } public MQFilterException(int responseCode, String errorMessage) { this.responseCode = responseCode; this.errorMessage = errorMessage; } public int getResponseCode() { return responseCode; } public String getErrorMessage() { return errorMessage; } }
MQFilterException
java
apache__flink
flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarRunRequestBodyTest.java
{ "start": 1373, "end": 2911 }
class ____ extends RestRequestMarshallingTestBase<JarRunRequestBody> { @Override protected Class<JarRunRequestBody> getTestRequestClass() { return JarRunRequestBody.class; } @Override protected JarRunRequestBody getTestRequestInstance() { return new JarRunRequestBody( "hello", Arrays.asList("boo", "far"), 4, new JobID(), true, "foo/bar", RecoveryClaimMode.CLAIM, Collections.singletonMap("key", "value")); } @Override protected void assertOriginalEqualsToUnmarshalled( final JarRunRequestBody expected, final JarRunRequestBody actual) { assertThat(actual.getEntryClassName()).isEqualTo(expected.getEntryClassName()); assertThat(actual.getProgramArgumentsList()).isEqualTo(expected.getProgramArgumentsList()); assertThat(actual.getParallelism()).isEqualTo(expected.getParallelism()); assertThat(actual.getJobId()).isEqualTo(expected.getJobId()); assertThat(actual.getAllowNonRestoredState()) .isEqualTo(expected.getAllowNonRestoredState()); assertThat(actual.getSavepointPath()).isEqualTo(expected.getSavepointPath()); assertThat(actual.getRecoveryClaimMode()).isEqualTo(expected.getRecoveryClaimMode()); assertThat(actual.getFlinkConfiguration().toMap()) .containsExactlyEntriesOf(expected.getFlinkConfiguration().toMap()); } }
JarRunRequestBodyTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryDefaultInEnumSwitchTest.java
{ "start": 33850, "end": 34315 }
enum ____ { ONE, TWO, } boolean m(Case c) { return switch (c) { case ONE -> true; case TWO -> false; }; } } """) .doTest(); } @Test public void expressionSwitchUnrecognized() { refactoringTestHelper .addInputLines( "in/Test.java", """
Case
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
{ "start": 2656, "end": 3298 }
class ____ a * heartbeat request using the state stored in the membership manager. The requests can be retrieved * by calling {@link StreamsGroupHeartbeatRequestManager#poll(long)}. Once the response is received, it updates the * state in the membership manager and handles any errors. * * <p>The heartbeat manager generates heartbeat requests based on the member state. It's also responsible * for the timing of the heartbeat requests to ensure they are sent according to the heartbeat interval * (while the member state is stable) or on demand (while the member is acknowledging an assignment or * leaving the group). */ public
creates
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/operator/AsyncOperatorTests.java
{ "start": 2412, "end": 7398 }
class ____ extends ESTestCase { private TestThreadPool threadPool; private static final String ESQL_TEST_EXECUTOR = "esql_test_executor"; @Before public void setThreadPool() { int numThreads = randomBoolean() ? 1 : between(2, 16); threadPool = new TestThreadPool( "test", new FixedExecutorBuilder(Settings.EMPTY, ESQL_TEST_EXECUTOR, numThreads, 1024, "esql", EsExecutors.TaskTrackingConfig.DEFAULT) ); } @After public void shutdownThreadPool() { terminate(threadPool); } public void testBasic() { BlockFactory globalBlockFactory = blockFactory(); LocalCircuitBreaker localBreaker = null; final DriverContext driverContext; if (randomBoolean()) { localBreaker = new LocalCircuitBreaker(globalBlockFactory.breaker(), between(0, 1024), between(0, 4096)); BlockFactory localFactory = globalBlockFactory.newChildFactory(localBreaker); driverContext = new DriverContext(globalBlockFactory.bigArrays(), localFactory); } else { driverContext = new DriverContext(globalBlockFactory.bigArrays(), globalBlockFactory); } int positions = randomIntBetween(0, 10_000); List<Long> ids = new ArrayList<>(positions); Map<Long, String> dict = new HashMap<>(); for (int i = 0; i < positions; i++) { long id = randomLong(); ids.add(id); if (randomBoolean()) { dict.computeIfAbsent(id, k -> randomAlphaOfLength(5)); } } SourceOperator sourceOperator = new AbstractBlockSourceOperator(driverContext.blockFactory(), randomIntBetween(10, 1000)) { @Override protected int remaining() { return ids.size() - currentPosition; } @Override protected Page createPage(int positionOffset, int length) { try (LongVector.Builder builder = blockFactory.newLongVectorBuilder(length)) { for (int i = 0; i < length; i++) { builder.appendLong(ids.get(currentPosition++)); } return new Page(builder.build().asBlock()); } } }; int maxConcurrentRequests = randomIntBetween(1, 10); AsyncOperator<Page> asyncOperator = new AsyncOperator<Page>(driverContext, threadPool.getThreadContext(), maxConcurrentRequests) { final LookupService lookupService = new LookupService(threadPool, globalBlockFactory, dict, maxConcurrentRequests); @Override protected void performAsync(Page inputPage, ActionListener<Page> listener) { lookupService.lookupAsync(inputPage, listener); } @Override public Page getOutput() { return fetchFromBuffer(); } @Override protected void releaseFetchedOnAnyThread(Page page) { releasePageOnAnyThread(page); } @Override public void doClose() { } }; List<Operator> intermediateOperators = new ArrayList<>(); intermediateOperators.add(asyncOperator); final Iterator<Long> it; if (randomBoolean()) { int limit = between(0, ids.size()); it = ids.subList(0, limit).iterator(); intermediateOperators.add(new LimitOperator(new Limiter(limit))); } else { it = ids.iterator(); } SinkOperator outputOperator = new PageConsumerOperator(page -> { try (Releasable ignored = page::releaseBlocks) { assertThat(page.getBlockCount(), equalTo(2)); LongBlock b1 = page.getBlock(0); BytesRefBlock b2 = page.getBlock(1); BytesRef scratch = new BytesRef(); for (int i = 0; i < page.getPositionCount(); i++) { assertTrue(it.hasNext()); long key = b1.getLong(i); assertThat(key, equalTo(it.next())); String v = dict.get(key); if (v == null) { assertTrue(b2.isNull(i)); } else { assertThat(b2.getBytesRef(i, scratch), equalTo(new BytesRef(v))); } } } }); PlainActionFuture<Void> future = new PlainActionFuture<>(); Driver driver = TestDriverFactory.create( driverContext, sourceOperator, intermediateOperators, outputOperator, () -> assertFalse(it.hasNext()) ); Driver.start(threadPool.getThreadContext(), threadPool.executor(ESQL_TEST_EXECUTOR), driver, between(1, 10000), future); future.actionGet(); Releasables.close(localBreaker); }
AsyncOperatorTests
java
quarkusio__quarkus
integration-tests/spring-data-jpa/src/main/java/io/quarkus/it/spring/data/jpa/EmployeeResource.java
{ "start": 270, "end": 1674 }
class ____ { private final EmployeeRepository employeeRepository; public EmployeeResource(EmployeeRepository employeeRepository) { this.employeeRepository = employeeRepository; } @GET public List<Employee> findAll() { return this.employeeRepository.findAll(); } @GET @Path("/{id}") public Employee findById(@PathParam("id") Long id) { return this.employeeRepository.findById(id).orElse(null); } @GET @Path("/unit/{orgUnitName}") public List<Employee> findByManagerOfManager(@PathParam("orgUnitName") String orgUnitName) { return this.employeeRepository.findByBelongsToTeamOrganizationalUnitName(orgUnitName); } @GET @Path("/search") public List<Employee> findByLastNameContainingAndFirstNameContainingAndEmailContainingAllIgnoreCase( @QueryParam("first") String firstName, @QueryParam("last") String lastName, @QueryParam("email") String email) { return this.employeeRepository.findByLastNameContainingAndFirstNameContainingAndEmailContainingAllIgnoreCase(lastName, firstName, email); } @GET @Path("/search-first-2") public List<Employee> findTop2ByFirstNameContainingAllIgnoreCase(@QueryParam("first") String firstName) { return this.employeeRepository.findFirst2ByFirstNameContainingIgnoreCaseOrderById(firstName); } }
EmployeeResource
java
quarkusio__quarkus
integration-tests/jpa-db2/src/main/java/io/quarkus/it/jpa/db2/SequencedAddress.java
{ "start": 200, "end": 894 }
class ____ { private long id; private String street; public SequencedAddress() { } public SequencedAddress(String street) { this.street = street; } @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "addressSeq") public long getId() { return id; } public void setId(long id) { this.id = id; } public String getStreet() { return street; } public void setStreet(String name) { this.street = name; } public void describeFully(StringBuilder sb) { sb.append("Address with id=").append(id).append(", street='").append(street).append("'"); } }
SequencedAddress
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/StringSerializerTest.java
{ "start": 1078, "end": 1585 }
class ____ extends SerializerTestBase<String> { @Override protected TypeSerializer<String> createSerializer() { return new StringSerializer(); } @Override protected int getLength() { return -1; } @Override protected Class<String> getTypeClass() { return String.class; } @Override protected String[] getTestData() { return new String[] {"a", "", "bcd", "jbmbmner8 jhk hj \n \t üäßß@µ", "", "non-empty"}; } }
StringSerializerTest
java
apache__avro
lang/java/perf/src/main/java/org/apache/avro/perf/test/record/ValidatingRecordTest.java
{ "start": 2664, "end": 3292 }
class ____ extends BasicState { private BasicRecord[] testData; private Encoder encoder; public TestStateEncode() { super(); } /** * Setup each trial * * @throws IOException Could not setup test data */ @Setup(Level.Trial) public void doSetupTrial() throws Exception { this.encoder = super.newEncoder(false, getNullOutputStream()); this.testData = new BasicRecord[getBatchSize()]; for (int i = 0; i < testData.length; i++) { testData[i] = new BasicRecord(super.getRandom()); } } } @State(Scope.Thread) public static
TestStateEncode
java
apache__camel
components/camel-git/src/generated/java/org/apache/camel/component/git/GitComponentConfigurer.java
{ "start": 730, "end": 3486 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { GitComponent target = (GitComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": target.setHealthCheckConsumerEnabled(property(camelContext, boolean.class, value)); return true; case "healthcheckproducerenabled": case "healthCheckProducerEnabled": target.setHealthCheckProducerEnabled(property(camelContext, boolean.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": return boolean.class; case "healthcheckproducerenabled": case "healthCheckProducerEnabled": return boolean.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { GitComponent target = (GitComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": return target.isHealthCheckConsumerEnabled(); case "healthcheckproducerenabled": case "healthCheckProducerEnabled": return target.isHealthCheckProducerEnabled(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); default: return null; } } }
GitComponentConfigurer
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/discovery/DiscoveryTests.java
{ "start": 21958, "end": 22046 }
class ____ { @Test @DisplayName("\t") void test() { } }
BlankDisplayNamesTestCase
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/ExtendedCamelContext.java
{ "start": 12113, "end": 12373 }
class ____ META-INF * * @return the default factory finder * @see #getBootstrapFactoryFinder() */ FactoryFinder getDefaultFactoryFinder(); /** * Sets the default FactoryFinder which will be used for the loading the factory
from
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/parameters/converters/ListConverter.java
{ "start": 1648, "end": 2569 }
class ____ implements DelegatingParameterConverterSupplier { private ParameterConverterSupplier delegate; public ListSupplier() { } // invoked by reflection for BeanParam in ClassInjectorTransformer public ListSupplier(ParameterConverterSupplier delegate) { this.delegate = delegate; } @Override public ParameterConverter get() { return delegate == null ? new ListConverter(null) : new ListConverter(delegate.get()); } @Override public String getClassName() { return ListConverter.class.getName(); } @Override public ParameterConverterSupplier getDelegate() { return delegate; } public ListSupplier setDelegate(ParameterConverterSupplier delegate) { this.delegate = delegate; return this; } } }
ListSupplier
java
jhy__jsoup
src/test/java/org/jsoup/parser/TokenQueueTest.java
{ "start": 431, "end": 14653 }
class ____ { @Test public void chompBalanced() { TokenQueue tq = new TokenQueue(":contains(one (two) three) four"); String pre = tq.consumeTo("("); String guts = tq.chompBalanced('(', ')'); String remainder = tq.remainder(); assertEquals(":contains", pre); assertEquals("one (two) three", guts); assertEquals(" four", remainder); } @Test public void chompEscapedBalanced() { TokenQueue tq = new TokenQueue(":contains(one (two) \\( \\) \\) three) four"); String pre = tq.consumeTo("("); String guts = tq.chompBalanced('(', ')'); String remainder = tq.remainder(); assertEquals(":contains", pre); assertEquals("one (two) \\( \\) \\) three", guts); assertEquals("one (two) ( ) ) three", TokenQueue.unescape(guts)); assertEquals(" four", remainder); } @Test public void chompBalancedMatchesAsMuchAsPossible() { TokenQueue tq = new TokenQueue("unbalanced(something(or another)) else"); tq.consumeTo("("); String match = tq.chompBalanced('(', ')'); assertEquals("something(or another)", match); } @Test public void unescape() { assertEquals("one ( ) \\", TokenQueue.unescape("one \\( \\) \\\\")); } @Test public void unescape_2() { assertEquals("\\&", TokenQueue.unescape("\\\\\\&")); } @ParameterizedTest @MethodSource("escapeCssIdentifier_WebPlatformTestParameters") @MethodSource("escapeCssIdentifier_additionalParameters") public void escapeCssIdentifier(String expected, String input) { assertEquals(expected, TokenQueue.escapeCssIdentifier(input)); } // https://github.com/web-platform-tests/wpt/blob/328fa1c67bf5dfa6f24571d4c41dd10224b6d247/css/cssom/escape.html private static Stream<Arguments> escapeCssIdentifier_WebPlatformTestParameters() { return Stream.of( Arguments.of("", ""), // Null bytes Arguments.of("\uFFFD", "\0"), Arguments.of("a\uFFFD", "a\0"), Arguments.of("\uFFFDb", "\0b"), Arguments.of("a\uFFFDb", "a\0b"), // Replacement character Arguments.of("\uFFFD", "\uFFFD"), Arguments.of("a\uFFFD", "a\uFFFD"), Arguments.of("\uFFFDb", "\uFFFDb"), Arguments.of("a\uFFFDb", "a\uFFFDb"), // Number prefix Arguments.of("\\30 a", "0a"), Arguments.of("\\31 a", "1a"), Arguments.of("\\32 a", "2a"), Arguments.of("\\33 a", "3a"), Arguments.of("\\34 a", "4a"), Arguments.of("\\35 a", "5a"), Arguments.of("\\36 a", "6a"), Arguments.of("\\37 a", "7a"), Arguments.of("\\38 a", "8a"), Arguments.of("\\39 a", "9a"), // Letter number prefix Arguments.of("a0b", "a0b"), Arguments.of("a1b", "a1b"), Arguments.of("a2b", "a2b"), Arguments.of("a3b", "a3b"), Arguments.of("a4b", "a4b"), Arguments.of("a5b", "a5b"), Arguments.of("a6b", "a6b"), Arguments.of("a7b", "a7b"), Arguments.of("a8b", "a8b"), Arguments.of("a9b", "a9b"), // Dash number prefix Arguments.of("-\\30 a", "-0a"), Arguments.of("-\\31 a", "-1a"), Arguments.of("-\\32 a", "-2a"), Arguments.of("-\\33 a", "-3a"), Arguments.of("-\\34 a", "-4a"), Arguments.of("-\\35 a", "-5a"), Arguments.of("-\\36 a", "-6a"), Arguments.of("-\\37 a", "-7a"), Arguments.of("-\\38 a", "-8a"), Arguments.of("-\\39 a", "-9a"), // Double dash prefix Arguments.of("--a", "--a"), // Various tests Arguments.of("\\1 \\2 \\1e \\1f ", "\u0001\u0002\u001E\u001F"), Arguments.of("\u0080\u002D\u005F\u00A9", "\u0080\u002D\u005F\u00A9"), Arguments.of("\\7f \u0080\u0081\u0082\u0083\u0084\u0085\u0086\u0087\u0088\u0089\u008A\u008B\u008C\u008D\u008E\u008F\u0090\u0091\u0092\u0093\u0094\u0095\u0096\u0097\u0098\u0099\u009A\u009B\u009C\u009D\u009E\u009F", "\u007F\u0080\u0081\u0082\u0083\u0084\u0085\u0086\u0087\u0088\u0089\u008A\u008B\u008C\u008D\u008E\u008F\u0090\u0091\u0092\u0093\u0094\u0095\u0096\u0097\u0098\u0099\u009A\u009B\u009C\u009D\u009E\u009F"), Arguments.of("\u00A0\u00A1\u00A2", "\u00A0\u00A1\u00A2"), Arguments.of("a0123456789b", "a0123456789b"), Arguments.of("abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz"), Arguments.of("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"), Arguments.of("hello\\\\world", "hello\\world"), // Backslashes get backslash-escaped Arguments.of("hello\u1234world", "hello\u1234world"), // Code points greater than U+0080 are preserved Arguments.of("\\-", "-"), // CSS.escape: Single dash escaped Arguments.of("\\ \\!xy", "\u0020\u0021\u0078\u0079"), // astral symbol (U+1D306 TETRAGRAM FOR CENTRE) Arguments.of("\uD834\uDF06", "\uD834\uDF06"), // lone surrogates Arguments.of("\uDF06", "\uDF06"), Arguments.of("\uD834", "\uD834") ); } private static Stream<Arguments> escapeCssIdentifier_additionalParameters() { return Stream.of( Arguments.of("one\\#two\\.three\\/four\\\\five", "one#two.three/four\\five"), Arguments.of("-a", "-a"), Arguments.of("--", "--") ); } @Test public void testNestedQuotes() { validateNestedQuotes("<html><body><a id=\"identifier\" onclick=\"func('arg')\" /></body></html>", "a[onclick*=\"('arg\"]"); validateNestedQuotes("<html><body><a id=\"identifier\" onclick=func('arg') /></body></html>", "a[onclick*=\"('arg\"]"); validateNestedQuotes("<html><body><a id=\"identifier\" onclick='func(\"arg\")' /></body></html>", "a[onclick*='(\"arg']"); validateNestedQuotes("<html><body><a id=\"identifier\" onclick=func(\"arg\") /></body></html>", "a[onclick*='(\"arg']"); } private static void validateNestedQuotes(String html, String selector) { assertEquals("#identifier", Jsoup.parse(html).select(selector).first().cssSelector()); } @Test public void chompBalancedThrowIllegalArgumentException() { try { TokenQueue tq = new TokenQueue("unbalanced(something(or another)) else"); tq.consumeTo("("); tq.chompBalanced('(', '+'); fail("should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertEquals("Did not find balanced marker at 'something(or another)) else'", expected.getMessage()); } } @Test public void testQuotedPattern() { final Document doc = Jsoup.parse("<div>\\) foo1</div><div>( foo2</div><div>1) foo3</div>"); assertEquals("\\) foo1",doc.select("div:matches(" + Pattern.quote("\\)") + ")").get(0).childNode(0).toString()); assertEquals("( foo2",doc.select("div:matches(" + Pattern.quote("(") + ")").get(0).childNode(0).toString()); assertEquals("1) foo3",doc.select("div:matches(" + Pattern.quote("1)") + ")").get(0).childNode(0).toString()); } @Test public void consumeEscapedTag() { TokenQueue q = new TokenQueue("p\\\\p p\\.p p\\:p p\\!p"); assertEquals("p\\p", q.consumeElementSelector()); assertTrue(q.consumeWhitespace()); assertEquals("p.p", q.consumeElementSelector()); assertTrue(q.consumeWhitespace()); assertEquals("p:p", q.consumeElementSelector()); assertTrue(q.consumeWhitespace()); assertEquals("p!p", q.consumeElementSelector()); assertTrue(q.isEmpty()); } @Test public void consumeEscapedId() { TokenQueue q = new TokenQueue("i\\.d i\\\\d"); assertEquals("i.d", q.consumeCssIdentifier()); assertTrue(q.consumeWhitespace()); assertEquals("i\\d", q.consumeCssIdentifier()); assertTrue(q.isEmpty()); } @Test void escapeAtEof() { TokenQueue q = new TokenQueue("Foo\\"); String s = q.consumeElementSelector(); assertEquals("Foo", s); // no escape, no eof. Just straight up Foo. } @ParameterizedTest @MethodSource("cssIdentifiers") @MethodSource("cssAdditionalIdentifiers") void consumeCssIdentifier_WebPlatformTests(String expected, String cssIdentifier) { assertParsedCssIdentifierEquals(expected, cssIdentifier); } private static Stream<Arguments> cssIdentifiers() { return Stream.of( // https://github.com/web-platform-tests/wpt/blob/36036fb5212a3fc15fc5750cecb1923ba4071668/dom/nodes/ParentNode-querySelector-escapes.html // - escape hex digit Arguments.of("0nextIsWhiteSpace", "\\30 nextIsWhiteSpace"), Arguments.of("0nextIsNotHexLetters", "\\30nextIsNotHexLetters"), Arguments.of("0connectHexMoreThan6Hex", "\\000030connectHexMoreThan6Hex"), Arguments.of("0spaceMoreThan6Hex", "\\000030 spaceMoreThan6Hex"), // - hex digit special replacement // 1. zero points Arguments.of("zero\uFFFD", "zero\\0"), Arguments.of("zero\uFFFD", "zero\\000000"), // 2. surrogate points Arguments.of("\uFFFDsurrogateFirst", "\\d83d surrogateFirst"), Arguments.of("surrogateSecond\uFFFd", "surrogateSecond\\dd11"), Arguments.of("surrogatePair\uFFFD\uFFFD", "surrogatePair\\d83d\\dd11"), // 3. out of range points Arguments.of("outOfRange\uFFFD", "outOfRange\\110000"), Arguments.of("outOfRange\uFFFD", "outOfRange\\110030"), Arguments.of("outOfRange\uFFFD", "outOfRange\\555555"), Arguments.of("outOfRange\uFFFD", "outOfRange\\ffffff"), // - escape anything else Arguments.of(".comma", "\\.comma"), Arguments.of("-minus", "\\-minus"), Arguments.of("g", "\\g"), // non edge cases Arguments.of("aBMPRegular", "\\61 BMPRegular"), Arguments.of("\uD83D\uDD11nonBMP", "\\1f511 nonBMP"), Arguments.of("00continueEscapes", "\\30\\30 continueEscapes"), Arguments.of("00continueEscapes", "\\30 \\30 continueEscapes"), Arguments.of("continueEscapes00", "continueEscapes\\30 \\30 "), Arguments.of("continueEscapes00", "continueEscapes\\30 \\30"), Arguments.of("continueEscapes00", "continueEscapes\\30\\30 "), Arguments.of("continueEscapes00", "continueEscapes\\30\\30"), // ident tests case from CSS tests of chromium source: https://goo.gl/3Cxdov Arguments.of("hello", "hel\\6Co"), Arguments.of("&B", "\\26 B"), Arguments.of("hello", "hel\\6C o"), Arguments.of("spaces", "spac\\65\r\ns"), Arguments.of("spaces", "sp\\61\tc\\65\fs"), Arguments.of("test\uD799", "test\\D799"), Arguments.of("\uE000", "\\E000"), Arguments.of("test", "te\\s\\t"), Arguments.of("spaces in\tident", "spaces\\ in\\\tident"), Arguments.of(".,:!", "\\.\\,\\:\\!"), Arguments.of("null\uFFFD", "null\\0"), Arguments.of("null\uFFFD", "null\\0000"), Arguments.of("large\uFFFD", "large\\110000"), Arguments.of("large\uFFFD", "large\\23456a"), Arguments.of("surrogate\uFFFD", "surrogate\\D800"), Arguments.of("surrogate\uFFFD", "surrogate\\0DBAC"), Arguments.of("\uFFFDsurrogate", "\\00DFFFsurrogate"), Arguments.of("\uDBFF\uDFFF", "\\10fFfF"), Arguments.of("\uDBFF\uDFFF0", "\\10fFfF0"), Arguments.of("\uDBC0\uDC0000", "\\10000000"), Arguments.of("eof\uFFFD", "eof\\"), Arguments.of("simple-ident", "simple-ident"), Arguments.of("testing123", "testing123"), Arguments.of("_underscore", "_underscore"), Arguments.of("-text", "-text"), Arguments.of("-m", "-\\6d"), Arguments.of("--abc", "--abc"), Arguments.of("--", "--"), Arguments.of("--11", "--11"), Arguments.of("---", "---"), Arguments.of("\u2003", "\u2003"), Arguments.of("\u00A0", "\u00A0"), Arguments.of("\u1234", "\u1234"), Arguments.of("\uD808\uDF45", "\uD808\uDF45"), Arguments.of("\uFFFD", "\u0000"), Arguments.of("ab\uFFFDc", "ab\u0000c") ); } private static Stream<Arguments> cssAdditionalIdentifiers() { return Stream.of( Arguments.of("1st", "\\31\r\nst"), Arguments.of("1", "\\31\r"), Arguments.of("1a", "\\31\ra"), Arguments.of("1", "\\031"), Arguments.of("1", "\\0031"), Arguments.of("1", "\\00031"), Arguments.of("1", "\\000031"), Arguments.of("1", "\\000031"), Arguments.of("a", "a\\\nb") ); } @Test void consumeCssIdentifierWithEmptyInput() { TokenQueue emptyQueue = new TokenQueue(""); Exception exception = assertThrows(IllegalArgumentException.class, emptyQueue::consumeCssIdentifier); assertEquals("CSS identifier expected, but end of input found", exception.getMessage()); } // Some of jsoup's tests depend on this behavior @Test public void consumeCssIdentifier_invalidButSupportedForBackwardsCompatibility() { assertParsedCssIdentifierEquals("1", "1"); assertParsedCssIdentifierEquals("-", "-"); assertParsedCssIdentifierEquals("-1", "-1"); } private static String parseCssIdentifier(String text) { TokenQueue q = new TokenQueue(text); return q.consumeCssIdentifier(); } private void assertParsedCssIdentifierEquals(String expected, String cssIdentifier) { assertEquals(expected, parseCssIdentifier(cssIdentifier)); } }
TokenQueueTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/functional/LazyAtomicReference.java
{ "start": 1799, "end": 3660 }
class ____<T> implements CallableRaisingIOE<T>, Supplier<T> { /** * Underlying reference. */ private final AtomicReference<T> reference = new AtomicReference<>(); /** * Constructor for lazy creation. */ private final CallableRaisingIOE<? extends T> constructor; /** * Constructor for this instance. * @param constructor method to invoke to actually construct the inner object. */ public LazyAtomicReference(final CallableRaisingIOE<? extends T> constructor) { this.constructor = requireNonNull(constructor); } /** * Getter for the constructor. * @return the constructor class */ protected CallableRaisingIOE<? extends T> getConstructor() { return constructor; } /** * Get the reference. * Subclasses working with this need to be careful working with this. * @return the reference. */ protected AtomicReference<T> getReference() { return reference; } /** * Get the value, constructing it if needed. * @return the value * @throws IOException on any evaluation failure * @throws NullPointerException if the evaluated function returned null. */ public synchronized T eval() throws IOException { final T v = reference.get(); if (v != null) { return v; } reference.set(requireNonNull(constructor.apply())); return reference.get(); } /** * Implementation of {@code CallableRaisingIOE.apply()}. * Invoke {@link #eval()}. * @return the value * @throws IOException on any evaluation failure */ @Override public final T apply() throws IOException { return eval(); } /** * Implementation of {@code Supplier.get()}. * <p> * Invoke {@link #eval()} and convert IOEs to * UncheckedIOException. * <p> * This is the {@code Supplier.get()} implementation, which allows * this
LazyAtomicReference
java
quarkusio__quarkus
independent-projects/qute/core/src/main/java/io/quarkus/qute/Qute.java
{ "start": 8506, "end": 10839 }
class ____ implements ParserHook { private final Pattern p = Pattern.compile("\\{\\}"); private final String prefix; public IndexedArgumentsParserHook() { this(TEMPLATE_PREFIX); } public IndexedArgumentsParserHook(String prefix) { this.prefix = prefix; } @Override public void beforeParsing(ParserHelper parserHelper) { if (prefix != null && !parserHelper.getTemplateId().startsWith(prefix)) { return; } parserHelper.addContentFilter(new Function<String, String>() { @Override public String apply(String input) { if (!input.contains("{}")) { return input; } // Find all empty expressions and turn them into index-based expressions // e.g. "Hello {} and {}!" turns into "Hello {data.0} and {data.1}!" StringBuilder builder = new StringBuilder(); Matcher m = p.matcher(input); int idx = 0; while (m.find()) { m.appendReplacement(builder, "{data." + idx + "}"); idx++; } m.appendTail(builder); return builder.toString(); } }); } } private static volatile Engine engine; private static volatile boolean cacheByDefault; private static final Map<Hash, Template> CACHE = new ConcurrentHashMap<>(); private static final Variant PLAIN_TEXT = Variant.forContentType(Variant.TEXT_PLAIN); private static final AtomicLong ID_GENERATOR = new AtomicLong(0); /* Internals */ private static final String TEMPLATE_PREFIX = "Qute$$"; private static String newId() { return TEMPLATE_PREFIX + ID_GENERATOR.incrementAndGet(); } private static Hash hashKey(String value) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); return new Hash(md.digest(value.getBytes(StandardCharsets.UTF_8))); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } private static final
IndexedArgumentsParserHook
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDropTest2.java
{ "start": 784, "end": 1264 }
class ____ extends TestCase { private String sql = "DROP PROCEDURE IF EXISTS CP_PayCalc1"; private WallConfig config = new WallConfig(); protected void setUp() throws Exception { config.setDropTableAllow(true); } public void testMySql() throws Exception { assertTrue(WallUtils.isValidateMySql(sql, config)); } public void testORACLE() throws Exception { assertTrue(WallUtils.isValidateOracle(sql, config)); } }
WallDropTest2
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/functional/RemoteIterators.java
{ "start": 15525, "end": 16416 }
class ____<S, T> extends WrappingRemoteIterator<S, T> { /** * Mapper to invoke. */ private final FunctionRaisingIOE<? super S, T> mapper; private MappingRemoteIterator( RemoteIterator<S> source, FunctionRaisingIOE<? super S, T> mapper) { super(source); this.mapper = requireNonNull(mapper); } @Override public boolean hasNext() throws IOException { return sourceHasNext(); } @Override public T next() throws IOException { return mapper.apply(sourceNext()); } @Override public String toString() { return "FunctionRemoteIterator{" + getSource() + '}'; } } /** * RemoteIterator which can change the type of the input. * This is useful in some situations. * @param <S> source type * @param <T> final output type. */ private static final
MappingRemoteIterator
java
google__dagger
javatests/dagger/internal/codegen/DaggerSuperficialValidationTest.java
{ "start": 28047, "end": 28188 }
class ____ extends MissingType {}"), CompilerTests.kotlinSource( "test.Foo.kt", "package test;", "
Baz
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/refactor/AddWhere_0.java
{ "start": 359, "end": 3137 }
class ____ extends TestCase { public void test_select_0() throws Exception { String sql = "select * from t"; SQLSelectStatement stmt = (SQLSelectStatement) SQLUtils.parseStatements(sql, JdbcConstants.MYSQL).get(0); stmt.addWhere(SQLUtils.toSQLExpr("id = 1", JdbcConstants.MYSQL)); assertEquals("SELECT *\n" + "FROM t\n" + "WHERE id = 1", stmt.toString()); } public void test_select_1() throws Exception { String sql = "select * from t where name = 'xx'"; SQLSelectStatement stmt = (SQLSelectStatement) SQLUtils.parseStatements(sql, JdbcConstants.MYSQL).get(0); stmt.addWhere(SQLUtils.toSQLExpr("id = 1", JdbcConstants.MYSQL)); assertEquals("SELECT *\n" + "FROM t\n" + "WHERE name = 'xx'\n" + "\tAND id = 1", stmt.toString()); } public void test_select_1_union() throws Exception { String sql = "select * from t1 union all select * from t2"; SQLSelectStatement stmt = (SQLSelectStatement) SQLUtils.parseStatements(sql, JdbcConstants.MYSQL).get(0); stmt.addWhere(SQLUtils.toSQLExpr("id = 1", JdbcConstants.MYSQL)); assertEquals("SELECT *\n" + "FROM (\n" + "\tSELECT *\n" + "\tFROM t1\n" + "\tUNION ALL\n" + "\tSELECT *\n" + "\tFROM t2\n" + ") u", stmt.toString()); } public void test_delete_0() throws Exception { String sql = "delete from t"; SQLDeleteStatement stmt = (SQLDeleteStatement) SQLUtils.parseStatements(sql, JdbcConstants.MYSQL).get(0); stmt.addWhere(SQLUtils.toSQLExpr("id = 1", JdbcConstants.MYSQL)); assertEquals("DELETE FROM t\n" + "WHERE id = 1", stmt.toString()); } public void test_delete_1() throws Exception { String sql = "delete from t where name = 'xx'"; SQLDeleteStatement stmt = (SQLDeleteStatement) SQLUtils.parseStatements(sql, JdbcConstants.MYSQL).get(0); stmt.addWhere(SQLUtils.toSQLExpr("id = 1", JdbcConstants.MYSQL)); assertEquals("DELETE FROM t\n" + "WHERE name = 'xx'\n" + "\tAND id = 1", stmt.toString()); } public void test_update_0() throws Exception { String sql = "update t set val = 'abc' where name = 'xx'"; SQLUpdateStatement stmt = (SQLUpdateStatement) SQLUtils.parseStatements(sql, JdbcConstants.MYSQL).get(0); stmt.addWhere(SQLUtils.toSQLExpr("id = 1", JdbcConstants.MYSQL)); assertEquals("UPDATE t\n" + "SET val = 'abc'\n" + "WHERE name = 'xx'\n" + "\tAND id = 1", stmt.toString()); } }
AddWhere_0