language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/CustomContextPathErrorPageTests.java
{ "start": 1333, "end": 1461 }
class ____ extends AbstractErrorPageTests { CustomContextPathErrorPageTests() { super(""); } }
CustomContextPathErrorPageTests
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/table/AsyncCalcITCase.java
{ "start": 16698, "end": 17063 }
class ____<T> extends AsyncFuncBase { private static final long serialVersionUID = 3L; abstract void finish(T future, int param); public void eval(T future, Integer param) { executor.schedule(() -> finish(future, param), 10, TimeUnit.MILLISECONDS); } } /** Test function. */ public static
AsyncFuncMoreGeneric
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/NestedRowProcessingState.java
{ "start": 920, "end": 4922 }
class ____ extends BaseExecutionContext implements RowProcessingState { private final AggregateEmbeddableInitializerImpl aggregateEmbeddableInitializer; final RowProcessingState processingState; public NestedRowProcessingState( AggregateEmbeddableInitializerImpl aggregateEmbeddableInitializer, RowProcessingState processingState) { super( processingState.getSession() ); this.aggregateEmbeddableInitializer = aggregateEmbeddableInitializer; this.processingState = processingState; } public static NestedRowProcessingState wrap( AggregateEmbeddableInitializerImpl aggregateEmbeddableInitializer, RowProcessingState processingState) { if ( processingState instanceof NestedRowProcessingState nestedRowProcessingState ) { return new NestedRowProcessingState( aggregateEmbeddableInitializer, nestedRowProcessingState.processingState ); } return new NestedRowProcessingState( aggregateEmbeddableInitializer, processingState ); } @Override public Object getJdbcValue(int position) { final Object[] jdbcValue = aggregateEmbeddableInitializer.getJdbcValues( processingState ); return jdbcValue == null ? null : jdbcValue[position]; } @Override public RowProcessingState unwrap() { return processingState; } // -- delegate the rest @Override public <T extends InitializerData> T getInitializerData(int initializerId) { return processingState.getInitializerData( initializerId ); } @Override public void setInitializerData(int initializerId, InitializerData state) { processingState.setInitializerData( initializerId, state ); } @Override public JdbcValuesSourceProcessingState getJdbcValuesSourceProcessingState() { return processingState.getJdbcValuesSourceProcessingState(); } @Override public LockMode determineEffectiveLockMode(String alias) { return processingState.determineEffectiveLockMode( alias ); } @Override public boolean needsResolveState() { return processingState.needsResolveState(); } @Override public RowReader<?> getRowReader() { return processingState.getRowReader(); } @Override public void registerNonExists(EntityFetch fetch) { processingState.registerNonExists( fetch ); } @Override public boolean isQueryCacheHit() { return processingState.isQueryCacheHit(); } @Override public void finishRowProcessing(boolean wasAdded) { processingState.finishRowProcessing( wasAdded ); } @Override public QueryOptions getQueryOptions() { return processingState.getQueryOptions(); } @Override public QueryParameterBindings getQueryParameterBindings() { return processingState.getQueryParameterBindings(); } @Override public boolean isScrollResult(){ return processingState.isScrollResult(); } @Override public Callback getCallback() { return processingState.getCallback(); } @Override public boolean hasCallbackActions() { return processingState.hasCallbackActions(); } @Override public CollectionKey getCollectionKey() { return processingState.getCollectionKey(); } @Override public Object getEntityInstance() { return processingState.getEntityInstance(); } @Override public Object getEntityId() { return processingState.getEntityId(); } @Override public String getEntityUniqueKeyAttributePath() { return processingState.getEntityUniqueKeyAttributePath(); } @Override public Object getEntityUniqueKey() { return processingState.getEntityUniqueKey(); } @Override public EntityMappingType getRootEntityDescriptor() { return processingState.getRootEntityDescriptor(); } @Override public void registerLoadingEntityHolder(EntityHolder holder) { processingState.registerLoadingEntityHolder( holder ); } @Override public void afterStatement(LogicalConnectionImplementor logicalConnection) { processingState.afterStatement( logicalConnection ); } @Override public boolean hasQueryExecutionToBeAddedToStatistics() { return processingState.hasQueryExecutionToBeAddedToStatistics(); } }
NestedRowProcessingState
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/RollbackExchangeException.java
{ "start": 906, "end": 1471 }
class ____ extends CamelExchangeException { public RollbackExchangeException(Exchange exchange) { this("Intended rollback", exchange); } public RollbackExchangeException(Exchange exchange, Throwable cause) { this("Intended rollback", exchange, cause); } public RollbackExchangeException(String message, Exchange exchange) { super(message, exchange); } public RollbackExchangeException(String message, Exchange exchange, Throwable cause) { super(message, exchange, cause); } }
RollbackExchangeException
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/retention/ExpiredModelSnapshotsRemoverTests.java
{ "start": 3130, "end": 21995 }
class ____ extends ESTestCase { private Client client; private JobResultsProvider resultsProvider; private OriginSettingClient originSettingClient; private List<String> capturedJobIds; private List<DeleteByQueryRequest> capturedDeleteModelSnapshotRequests; private TestListener listener; @Before public void setUpTests() { capturedJobIds = new ArrayList<>(); capturedDeleteModelSnapshotRequests = new ArrayList<>(); client = mock(Client.class); originSettingClient = MockOriginSettingClient.mockOriginSettingClient(client, ClientHelper.ML_ORIGIN); resultsProvider = mock(JobResultsProvider.class); listener = new TestListener(); } public void testRemove_GivenJobWithoutActiveSnapshot() throws IOException { List<Job> jobs = Collections.singletonList(JobTests.buildJobBuilder("foo").setModelSnapshotRetentionDays(7L).build()); List<SearchResponse> responses = Collections.singletonList( AbstractExpiredJobDataRemoverTests.createSearchResponse(Collections.emptyList()) ); givenClientRequestsSucceed(responses, Collections.emptyMap()); createExpiredModelSnapshotsRemover(jobs.iterator()).remove(1.0f, listener, () -> false); listener.waitToCompletion(); assertThat(listener.success, is(true)); verify(client, times(1)).execute(eq(TransportSearchAction.TYPE), any(), any()); } public void testRemove_GivenJobsWithMixedRetentionPolicies() { List<SearchResponse> searchResponses = new ArrayList<>(); List<Job> jobs = Arrays.asList( JobTests.buildJobBuilder("job-1").setModelSnapshotRetentionDays(7L).setModelSnapshotId("active").build(), JobTests.buildJobBuilder("job-2").setModelSnapshotRetentionDays(17L).setModelSnapshotId("active").build() ); Date now = new Date(); Date oneDayAgo = new Date(now.getTime() - TimeValue.timeValueDays(1).getMillis()); SearchHit snapshot1_1 = createModelSnapshotQueryHit("job-1", "fresh-snapshot", oneDayAgo); searchResponses.add(AbstractExpiredJobDataRemoverTests.createSearchResponseFromHits(Collections.singletonList(snapshot1_1))); SearchHit snapshot2_1 = createModelSnapshotQueryHit("job-2", "fresh-snapshot", oneDayAgo); searchResponses.add(AbstractExpiredJobDataRemoverTests.createSearchResponseFromHits(Collections.singletonList(snapshot2_1))); // It needs to be strictly more than 7 days before the most recent snapshot, hence the extra millisecond Date eightDaysAndOneMsAgo = new Date(now.getTime() - TimeValue.timeValueDays(8).getMillis() - 1); Map<String, List<ModelSnapshot>> snapshotResponses = new HashMap<>(); snapshotResponses.put( "job-1", Arrays.asList( // Keeping active as its expiration is not known. We can assume "worst case" and verify it is not removed createModelSnapshot("job-1", "active", eightDaysAndOneMsAgo), createModelSnapshot("job-1", "old-snapshot", eightDaysAndOneMsAgo) ) ); // Retention days for job-2 is 17 days, consequently, its query should return anything as we don't ask for snapshots // created AFTER 17 days ago snapshotResponses.put("job-2", Collections.emptyList()); givenClientRequestsSucceed(searchResponses, snapshotResponses); createExpiredModelSnapshotsRemover(jobs.iterator()).remove(1.0f, listener, () -> false); listener.waitToCompletion(); assertThat(listener.success, is(true)); assertThat(capturedJobIds.size(), equalTo(2)); assertThat(capturedJobIds.get(0), equalTo("job-1")); assertThat(capturedJobIds.get(1), equalTo("job-2")); assertThat(capturedDeleteModelSnapshotRequests.size(), equalTo(1)); DeleteByQueryRequest deleteSnapshotRequest = capturedDeleteModelSnapshotRequests.get(0); assertThat( deleteSnapshotRequest.indices(), arrayContainingInAnyOrder( AnomalyDetectorsIndex.jobResultsAliasedName("job-1"), AnomalyDetectorsIndex.jobStateIndexPattern(), AnnotationIndex.READ_ALIAS_NAME ) ); assertThat(deleteSnapshotRequest.getSearchRequest().source().query() instanceof IdsQueryBuilder, is(true)); IdsQueryBuilder idsQueryBuilder = (IdsQueryBuilder) deleteSnapshotRequest.getSearchRequest().source().query(); assertTrue( "expected ids related to [old-snapshot] but received [" + idsQueryBuilder.ids() + "]", idsQueryBuilder.ids().stream().allMatch(s -> s.contains("old-snapshot")) ); } public void testRemove_GivenTimeout() throws IOException { List<SearchResponse> searchResponses = new ArrayList<>(); List<Job> jobs = Arrays.asList( JobTests.buildJobBuilder("snapshots-1").setModelSnapshotRetentionDays(7L).setModelSnapshotId("active").build(), JobTests.buildJobBuilder("snapshots-2").setModelSnapshotRetentionDays(17L).setModelSnapshotId("active").build() ); Date now = new Date(); List<ModelSnapshot> snapshots1JobSnapshots = Arrays.asList( createModelSnapshot("snapshots-1", "snapshots-1_1", now), createModelSnapshot("snapshots-1", "snapshots-1_2", now) ); List<ModelSnapshot> snapshots2JobSnapshots = Collections.singletonList(createModelSnapshot("snapshots-2", "snapshots-2_1", now)); searchResponses.add(AbstractExpiredJobDataRemoverTests.createSearchResponse(snapshots1JobSnapshots)); searchResponses.add(AbstractExpiredJobDataRemoverTests.createSearchResponse(snapshots2JobSnapshots)); HashMap<String, List<ModelSnapshot>> snapshots = new HashMap<>(); // ALl snapshots are "now" and the retention days is much longer than that. // So, getting the snapshots should return empty for both snapshots.put("snapshots-1", Collections.emptyList()); snapshots.put("snapshots-2", Collections.emptyList()); givenClientRequestsSucceed(searchResponses, snapshots); final int timeoutAfter = randomIntBetween(0, 1); AtomicInteger attemptsLeft = new AtomicInteger(timeoutAfter); createExpiredModelSnapshotsRemover(jobs.iterator()).remove(1.0f, listener, () -> (attemptsLeft.getAndDecrement() <= 0)); listener.waitToCompletion(); assertThat(listener.success, is(false)); } public void testRemove_GivenClientSearchRequestsFail() { List<SearchResponse> searchResponses = new ArrayList<>(); List<Job> jobs = Arrays.asList( JobTests.buildJobBuilder("snapshots-1").setModelSnapshotRetentionDays(7L).setModelSnapshotId("active").build(), JobTests.buildJobBuilder("snapshots-2").setModelSnapshotRetentionDays(17L).setModelSnapshotId("active").build() ); givenClientSearchRequestsFail(searchResponses, Collections.emptyMap()); createExpiredModelSnapshotsRemover(jobs.iterator()).remove(1.0f, listener, () -> false); listener.waitToCompletion(); assertThat(listener.success, is(false)); assertThat(capturedDeleteModelSnapshotRequests.size(), equalTo(0)); } public void testRemove_GivenClientDeleteSnapshotRequestsFail() { List<SearchResponse> searchResponses = new ArrayList<>(); List<Job> jobs = Arrays.asList( JobTests.buildJobBuilder("snapshots-1").setModelSnapshotRetentionDays(7L).setModelSnapshotId("active").build(), JobTests.buildJobBuilder("snapshots-2").setModelSnapshotRetentionDays(17L).setModelSnapshotId("active").build() ); Date now = new Date(); Date oneDayAgo = new Date(new Date().getTime() - TimeValue.timeValueDays(1).getMillis()); Date eightDaysAndOneMsAgo = new Date(now.getTime() - TimeValue.timeValueDays(8).getMillis() - 1); SearchHit snapshot1_1 = createModelSnapshotQueryHit("snapshots-1", "snapshots-1_1", oneDayAgo); searchResponses.add(AbstractExpiredJobDataRemoverTests.createSearchResponseFromHits(Collections.singletonList(snapshot1_1))); Map<String, List<ModelSnapshot>> snapshots = new HashMap<>(); // Should only return the one from 8 days ago snapshots.put("snapshots-1", Collections.singletonList(createModelSnapshot("snapshots-1", "snapshots-1_2", eightDaysAndOneMsAgo))); // Shouldn't return anything as retention is 17 days snapshots.put("snapshots-2", Collections.emptyList()); SearchHit snapshot2_2 = createModelSnapshotQueryHit("snapshots-2", "snapshots-2_1", eightDaysAndOneMsAgo); searchResponses.add(AbstractExpiredJobDataRemoverTests.createSearchResponseFromHits(Collections.singletonList(snapshot2_2))); givenClientDeleteModelSnapshotRequestsFail(searchResponses, snapshots); createExpiredModelSnapshotsRemover(jobs.iterator()).remove(1.0f, listener, () -> false); listener.waitToCompletion(); assertThat(listener.success, is(false)); assertThat(capturedJobIds.size(), equalTo(1)); assertThat(capturedJobIds.get(0), equalTo("snapshots-1")); assertThat(capturedDeleteModelSnapshotRequests.size(), equalTo(1)); DeleteByQueryRequest deleteSnapshotRequest = capturedDeleteModelSnapshotRequests.get(0); assertThat( deleteSnapshotRequest.indices(), arrayContainingInAnyOrder( AnomalyDetectorsIndex.jobResultsAliasedName("snapshots-1"), AnomalyDetectorsIndex.jobStateIndexPattern(), AnnotationIndex.READ_ALIAS_NAME ) ); assertThat(deleteSnapshotRequest.getSearchRequest().source().query() instanceof IdsQueryBuilder, is(true)); IdsQueryBuilder idsQueryBuilder = (IdsQueryBuilder) deleteSnapshotRequest.getSearchRequest().source().query(); assertTrue( "expected ids related to [snapshots-1_2] but received [" + idsQueryBuilder.ids() + "]", idsQueryBuilder.ids().stream().allMatch(s -> s.contains("snapshots-1_2")) ); } @SuppressWarnings("unchecked") public void testCalcCutoffEpochMs() { List<SearchResponse> searchResponses = new ArrayList<>(); Date oneDayAgo = new Date(new Date().getTime() - TimeValue.timeValueDays(1).getMillis()); SearchHit snapshot1_1 = createModelSnapshotQueryHit("job-1", "newest-snapshot", oneDayAgo); searchResponses.add(AbstractExpiredJobDataRemoverTests.createSearchResponseFromHits(Collections.singletonList(snapshot1_1))); givenClientRequests( searchResponses, true, true, Collections.singletonMap("job-1", Collections.singletonList(createModelSnapshot("job-1", "newest-snapshot", oneDayAgo))) ); long retentionDays = 3L; ActionListener<AbstractExpiredJobDataRemover.CutoffDetails> cutoffListener = mock(ActionListener.class); when(cutoffListener.delegateFailureAndWrap(any())).thenCallRealMethod(); createExpiredModelSnapshotsRemover(Collections.emptyIterator()).calcCutoffEpochMs("job-1", retentionDays, cutoffListener); long dayInMills = 60 * 60 * 24 * 1000; long expectedCutoffTime = oneDayAgo.getTime() - (dayInMills * retentionDays); verify(cutoffListener).onResponse(eq(new AbstractExpiredJobDataRemover.CutoffDetails(oneDayAgo.getTime(), expectedCutoffTime))); } public void testRemove_GivenIndexNotWritable_ShouldHandleGracefully() { List<SearchResponse> searchResponses = new ArrayList<>(); List<Job> jobs = Arrays.asList( JobTests.buildJobBuilder("job-1").setModelSnapshotRetentionDays(7L).setModelSnapshotId("active").build() ); Date now = new Date(); Date oneDayAgo = new Date(now.getTime() - TimeValue.timeValueDays(1).getMillis()); SearchHit snapshot1 = createModelSnapshotQueryHit("job-1", "fresh-snapshot", oneDayAgo); searchResponses.add(AbstractExpiredJobDataRemoverTests.createSearchResponseFromHits(Collections.singletonList(snapshot1))); Date eightDaysAndOneMsAgo = new Date(now.getTime() - TimeValue.timeValueDays(8).getMillis() - 1); Map<String, List<ModelSnapshot>> snapshotResponses = new HashMap<>(); snapshotResponses.put( "job-1", Arrays.asList( // Keeping active as its expiration is not known. We can assume "worst case" and verify it is not removed createModelSnapshot("job-1", "active", eightDaysAndOneMsAgo), createModelSnapshot("job-1", "old-snapshot", eightDaysAndOneMsAgo) ) ); givenClientRequestsSucceed(searchResponses, snapshotResponses); // Create remover with state index not writable createExpiredModelSnapshotsRemover(jobs.iterator(), false).remove(1.0f, listener, () -> false); listener.waitToCompletion(); // Should succeed, but not attempt to delete anything assertThat(listener.success, is(true)); assertThat(capturedDeleteModelSnapshotRequests.size(), equalTo(0)); } private ExpiredModelSnapshotsRemover createExpiredModelSnapshotsRemover(Iterator<Job> jobIterator) { return createExpiredModelSnapshotsRemover(jobIterator, true); } private ExpiredModelSnapshotsRemover createExpiredModelSnapshotsRemover(Iterator<Job> jobIterator, boolean isStateIndexWritable) { ThreadPool threadPool = mock(ThreadPool.class); ExecutorService executor = mock(ExecutorService.class); when(threadPool.executor(eq(MachineLearning.UTILITY_THREAD_POOL_NAME))).thenReturn(executor); doAnswer(invocationOnMock -> { Runnable run = (Runnable) invocationOnMock.getArguments()[0]; run.run(); return null; }).when(executor).execute(any()); MockWritableIndexExpander.create(isStateIndexWritable); return new ExpiredModelSnapshotsRemover( originSettingClient, jobIterator, new TaskId("test", 0L), threadPool, resultsProvider, mock(AnomalyDetectionAuditor.class) ); } private static ModelSnapshot createModelSnapshot(String jobId, String snapshotId, Date date) { return new ModelSnapshot.Builder(jobId).setSnapshotId(snapshotId).setTimestamp(date).build(); } private static SearchHit createModelSnapshotQueryHit(String jobId, String snapshotId, Date date) { SearchHitBuilder hitBuilder = new SearchHitBuilder(0); hitBuilder.addField(Job.ID.getPreferredName(), Collections.singletonList(jobId)); hitBuilder.addField(ModelSnapshotField.SNAPSHOT_ID.getPreferredName(), Collections.singletonList(snapshotId)); String dateAsString = Long.valueOf(date.getTime()).toString(); hitBuilder.addField(ModelSnapshot.TIMESTAMP.getPreferredName(), Collections.singletonList(dateAsString)); return hitBuilder.build(); } private void givenClientRequestsSucceed(List<SearchResponse> searchResponses, Map<String, List<ModelSnapshot>> snapshots) { givenClientRequests(searchResponses, true, true, snapshots); } private void givenClientSearchRequestsFail(List<SearchResponse> searchResponses, Map<String, List<ModelSnapshot>> snapshots) { givenClientRequests(searchResponses, false, true, snapshots); } private void givenClientDeleteModelSnapshotRequestsFail( List<SearchResponse> searchResponses, Map<String, List<ModelSnapshot>> snapshots ) { givenClientRequests(searchResponses, true, false, snapshots); } @SuppressWarnings("unchecked") private void givenClientRequests( List<SearchResponse> searchResponses, boolean shouldSearchRequestsSucceed, boolean shouldDeleteSnapshotRequestsSucceed, Map<String, List<ModelSnapshot>> snapshots ) { doAnswer(new Answer<Void>() { final AtomicInteger callCount = new AtomicInteger(); @Override public Void answer(InvocationOnMock invocationOnMock) { ActionListener<SearchResponse> listener = (ActionListener<SearchResponse>) invocationOnMock.getArguments()[2]; // Only the last search request should fail if (shouldSearchRequestsSucceed || callCount.get() < (searchResponses.size() + snapshots.size())) { SearchResponse response = searchResponses.get(callCount.getAndIncrement()); listener.onResponse(response); } else { listener.onFailure(new RuntimeException("search failed")); } return null; } }).when(client).execute(same(TransportSearchAction.TYPE), any(), any()); doAnswer(invocationOnMock -> { capturedDeleteModelSnapshotRequests.add((DeleteByQueryRequest) invocationOnMock.getArguments()[1]); ActionListener<AcknowledgedResponse> listener = (ActionListener<AcknowledgedResponse>) invocationOnMock.getArguments()[2]; if (shouldDeleteSnapshotRequestsSucceed) { listener.onResponse(null); } else { listener.onFailure(new RuntimeException("delete snapshot failed")); } return null; }).when(client).execute(same(DeleteByQueryAction.INSTANCE), any(), any()); for (Map.Entry<String, List<ModelSnapshot>> snapshot : snapshots.entrySet()) { doAnswer(new Answer<Void>() { final AtomicInteger callCount = new AtomicInteger(); @Override public Void answer(InvocationOnMock invocationOnMock) { capturedJobIds.add((String) invocationOnMock.getArguments()[0]); Consumer<QueryPage<ModelSnapshot>> listener = (Consumer<QueryPage<ModelSnapshot>>) invocationOnMock.getArguments()[9]; Consumer<Exception> failure = (Consumer<Exception>) invocationOnMock.getArguments()[10]; if (shouldSearchRequestsSucceed || callCount.get() < snapshots.size()) { callCount.incrementAndGet(); listener.accept(new QueryPage<>(snapshot.getValue(), 10, new ParseField("snapshots"))); } else { failure.accept(new RuntimeException("search failed")); } return null; } }).when(resultsProvider) .modelSnapshots(eq(snapshot.getKey()), anyInt(), anyInt(), any(), any(), any(), anyBoolean(), any(), any(), any(), any()); } } }
ExpiredModelSnapshotsRemoverTests
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestBlockLocation.java
{ "start": 1109, "end": 4721 }
class ____ { private static final String[] EMPTY_STR_ARRAY = new String[0]; private static final StorageType[] EMPTY_STORAGE_TYPE_ARRAY = StorageType.EMPTY_ARRAY; private static void checkBlockLocation(final BlockLocation loc) throws Exception { checkBlockLocation(loc, 0, 0, false); } private static void checkBlockLocation(final BlockLocation loc, final long offset, final long length, final boolean corrupt) throws Exception { checkBlockLocation(loc, EMPTY_STR_ARRAY, EMPTY_STR_ARRAY, EMPTY_STR_ARRAY, EMPTY_STR_ARRAY, EMPTY_STR_ARRAY, EMPTY_STORAGE_TYPE_ARRAY, offset, length, corrupt); } private static void checkBlockLocation(final BlockLocation loc, String[] names, String[] hosts, String[] cachedHosts, String[] topologyPaths, String[] storageIds, StorageType[] storageTypes, final long offset, final long length, final boolean corrupt) throws Exception { assertNotNull(loc.getHosts()); assertNotNull(loc.getCachedHosts()); assertNotNull(loc.getNames()); assertNotNull(loc.getTopologyPaths()); assertNotNull(loc.getStorageIds()); assertNotNull(loc.getStorageTypes()); assertArrayEquals(hosts, loc.getHosts()); assertArrayEquals(cachedHosts, loc.getCachedHosts()); assertArrayEquals(names, loc.getNames()); assertArrayEquals(topologyPaths, loc.getTopologyPaths()); assertArrayEquals(storageIds, loc.getStorageIds()); assertArrayEquals(storageTypes, loc.getStorageTypes()); assertEquals(offset, loc.getOffset()); assertEquals(length, loc.getLength()); assertEquals(corrupt, loc.isCorrupt()); } /** * Call all the constructors and verify the delegation is working properly */ @Test @Timeout(value = 5) public void testBlockLocationConstructors() throws Exception { // BlockLocation loc; loc = new BlockLocation(); checkBlockLocation(loc); loc = new BlockLocation(null, null, 1, 2); checkBlockLocation(loc, 1, 2, false); loc = new BlockLocation(null, null, null, 1, 2); checkBlockLocation(loc, 1, 2, false); loc = new BlockLocation(null, null, null, 1, 2, true); checkBlockLocation(loc, 1, 2, true); loc = new BlockLocation(null, null, null, null, 1, 2, true); checkBlockLocation(loc, 1, 2, true); loc = new BlockLocation(null, null, null, null, null, null, 1, 2, true); checkBlockLocation(loc, 1, 2, true); } /** * Call each of the setters and verify */ @Test @Timeout(value = 5) public void testBlockLocationSetters() throws Exception { BlockLocation loc; loc = new BlockLocation(); // Test that null sets the empty array loc.setHosts(null); loc.setCachedHosts(null); loc.setNames(null); loc.setTopologyPaths(null); checkBlockLocation(loc); // Test that not-null gets set properly String[] names = new String[] { "name" }; String[] hosts = new String[] { "host" }; String[] cachedHosts = new String[] { "cachedHost" }; String[] topologyPaths = new String[] { "path" }; String[] storageIds = new String[] { "storageId" }; StorageType[] storageTypes = new StorageType[] { StorageType.DISK }; loc.setNames(names); loc.setHosts(hosts); loc.setCachedHosts(cachedHosts); loc.setTopologyPaths(topologyPaths); loc.setStorageIds(storageIds); loc.setStorageTypes(storageTypes); loc.setOffset(1); loc.setLength(2); loc.setCorrupt(true); checkBlockLocation(loc, names, hosts, cachedHosts, topologyPaths, storageIds, storageTypes, 1, 2, true); } }
TestBlockLocation
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/ClusterName.java
{ "start": 870, "end": 2841 }
class ____ implements Writeable { public static final Setting<ClusterName> CLUSTER_NAME_SETTING = new Setting<>("cluster.name", "elasticsearch", (s) -> { if (s.isEmpty()) { throw new IllegalArgumentException("[cluster.name] must not be empty"); } if (s.contains(":")) { throw new IllegalArgumentException("[cluster.name] must not contain ':'"); } return new ClusterName(s); }, Setting.Property.NodeScope); public static final ClusterName DEFAULT = CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY); private final String value; public ClusterName(StreamInput input) throws IOException { this(input.readString()); } public ClusterName(String value) { // cluster name string is most likely part of a setting so we can speed things up over outright interning here this.value = Settings.internKeyOrValue(value); } public String value() { return this.value; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(value); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClusterName that = (ClusterName) o; return Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(value); } @Override public String toString() { return "Cluster [" + value + "]"; } public Predicate<ClusterName> getEqualityPredicate() { return new Predicate<ClusterName>() { @Override public boolean test(ClusterName o) { return ClusterName.this.equals(o); } @Override public String toString() { return "local cluster name [" + ClusterName.this.value() + "]"; } }; } }
ClusterName
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/IndicesAndAliasesResolver.java
{ "start": 38771, "end": 40173 }
class ____ extends RemoteClusterAware { private final CopyOnWriteArraySet<String> clusters; private RemoteClusterResolver(Settings settings, LinkedProjectConfigService linkedProjectConfigService) { super(settings); clusters = new CopyOnWriteArraySet<>( linkedProjectConfigService.getInitialLinkedProjectConfigs().stream().map(LinkedProjectConfig::linkedProjectAlias).toList() ); linkedProjectConfigService.register(this); } @Override public void updateLinkedProject(LinkedProjectConfig config) { if (config.isConnectionEnabled()) { clusters.add(config.linkedProjectAlias()); } else { clusters.remove(config.linkedProjectAlias()); } } ResolvedIndices splitLocalAndRemoteIndexNames(String... indices) { final Map<String, List<String>> map = super.groupClusterIndices(clusters, indices); final List<String> local = map.remove(LOCAL_CLUSTER_GROUP_KEY); final List<String> remote = map.entrySet() .stream() .flatMap(e -> e.getValue().stream().map(v -> e.getKey() + REMOTE_CLUSTER_INDEX_SEPARATOR + v)) .toList(); return new ResolvedIndices(local == null ? List.of() : local, remote); } } }
RemoteClusterResolver
java
google__error-prone
check_api/src/main/java/com/google/errorprone/util/MoreAnnotations.java
{ "start": 3245, "end": 5956 }
class ____. These type * annotations won't be included when the symbol is not in the current compilation. */ public static Stream<TypeCompound> getTopLevelTypeAttributes(Symbol sym) { Symbol typeAnnotationOwner = switch (sym.getKind()) { case PARAMETER -> sym.owner; default -> sym; }; return typeAnnotationOwner.getRawTypeAttributes().stream() .filter(anno -> isAnnotationOnType(sym, anno.position)); } private static boolean isAnnotationOnType(Symbol sym, TypeAnnotationPosition position) { if (!position.location.stream() .allMatch(e -> e.tag == TypeAnnotationPosition.TypePathEntryKind.INNER_TYPE)) { return false; } if (!targetTypeMatches(sym, position)) { return false; } Type type = switch (sym.getKind()) { case METHOD, CONSTRUCTOR -> ((MethodSymbol) sym).getReturnType(); default -> sym.asType(); }; return isAnnotationOnType(type, position.location); } private static boolean isAnnotationOnType( Type type, com.sun.tools.javac.util.List<TypeAnnotationPosition.TypePathEntry> location) { com.sun.tools.javac.util.List<TypeAnnotationPosition.TypePathEntry> expected = com.sun.tools.javac.util.List.nil(); for (Type curr = type.getEnclosingType(); curr != null && !curr.hasTag(TypeTag.NONE); curr = curr.getEnclosingType()) { expected = expected.append(TypeAnnotationPosition.TypePathEntry.INNER_TYPE); } return expected.equals(location); } private static boolean targetTypeMatches(Symbol sym, TypeAnnotationPosition position) { return switch (sym.getKind()) { case LOCAL_VARIABLE, BINDING_VARIABLE -> position.type == TargetType.LOCAL_VARIABLE; // treated like a field case FIELD, ENUM_CONSTANT -> position.type == TargetType.FIELD; case CONSTRUCTOR, METHOD -> position.type == TargetType.METHOD_RETURN; case PARAMETER -> switch (position.type) { case METHOD_FORMAL_PARAMETER -> { int parameterIndex = position.parameter_index; if (position.onLambda != null) { com.sun.tools.javac.util.List<JCTree.JCVariableDecl> lambdaParams = position.onLambda.params; yield parameterIndex < lambdaParams.size() && lambdaParams.get(parameterIndex).sym.equals(sym); } else { yield ((Symbol.MethodSymbol) sym.owner).getParameters().indexOf(sym) == parameterIndex; } } default -> false; }; // There are no type annotations on the top-level type of the
files
java
apache__dubbo
dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/AbstractServiceNameMappingTest.java
{ "start": 4576, "end": 5496 }
class ____ extends AbstractServiceNameMapping { public boolean enabled = false; public MockServiceNameMapping2(ApplicationModel applicationModel) { super(applicationModel); } @Override public Set<String> get(URL url) { return Collections.emptySet(); } @Override public Set<String> getAndListen(URL url, MappingListener mappingListener) { if (!enabled) { return Collections.emptySet(); } return new HashSet<>(Arrays.asList("remote-app3")); } @Override protected void removeListener(URL url, MappingListener mappingListener) {} @Override public boolean map(URL url) { return false; } @Override public boolean hasValidMetadataCenter() { return false; } } }
MockServiceNameMapping2
java
dropwizard__dropwizard
dropwizard-health/src/main/java/io/dropwizard/health/check/http/HttpHealthResponse.java
{ "start": 118, "end": 1101 }
class ____ { private final int status; @NonNull private final String body; public HttpHealthResponse(final int status, @NonNull final String body) { this.status = status; this.body = Objects.requireNonNull(body); } public int getStatus() { return status; } @NonNull public String getBody() { return body; } @Override public boolean equals(final Object other) { if (this == other) { return true; } if (!(other instanceof HttpHealthResponse that)) { return false; } return status == that.status && Objects.equals(body, that.body); } @Override public int hashCode() { return Objects.hash(status, body); } @Override public String toString() { return "HttpHealthResponse{" + "status=" + status + ", body='" + body + '\'' + '}'; } }
HttpHealthResponse
java
FasterXML__jackson-core
src/main/java/tools/jackson/core/Base64Variants.java
{ "start": 892, "end": 5607 }
class ____ { final static String STD_BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** * This variant is what most people would think of "the standard" * Base64 encoding. *<p> * See <a href="http://en.wikipedia.org/wiki/Base64">wikipedia Base64 entry</a> for details. *<p> * Note that although this can be thought of as the standard variant, * it is <b>not</b> the default for Jackson: no-linefeeds alternative * is instead used because of JSON requirement of escaping all linefeeds. *<p> * Writes padding on output; requires padding when reading (may change later with a call to {@link Base64Variant#withWritePadding}) */ public final static Base64Variant MIME = new Base64Variant("MIME", STD_BASE64_ALPHABET, true, '=', 76); /** * Slightly non-standard modification of {@link #MIME} which does not * use linefeeds (max line length set to infinite). Useful when linefeeds * wouldn't work well (possibly in attributes), or for minor space savings * (save 1 linefeed per 76 data chars, ie. ~1.4% savings). *<p> * Writes padding on output; requires padding when reading (may change later with a call to {@link Base64Variant#withWritePadding}) */ public final static Base64Variant MIME_NO_LINEFEEDS = new Base64Variant(MIME, "MIME-NO-LINEFEEDS", Integer.MAX_VALUE); /** * This variant is the one that predates {@link #MIME}: it is otherwise * identical, except that it mandates shorter line length. *<p> * Writes padding on output; requires padding when reading (may change later with a call to {@link Base64Variant#withWritePadding}) */ public final static Base64Variant PEM = new Base64Variant(MIME, "PEM", true, '=', 64); /** * This non-standard variant is usually used when encoded data needs to be * passed via URLs (such as part of GET request). It differs from the * base {@link #MIME} variant in multiple ways. * First, no padding is used: this also means that it generally cannot * be written in multiple separate but adjacent chunks (which would not * be the usual use case in any case). Also, no linefeeds are used (max * line length set to infinite). And finally, two characters (plus and * slash) that would need quoting in URLs are replaced with more * optimal alternatives (hyphen and underscore, respectively). *<p> * Does not write padding on output; does not accept padding when reading (may change later with a call to {@link Base64Variant#withWritePadding}) */ public final static Base64Variant MODIFIED_FOR_URL; static { StringBuilder sb = new StringBuilder(STD_BASE64_ALPHABET); // Replace plus with hyphen, slash with underscore (and no padding) sb.setCharAt(sb.indexOf("+"), '-'); sb.setCharAt(sb.indexOf("/"), '_'); // And finally, let's not split lines either, wouldn't work too well with URLs MODIFIED_FOR_URL = new Base64Variant("MODIFIED-FOR-URL", sb.toString(), false, Base64Variant.PADDING_CHAR_NONE, Integer.MAX_VALUE); } /** * Method used to get the default variant -- {@link #MIME_NO_LINEFEEDS} -- for cases * where caller does not explicitly specify the variant. * We will prefer no-linefeed version because linefeeds in JSON values * must be escaped, making linefeed-containing variants sub-optimal. * * @return Default variant ({@code MIME_NO_LINEFEEDS}) */ public static Base64Variant getDefaultVariant() { return MIME_NO_LINEFEEDS; } /** * Lookup method for finding one of standard variants by name. * If name does not match any of standard variant names, * a {@link IllegalArgumentException} is thrown. * * @param name Name of base64 variant to return * * @return Standard base64 variant that matches given {@code name} * * @throws IllegalArgumentException if no standard variant with given name exists */ public static Base64Variant valueOf(String name) throws IllegalArgumentException { if (MIME._name.equals(name)) { return MIME; } if (MIME_NO_LINEFEEDS._name.equals(name)) { return MIME_NO_LINEFEEDS; } if (PEM._name.equals(name)) { return PEM; } if (MODIFIED_FOR_URL._name.equals(name)) { return MODIFIED_FOR_URL; } if (name == null) { name = "<null>"; } else { name = "'"+name+"'"; } throw new IllegalArgumentException("No Base64Variant with name "+name); } }
Base64Variants
java
netty__netty
transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDomainSocketStartTlsTest.java
{ "start": 933, "end": 1333 }
class ____ extends SocketStartTlsTest { @Override protected SocketAddress newSocketAddress() { return EpollSocketTestPermutation.newDomainSocketAddress(); } @Override protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() { return EpollSocketTestPermutation.INSTANCE.domainSocket(); } }
EpollDomainSocketStartTlsTest
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/authzpolicy/ClassRolesAllowedMethodAuthZPolicyResource.java
{ "start": 384, "end": 824 }
class ____ { @AuthorizationPolicy(name = "permit-user") @GET public String principal(@Context SecurityContext securityContext) { return securityContext.getUserPrincipal().getName(); } @Path("no-authz-policy") @GET public String noAuthorizationPolicy(@Context SecurityContext securityContext) { return securityContext.getUserPrincipal().getName(); } }
ClassRolesAllowedMethodAuthZPolicyResource
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/IsSingleton.java
{ "start": 900, "end": 1059 }
class ____ a singleton, then a single instance will be * shared (and hence should be treated as immutable and be used in a thread-safe manner). * <p/> * This
is
java
google__dagger
hilt-compiler/main/java/dagger/hilt/processor/internal/root/KspComponentTreeDepsProcessor.java
{ "start": 1112, "end": 1595 }
class ____ extends KspBaseProcessingStepProcessor { public KspComponentTreeDepsProcessor(SymbolProcessorEnvironment symbolProcessorEnvironment) { super(symbolProcessorEnvironment); } @Override protected BaseProcessingStep processingStep() { return new ComponentTreeDepsProcessingStep(getXProcessingEnv()); } /** Provides the {@link KspComponentTreeDepsProcessor}. */ @AutoService(SymbolProcessorProvider.class) public static final
KspComponentTreeDepsProcessor
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/xml/AbstractSimpleBeanDefinitionParser.java
{ "start": 987, "end": 1192 }
class ____ when there exists a one-to-one mapping * between attribute names on the element that is to be parsed and * the property names on the {@link Class} being configured. * * <p>Extend this parser
for
java
grpc__grpc-java
interop-testing/src/generated/main/grpc/io/grpc/testing/integration/ReconnectServiceGrpc.java
{ "start": 16314, "end": 16490 }
class ____ extends ReconnectServiceBaseDescriptorSupplier { ReconnectServiceFileDescriptorSupplier() {} } private static final
ReconnectServiceFileDescriptorSupplier
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/EqualsWrongThing.java
{ "start": 2609, "end": 7196 }
class ____ extends BugChecker implements MethodTreeMatcher { private static final Matcher<MethodInvocationTree> COMPARISON_METHOD = anyOf(staticMethod().onClass("java.util.Arrays").named("equals"), staticEqualsInvocation()); private static final ImmutableSet<ElementKind> FIELD_TYPES = Sets.immutableEnumSet(ElementKind.FIELD, ElementKind.METHOD); @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!equalsMethodDeclaration().matches(tree, state)) { return NO_MATCH; } ClassSymbol classSymbol = getSymbol(tree).enclClass(); Set<ComparisonSite> suspiciousComparisons = new HashSet<>(); new TreeScanner<Void, Void>() { @Override public Void visitBinary(BinaryTree node, Void unused) { if (node.getKind() == Kind.EQUAL_TO || node.getKind() == Kind.NOT_EQUAL_TO) { getDubiousComparison(classSymbol, node, node.getLeftOperand(), node.getRightOperand()) .ifPresent(suspiciousComparisons::add); } return super.visitBinary(node, null); } @Override public Void visitMethodInvocation(MethodInvocationTree node, Void unused) { var args = node.getArguments(); if (COMPARISON_METHOD.matches(node, state)) { // args.size() / 2 handles the six-arg overload of Arrays.equals (the 0th and 3rd args are // the arrays). getDubiousComparison(classSymbol, node, args.getFirst(), args.get(args.size() / 2)) .ifPresent(suspiciousComparisons::add); } if (instanceEqualsInvocation().matches(node, state)) { ExpressionTree receiver = getReceiver(node); if (receiver != null) { // Special-case super, for odd cases like `super.equals(this)`. if (!(receiver instanceof IdentifierTree identifierTree && identifierTree.getName().contentEquals("super"))) { getDubiousComparison(classSymbol, node, receiver, args.getFirst()) .ifPresent(suspiciousComparisons::add); } } } return super.visitMethodInvocation(node, null); } }.scan(tree, null); // Fast path return. if (suspiciousComparisons.isEmpty()) { return NO_MATCH; } // Special case where comparisons are made of (a, b) and (b, a) to imply that order doesn't // matter. ImmutableSet<ComparisonPair> suspiciousPairs = suspiciousComparisons.stream().map(ComparisonSite::pair).collect(toImmutableSet()); suspiciousComparisons.stream() .filter(p -> !suspiciousPairs.contains(p.pair().reversed())) .map( c -> buildDescription(c.tree()) .setMessage( String.format( "Suspicious comparison between `%s` and `%s`", c.pair().lhs(), c.pair().rhs())) .build()) .forEach(state::reportMatch); return NO_MATCH; } private static Optional<ComparisonSite> getDubiousComparison( ClassSymbol encl, Tree tree, ExpressionTree lhs, ExpressionTree rhs) { Symbol lhsSymbol = getSymbol(lhs); Symbol rhsSymbol = getSymbol(rhs); if (lhsSymbol == null || rhsSymbol == null || lhsSymbol.equals(rhsSymbol)) { return Optional.empty(); } if (isStatic(lhsSymbol) || isStatic(rhsSymbol)) { return Optional.empty(); } if (!encl.equals(lhsSymbol.enclClass()) || !encl.equals(rhsSymbol.enclClass())) { return Optional.empty(); } if (!FIELD_TYPES.contains(lhsSymbol.getKind()) || !FIELD_TYPES.contains(rhsSymbol.getKind())) { return Optional.empty(); } if (getKind(lhs) != getKind(rhs)) { return Optional.empty(); } return Optional.of(ComparisonSite.of(tree, lhsSymbol, rhsSymbol)); } private static Kind getKind(Tree tree) { Kind kind = tree.getKind(); // Treat identifiers as being similar to member selects for our purposes, as in a == that.a. return kind == Kind.IDENTIFIER ? Kind.MEMBER_SELECT : kind; } private record ComparisonSite(Tree tree, ComparisonPair pair) { private static ComparisonSite of(Tree tree, Symbol lhs, Symbol rhs) { return new ComparisonSite(tree, ComparisonPair.of(lhs, rhs)); } } private record ComparisonPair(Symbol lhs, Symbol rhs) { final ComparisonPair reversed() { return of(rhs(), lhs()); } private static ComparisonPair of(Symbol lhs, Symbol rhs) { return new ComparisonPair(lhs, rhs); } } }
EqualsWrongThing
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scheduling/config/TaskExecutionOutcomeTests.java
{ "start": 951, "end": 3359 }
class ____ { @Test void shouldCreateWithNoneStatus() { TaskExecutionOutcome outcome = TaskExecutionOutcome.create(); assertThat(outcome.status()).isEqualTo(TaskExecutionOutcome.Status.NONE); assertThat(outcome.executionTime()).isNull(); assertThat(outcome.throwable()).isNull(); } @Test void startedTaskShouldBeOngoing() { TaskExecutionOutcome outcome = TaskExecutionOutcome.create(); Instant now = Instant.now(); outcome = outcome.start(now); assertThat(outcome.status()).isEqualTo(TaskExecutionOutcome.Status.STARTED); assertThat(outcome.executionTime()).isEqualTo(now); assertThat(outcome.throwable()).isNull(); } @Test void shouldRejectSuccessWhenNotStarted() { TaskExecutionOutcome outcome = TaskExecutionOutcome.create(); assertThatIllegalStateException().isThrownBy(outcome::success); } @Test void shouldRejectErrorWhenNotStarted() { TaskExecutionOutcome outcome = TaskExecutionOutcome.create(); assertThatIllegalStateException().isThrownBy(() -> outcome.failure(new IllegalArgumentException("test error"))); } @Test void finishedTaskShouldBeSuccessful() { TaskExecutionOutcome outcome = TaskExecutionOutcome.create(); Instant now = Instant.now(); outcome = outcome.start(now); outcome = outcome.success(); assertThat(outcome.status()).isEqualTo(TaskExecutionOutcome.Status.SUCCESS); assertThat(outcome.executionTime()).isEqualTo(now); assertThat(outcome.throwable()).isNull(); } @Test void errorTaskShouldBeFailure() { TaskExecutionOutcome outcome = TaskExecutionOutcome.create(); Instant now = Instant.now(); outcome = outcome.start(now); outcome = outcome.failure(new IllegalArgumentException(("test error"))); assertThat(outcome.status()).isEqualTo(TaskExecutionOutcome.Status.ERROR); assertThat(outcome.executionTime()).isEqualTo(now); assertThat(outcome.throwable()).isInstanceOf(IllegalArgumentException.class); } @Test void newTaskExecutionShouldNotFail() { TaskExecutionOutcome outcome = TaskExecutionOutcome.create(); Instant now = Instant.now(); outcome = outcome.start(now); outcome = outcome.failure(new IllegalArgumentException(("test error"))); outcome = outcome.start(now.plusSeconds(2)); assertThat(outcome.status()).isEqualTo(TaskExecutionOutcome.Status.STARTED); assertThat(outcome.executionTime()).isAfter(now); assertThat(outcome.throwable()).isNull(); } }
TaskExecutionOutcomeTests
java
apache__camel
components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/decorators/http/JettySegmentDecorator.java
{ "start": 872, "end": 1021 }
class ____ extends AbstractHttpSegmentDecorator { @Override public String getComponent() { return "jetty"; } }
JettySegmentDecorator
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/javatime/key/DurationAsKeyTest.java
{ "start": 420, "end": 1228 }
class ____ extends DateTimeTestBase { private static final Duration DURATION = Duration.ofMinutes(13).plusSeconds(37).plusNanos(120 * 1000 * 1000L); private static final String DURATION_STRING = "PT13M37.12S"; private final ObjectMapper MAPPER = newMapper(); private final ObjectReader READER = MAPPER.readerFor(new TypeReference<Map<Duration, String>>() { }); @Test public void testSerialization() throws Exception { assertEquals(mapAsString(DURATION_STRING, "test"), MAPPER.writeValueAsString(Collections.singletonMap(DURATION, "test"))); } @Test public void testDeserialization() throws Exception { assertEquals(Collections.singletonMap(DURATION, "test"), READER.readValue(mapAsString(DURATION_STRING, "test"))); } }
DurationAsKeyTest
java
quarkusio__quarkus
integration-tests/maven/src/test/java/io/quarkus/maven/AddExtensionMojoTest.java
{ "start": 1386, "end": 7254 }
class ____ { private static final File MIN_POM = new File("target/test-classes/projects/simple-pom-it/pom.xml"); private static final File OUTPUT_POM = new File("target/test-classes/add-extension/pom.xml"); private static final String DEP_GAV = "org.apache.commons:commons-lang3:3.8.1"; private AddExtensionMojo mojo; @BeforeAll static void globalInit() { RegistryClientTestHelper.enableRegistryClientTestConfig(); } @AfterAll static void globalCleanUp() { RegistryClientTestHelper.disableRegistryClientTestConfig(); } @BeforeEach void init() throws Exception { mojo = getMojo(); mojo.project = new MavenProject(); mojo.project.setPomFile(OUTPUT_POM); mojo.project.setFile(OUTPUT_POM); FileUtils.copyFile(MIN_POM, OUTPUT_POM); Model model = ModelUtils.readModel(OUTPUT_POM.toPath()); model.setPomFile(OUTPUT_POM); mojo.project.setOriginalModel(model); final MavenArtifactResolver mvn = new MavenArtifactResolver( new BootstrapMavenContext(BootstrapMavenContext.config() .setCurrentProject(OUTPUT_POM.getAbsolutePath()) .setOffline(true))); mojo.repoSession = mvn.getSession(); mojo.repos = mvn.getRepositories(); mojo.workspaceProvider = new QuarkusWorkspaceProvider(null, null, null, null, null, mvn.getRemoteRepositoryManager(), mvn.getMavenContext().getSettingsDecrypter()) { @Override public BootstrapMavenContext createMavenContext(BootstrapMavenContextConfig<?> config) { return mvn.getMavenContext(); } @Override public MavenArtifactResolver createArtifactResolver(BootstrapMavenContextConfig<?> config) { return mvn; } }; final Model effectiveModel = model.clone(); final DependencyManagement dm = new DependencyManagement(); effectiveModel.setDependencyManagement(dm); final Artifact projectPom = new DefaultArtifact(ModelUtils.getGroupId(model), model.getArtifactId(), null, "pom", ModelUtils.getVersion(model)); final ArtifactDescriptorResult descriptor = mvn.resolveDescriptor(projectPom); descriptor.getManagedDependencies().forEach(d -> { final Dependency dep = new Dependency(); Artifact a = d.getArtifact(); dep.setGroupId(a.getGroupId()); dep.setArtifactId(a.getArtifactId()); dep.setClassifier(a.getClassifier()); dep.setType(a.getExtension()); dep.setVersion(a.getVersion()); if (d.getOptional() != null) { dep.setOptional(d.getOptional()); } dep.setScope(d.getScope()); dm.addDependency(dep); }); descriptor.getDependencies().forEach(d -> { final Dependency dep = new Dependency(); Artifact a = d.getArtifact(); dep.setGroupId(a.getGroupId()); dep.setArtifactId(a.getArtifactId()); dep.setClassifier(a.getClassifier()); dep.setType(a.getExtension()); dep.setVersion(a.getVersion()); if (d.getOptional() != null) { dep.setOptional(d.getOptional()); } dep.setScope(d.getScope()); effectiveModel.addDependency(dep); }); descriptor.getProperties().entrySet().forEach(p -> effectiveModel.getProperties().setProperty(p.getKey(), p.getValue() == null ? "" : p.getValue().toString())); mojo.project.setModel(effectiveModel); } protected AddExtensionMojo getMojo() throws Exception { return new AddExtensionMojo(); } @Test void testAddSingleDependency() throws MojoExecutionException, IOException, XmlPullParserException { mojo.extension = DEP_GAV; mojo.extensions = new HashSet<>(); mojo.execute(); Model reloaded = reload(); List<Dependency> dependencies = reloaded.getDependencies(); assertThat(dependencies).hasSize(1); assertThat(dependencies.get(0).getArtifactId()).isEqualTo("commons-lang3"); } @Test void testAddMultipleDependency() throws MojoExecutionException, IOException, XmlPullParserException { Set<String> deps = new HashSet<>(); deps.add(DEP_GAV); // use an obscure jar that is lightweight and comes with no dependencies deps.add("io.smallrye:jandex-test-data:3.4.0"); mojo.extensions = deps; mojo.execute(); Model reloaded = reload(); List<Dependency> dependencies = reloaded.getDependencies(); assertThat(dependencies).hasSize(2); } @Test void testThatBothParameterCannotBeSet() { mojo.extension = DEP_GAV; Set<String> deps = new HashSet<>(); // use an obscure jar that is lightweight and comes with no dependencies deps.add("io.smallrye:jandex-test-data:3.4.0"); mojo.extensions = deps; assertThrows(MojoExecutionException.class, () -> mojo.execute()); } @Test void testThatAtLeastOneParameterMustBeSet() { assertThrows(MojoExecutionException.class, () -> mojo.execute()); } @Test void testThatAtLeastOneParameterMustBeSetWithBlankAndEmpty() { mojo.extension = ""; mojo.extensions = Collections.emptySet(); assertThrows(MojoExecutionException.class, () -> mojo.execute()); } private Model reload() throws IOException, XmlPullParserException { MavenXpp3Reader reader = new MavenXpp3Reader(); try (Reader fr = Files.newBufferedReader(OUTPUT_POM.toPath())) { return reader.read(fr); } } }
AddExtensionMojoTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/internal/InFlightMetadataCollectorImpl.java
{ "start": 50314, "end": 63260 }
class ____ implements EntityTableXref { private final Identifier primaryTableLogicalName; private final Table primaryTable; private final EntityTableXrefImpl superEntityTableXref; //annotations needs a Map<String,Join> //private Map<Identifier,Join> secondaryTableJoinMap; private Map<String,Join> secondaryTableJoinMap; public EntityTableXrefImpl( Identifier primaryTableLogicalName, Table primaryTable, EntityTableXrefImpl superEntityTableXref) { this.primaryTableLogicalName = primaryTableLogicalName; this.primaryTable = primaryTable; this.superEntityTableXref = superEntityTableXref; } @Override public void addSecondaryTable( LocalMetadataBuildingContext buildingContext, Identifier logicalName, Join secondaryTableJoin) { if ( Identifier.areEqual( primaryTableLogicalName, logicalName ) ) { throw new org.hibernate.boot.MappingException( String.format( Locale.ENGLISH, "Attempt to add secondary table with same name as primary table [%s]", primaryTableLogicalName ), buildingContext.getOrigin() ); } if ( secondaryTableJoinMap == null ) { //secondaryTableJoinMap = new HashMap<Identifier,Join>(); //secondaryTableJoinMap.put( logicalName, secondaryTableJoin ); secondaryTableJoinMap = new HashMap<>(); secondaryTableJoinMap.put( logicalName.getCanonicalName(), secondaryTableJoin ); } else { //final Join existing = secondaryTableJoinMap.put( logicalName, secondaryTableJoin ); final Join existing = secondaryTableJoinMap.put( logicalName.getCanonicalName(), secondaryTableJoin ); if ( existing != null ) { throw new org.hibernate.boot.MappingException( String.format( Locale.ENGLISH, "Added secondary table with same name [%s]", logicalName ), buildingContext.getOrigin() ); } } } @Override public void addSecondaryTable(QualifiedTableName logicalQualifiedTableName, Join secondaryTableJoin) { final Identifier tableName = logicalQualifiedTableName.getTableName(); if ( Identifier.areEqual( toIdentifier( new QualifiedTableName( toIdentifier( primaryTable.getCatalog() ), toIdentifier( primaryTable.getSchema() ), primaryTableLogicalName ).render() ), toIdentifier( logicalQualifiedTableName.render() ) ) ) { throw new DuplicateSecondaryTableException( tableName ); } if ( secondaryTableJoinMap == null ) { //secondaryTableJoinMap = new HashMap<Identifier,Join>(); //secondaryTableJoinMap.put( logicalName, secondaryTableJoin ); secondaryTableJoinMap = new HashMap<>(); secondaryTableJoinMap.put( tableName.getCanonicalName(), secondaryTableJoin ); } else { //final Join existing = secondaryTableJoinMap.put( logicalName, secondaryTableJoin ); final Join existing = secondaryTableJoinMap.put( tableName.getCanonicalName(), secondaryTableJoin ); if ( existing != null ) { throw new DuplicateSecondaryTableException( tableName ); } } } @Override public Table getPrimaryTable() { return primaryTable; } @Override public Table resolveTable(Identifier tableName) { if ( tableName == null ) { return primaryTable; } if ( Identifier.areEqual( primaryTableLogicalName, tableName ) ) { return primaryTable; } Join secondaryTableJoin = null; if ( secondaryTableJoinMap != null ) { //secondaryTableJoin = secondaryTableJoinMap.get( tableName ); secondaryTableJoin = secondaryTableJoinMap.get( tableName.getCanonicalName() ); } if ( secondaryTableJoin != null ) { return secondaryTableJoin.getTable(); } if ( superEntityTableXref != null ) { return superEntityTableXref.resolveTable( tableName ); } return null; } public Join locateJoin(Identifier tableName) { if ( tableName == null ) { return null; } Join join = null; if ( secondaryTableJoinMap != null ) { join = secondaryTableJoinMap.get( tableName.getCanonicalName() ); } if ( join != null ) { return join; } if ( superEntityTableXref != null ) { return superEntityTableXref.locateJoin( tableName ); } return null; } } private ArrayList<IdGeneratorResolver> idGeneratorResolverSecondPassList; private ArrayList<SetBasicValueTypeSecondPass> setBasicValueTypeSecondPassList; private ArrayList<AggregateComponentSecondPass> aggregateComponentSecondPassList; private ArrayList<FkSecondPass> fkSecondPassList; private ArrayList<CreateKeySecondPass> createKeySecondPassList; private ArrayList<ImplicitToOneJoinTableSecondPass> toOneJoinTableSecondPassList; private ArrayList<SecondaryTableSecondPass> secondaryTableSecondPassList; private ArrayList<SecondaryTableFromAnnotationSecondPass> secondaryTableFromAnnotationSecondPassesList; private ArrayList<QuerySecondPass> querySecondPassList; private ArrayList<ImplicitColumnNamingSecondPass> implicitColumnNamingSecondPassList; private ArrayList<SecondPass> generalSecondPassList; private ArrayList<OptionalDeterminationSecondPass> optionalDeterminationSecondPassList; @Override public void addSecondPass(SecondPass secondPass) { addSecondPass( secondPass, false ); } @Override public void addSecondPass(SecondPass secondPass, boolean onTopOfTheQueue) { if ( secondPass instanceof IdGeneratorResolver generatorResolver ) { addIdGeneratorResolverSecondPass( generatorResolver, onTopOfTheQueue ); } else if ( secondPass instanceof SetBasicValueTypeSecondPass setBasicValueTypeSecondPass ) { addSetBasicValueTypeSecondPass( setBasicValueTypeSecondPass, onTopOfTheQueue ); } else if ( secondPass instanceof AggregateComponentSecondPass aggregateComponentSecondPass ) { addAggregateComponentSecondPass( aggregateComponentSecondPass, onTopOfTheQueue ); } else if ( secondPass instanceof FkSecondPass fkSecondPass ) { addFkSecondPass( fkSecondPass, onTopOfTheQueue ); } else if ( secondPass instanceof CreateKeySecondPass createKeySecondPass ) { addCreateKeySecondPass( createKeySecondPass, onTopOfTheQueue ); } else if ( secondPass instanceof ImplicitToOneJoinTableSecondPass implicitToOneJoinTableSecondPass ) { addImplicitToOneJoinTableSecondPass( implicitToOneJoinTableSecondPass ); } else if ( secondPass instanceof SecondaryTableSecondPass secondaryTableSecondPass ) { addSecondaryTableSecondPass( secondaryTableSecondPass, onTopOfTheQueue ); } else if ( secondPass instanceof SecondaryTableFromAnnotationSecondPass secondaryTableFromAnnotationSecondPass ) { addSecondaryTableFromAnnotationSecondPass( secondaryTableFromAnnotationSecondPass, onTopOfTheQueue ); } else if ( secondPass instanceof QuerySecondPass querySecondPass ) { addQuerySecondPass( querySecondPass, onTopOfTheQueue ); } else if ( secondPass instanceof ImplicitColumnNamingSecondPass implicitColumnNamingSecondPass ) { addImplicitColumnNamingSecondPass( implicitColumnNamingSecondPass ); } else if ( secondPass instanceof OptionalDeterminationSecondPass optionalDeterminationSecondPass ) { addOptionalDeterminationSecondPass( optionalDeterminationSecondPass ); } else { // add to the general SecondPass list if ( generalSecondPassList == null ) { generalSecondPassList = new ArrayList<>(); } addSecondPass( secondPass, generalSecondPassList, onTopOfTheQueue ); } } private <T extends SecondPass> void addSecondPass(T secondPass, ArrayList<T> secondPassList, boolean onTopOfTheQueue) { if ( onTopOfTheQueue ) { secondPassList.add( 0, secondPass ); } else { secondPassList.add( secondPass ); } } private void addSetBasicValueTypeSecondPass(SetBasicValueTypeSecondPass secondPass, boolean onTopOfTheQueue) { if ( setBasicValueTypeSecondPassList == null ) { setBasicValueTypeSecondPassList = new ArrayList<>(); } addSecondPass( secondPass, setBasicValueTypeSecondPassList, onTopOfTheQueue ); } private void addAggregateComponentSecondPass(AggregateComponentSecondPass secondPass, boolean onTopOfTheQueue) { if ( aggregateComponentSecondPassList == null ) { aggregateComponentSecondPassList = new ArrayList<>(); } addSecondPass( secondPass, aggregateComponentSecondPassList, onTopOfTheQueue ); } private void addIdGeneratorResolverSecondPass(IdGeneratorResolver secondPass, boolean onTopOfTheQueue) { if ( idGeneratorResolverSecondPassList == null ) { idGeneratorResolverSecondPassList = new ArrayList<>(); } addSecondPass( secondPass, idGeneratorResolverSecondPassList, onTopOfTheQueue ); } private void addFkSecondPass(FkSecondPass secondPass, boolean onTopOfTheQueue) { if ( fkSecondPassList == null ) { fkSecondPassList = new ArrayList<>(); } addSecondPass( secondPass, fkSecondPassList, onTopOfTheQueue ); } private void addCreateKeySecondPass(CreateKeySecondPass secondPass, boolean onTopOfTheQueue) { if ( createKeySecondPassList == null ) { createKeySecondPassList = new ArrayList<>(); } addSecondPass( secondPass, createKeySecondPassList, onTopOfTheQueue ); } private void addImplicitToOneJoinTableSecondPass(ImplicitToOneJoinTableSecondPass secondPass) { if ( toOneJoinTableSecondPassList == null ) { toOneJoinTableSecondPassList = new ArrayList<>(); } toOneJoinTableSecondPassList.add( secondPass ); } private void addSecondaryTableSecondPass(SecondaryTableSecondPass secondPass, boolean onTopOfTheQueue) { if ( secondaryTableSecondPassList == null ) { secondaryTableSecondPassList = new ArrayList<>(); } addSecondPass( secondPass, secondaryTableSecondPassList, onTopOfTheQueue ); } private void addSecondaryTableFromAnnotationSecondPass( SecondaryTableFromAnnotationSecondPass secondPass, boolean onTopOfTheQueue){ if ( secondaryTableFromAnnotationSecondPassesList == null ) { secondaryTableFromAnnotationSecondPassesList = new ArrayList<>(); } addSecondPass( secondPass, secondaryTableFromAnnotationSecondPassesList, onTopOfTheQueue ); } private void addQuerySecondPass(QuerySecondPass secondPass, boolean onTopOfTheQueue) { if ( querySecondPassList == null ) { querySecondPassList = new ArrayList<>(); } addSecondPass( secondPass, querySecondPassList, onTopOfTheQueue ); } private void addImplicitColumnNamingSecondPass(ImplicitColumnNamingSecondPass secondPass) { if ( implicitColumnNamingSecondPassList == null ) { implicitColumnNamingSecondPassList = new ArrayList<>(); } implicitColumnNamingSecondPassList.add( secondPass ); } private void addOptionalDeterminationSecondPass(OptionalDeterminationSecondPass secondPass) { if ( optionalDeterminationSecondPassList == null ) { optionalDeterminationSecondPassList = new ArrayList<>(); } optionalDeterminationSecondPassList.add( secondPass ); } private boolean inSecondPass = false; /** * Ugh! But we need this done before we ask Envers to produce its entities. */ public void processSecondPasses(MetadataBuildingContext buildingContext) { assert !inSecondPass; inSecondPass = true; try { processSecondPasses( idGeneratorResolverSecondPassList ); processSecondPasses( implicitColumnNamingSecondPassList ); processSecondPasses( setBasicValueTypeSecondPassList ); processSecondPasses( toOneJoinTableSecondPassList ); composites.forEach( Component::sortProperties ); processFkSecondPassesInOrder(); processSecondPasses( createKeySecondPassList ); processSecondPasses( secondaryTableSecondPassList ); processSecondPasses( querySecondPassList ); processSecondPasses( generalSecondPassList ); processSecondPasses( optionalDeterminationSecondPassList ); processPropertyReferences(); processSecondPasses( aggregateComponentSecondPassList ); secondPassCompileForeignKeys( buildingContext ); processNaturalIdUniqueKeyBinders(); processCachingOverrides(); processValueResolvers( buildingContext ); } finally { inSecondPass = false; } } private void processValueResolvers(MetadataBuildingContext buildingContext) { if ( valueResolvers != null ) { while ( !valueResolvers.isEmpty() ) { final boolean anyRemoved = valueResolvers.removeIf( resolver -> resolver.apply( buildingContext ) ); if ( !anyRemoved ) { throw new MappingException( "Unable to complete initialization of boot meta-model" ); } } } } private void processSecondPasses(ArrayList<? extends SecondPass> secondPasses) { if ( secondPasses != null ) { for ( SecondPass secondPass : secondPasses ) { secondPass.doSecondPass( getEntityBindingMap() ); } secondPasses.clear(); } } private void processFkSecondPassesInOrder() { if ( fkSecondPassList == null || fkSecondPassList.isEmpty() ) { processSecondPasses( secondaryTableFromAnnotationSecondPassesList ); } else { // split FkSecondPass instances into primary key and non primary key FKs. // While doing so build a map of
EntityTableXrefImpl
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToBooleanFromStringEvaluator.java
{ "start": 4179, "end": 4809 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final Source source; private final EvalOperator.ExpressionEvaluator.Factory keyword; public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory keyword) { this.source = source; this.keyword = keyword; } @Override public ToBooleanFromStringEvaluator get(DriverContext context) { return new ToBooleanFromStringEvaluator(source, keyword.get(context), context); } @Override public String toString() { return "ToBooleanFromStringEvaluator[" + "keyword=" + keyword + "]"; } } }
Factory
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/expr/OracleArgumentExpr.java
{ "start": 1008, "end": 2505 }
class ____ extends OracleSQLObjectImpl implements SQLExpr, SQLReplaceable { private String argumentName; private SQLExpr value; public OracleArgumentExpr() { } public OracleArgumentExpr(String argumentName, SQLExpr value) { this.argumentName = argumentName; setValue(value); } public String getArgumentName() { return argumentName; } public void setArgumentName(String argumentName) { this.argumentName = argumentName; } public SQLExpr getValue() { return value; } public void setValue(SQLExpr value) { if (value != null) { value.setParent(this); } this.value = value; } @Override public void accept0(OracleASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, value); } visitor.endVisit(this); } @Override public OracleArgumentExpr clone() { OracleArgumentExpr x = new OracleArgumentExpr(); x.argumentName = argumentName; if (value != null) { x.setValue(value.clone()); } return x; } @Override public boolean replace(SQLExpr expr, SQLExpr target) { if (value == expr) { setValue(target); return true; } return false; } @Override public List<SQLObject> getChildren() { return Collections.<SQLObject>singletonList(this.value); } }
OracleArgumentExpr
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfigurationTests.java
{ "start": 24942, "end": 25271 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off return http .authorizeHttpRequests((authorize) -> authorize .anyRequest().permitAll() ) .build(); // @formatter:on } } @Configuration @EnableWebSecurity static
AuthorizeRequestsConfig
java
apache__rocketmq
tools/src/main/java/org/apache/rocketmq/tools/command/topic/UpdateTopicPermSubCommand.java
{ "start": 1673, "end": 7266 }
class ____ implements SubCommand { @Override public String commandName() { return "updateTopicPerm"; } @Override public String commandDesc() { return "Update topic perm."; } @Override public Options buildCommandlineOptions(Options options) { Option opt = new Option("b", "brokerAddr", true, "create topic to which broker"); opt.setRequired(false); options.addOption(opt); opt = new Option("c", "clusterName", true, "create topic to which cluster"); opt.setRequired(false); options.addOption(opt); opt = new Option("t", "topic", true, "topic name"); opt.setRequired(true); options.addOption(opt); opt = new Option("p", "perm", true, "set topic's permission(2|4|6), intro[2:W; 4:R; 6:RW]"); opt.setRequired(true); options.addOption(opt); return options; } @Override public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { defaultMQAdminExt.start(); TopicConfig topicConfig = new TopicConfig(); String topic; if (commandLine.hasOption('t')) { topic = commandLine.getOptionValue('t').trim(); } else { System.out.printf("topic parameter value must be need.%n"); return; } TopicRouteData topicRouteData = defaultMQAdminExt.examineTopicRouteInfo(topic); assert topicRouteData != null; List<QueueData> queueDatas = topicRouteData.getQueueDatas(); assert queueDatas != null && queueDatas.size() > 0; QueueData queueData = queueDatas.get(0); topicConfig.setTopicName(topic); topicConfig.setWriteQueueNums(queueData.getWriteQueueNums()); topicConfig.setReadQueueNums(queueData.getReadQueueNums()); topicConfig.setTopicSysFlag(queueData.getTopicSysFlag()); //new perm int perm; if (commandLine.hasOption('p')) { perm = Integer.parseInt(commandLine.getOptionValue('p').trim()); } else { System.out.printf("perm parameter value must be need.%n"); return; } topicConfig.setPerm(perm); if (commandLine.hasOption('b')) { String brokerAddr = commandLine.getOptionValue('b').trim(); List<BrokerData> brokerDatas = topicRouteData.getBrokerDatas(); String brokerName = null; for (BrokerData data : brokerDatas) { HashMap<Long, String> brokerAddrs = data.getBrokerAddrs(); if (brokerAddrs == null || brokerAddrs.size() == 0) { continue; } for (Map.Entry<Long, String> entry : brokerAddrs.entrySet()) { if (brokerAddr.equals(entry.getValue()) && MixAll.MASTER_ID == entry.getKey()) { brokerName = data.getBrokerName(); break; } } if (brokerName != null) { break; } } if (brokerName != null) { List<QueueData> queueDataList = topicRouteData.getQueueDatas(); assert queueDataList != null && queueDataList.size() > 0; int oldPerm = 0; for (QueueData data : queueDataList) { if (brokerName.equals(data.getBrokerName())) { oldPerm = data.getPerm(); if (perm == oldPerm) { System.out.printf("new perm equals to the old one!%n"); return; } break; } } defaultMQAdminExt.createAndUpdateTopicConfig(brokerAddr, topicConfig); System.out.printf("update topic perm from %s to %s in %s success.%n", oldPerm, perm, brokerAddr); System.out.printf("%s.%n", topicConfig); return; } else { System.out.printf("updateTopicPerm error broker not exit or broker is not master!.%n"); return; } } else if (commandLine.hasOption('c')) { String clusterName = commandLine.getOptionValue('c').trim(); Set<String> masterSet = CommandUtil.fetchMasterAddrByClusterName(defaultMQAdminExt, clusterName); for (String addr : masterSet) { defaultMQAdminExt.createAndUpdateTopicConfig(addr, topicConfig); System.out.printf("update topic perm from %s to %s in %s success.%n", queueData.getPerm(), perm, addr); } return; } ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options); } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } }
UpdateTopicPermSubCommand
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/D.java
{ "start": 238, "end": 1374 }
class ____ extends AbstractEntity { private static final long serialVersionUID = 2417176961L; @jakarta.persistence.OneToMany(mappedBy = "d") private java.util.Set<B> bCollection = new java.util.HashSet<B>(); @jakarta.persistence.ManyToOne(optional = false) private C c; @jakarta.persistence.ManyToOne(optional = false) private E e; @jakarta.persistence.OneToMany(mappedBy = "d") @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH }) private java.util.Set<F> fCollection = new java.util.HashSet<F>(); public java.util.Set<B> getBCollection() { return bCollection; } public void setBCollection( java.util.Set<B> parameter) { this.bCollection = parameter; } public C getC() { return c; } public void setC(C c) { this.c = c; } public E getE() { return e; } public void setE(E e) { this.e = e; } public java.util.Set<F> getFCollection() { return fCollection; } public void setFCollection( java.util.Set<F> parameter) { this.fCollection = parameter; } }
D
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/FhirEndpointBuilderFactory.java
{ "start": 52032, "end": 64751 }
interface ____ extends EndpointProducerBuilder { default FhirEndpointProducerBuilder basic() { return (FhirEndpointProducerBuilder) this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * To use the custom client. * * The option is a: * <code>ca.uhn.fhir.rest.client.api.IGenericClient</code> type. * * Group: advanced * * @param client the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder client(ca.uhn.fhir.rest.client.api.IGenericClient client) { doSetProperty("client", client); return this; } /** * To use the custom client. * * The option will be converted to a * <code>ca.uhn.fhir.rest.client.api.IGenericClient</code> type. * * Group: advanced * * @param client the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder client(String client) { doSetProperty("client", client); return this; } /** * To use the custom client factory. * * The option is a: * <code>ca.uhn.fhir.rest.client.api.IRestfulClientFactory</code> type. * * Group: advanced * * @param clientFactory the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder clientFactory(ca.uhn.fhir.rest.client.api.IRestfulClientFactory clientFactory) { doSetProperty("clientFactory", clientFactory); return this; } /** * To use the custom client factory. * * The option will be converted to a * <code>ca.uhn.fhir.rest.client.api.IRestfulClientFactory</code> type. * * Group: advanced * * @param clientFactory the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder clientFactory(String clientFactory) { doSetProperty("clientFactory", clientFactory); return this; } /** * Compresses outgoing (POST/PUT) contents to the GZIP format. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param compress the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder compress(boolean compress) { doSetProperty("compress", compress); return this; } /** * Compresses outgoing (POST/PUT) contents to the GZIP format. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param compress the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder compress(String compress) { doSetProperty("compress", compress); return this; } /** * How long to try and establish the initial TCP connection (in ms). * * The option is a: <code>java.lang.Integer</code> type. * * Default: 10000 * Group: advanced * * @param connectionTimeout the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder connectionTimeout(Integer connectionTimeout) { doSetProperty("connectionTimeout", connectionTimeout); return this; } /** * How long to try and establish the initial TCP connection (in ms). * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Default: 10000 * Group: advanced * * @param connectionTimeout the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder connectionTimeout(String connectionTimeout) { doSetProperty("connectionTimeout", connectionTimeout); return this; } /** * When this option is set, model classes will not be scanned for * children until the child list for the given type is actually * accessed. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param deferModelScanning the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder deferModelScanning(boolean deferModelScanning) { doSetProperty("deferModelScanning", deferModelScanning); return this; } /** * When this option is set, model classes will not be scanned for * children until the child list for the given type is actually * accessed. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param deferModelScanning the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder deferModelScanning(String deferModelScanning) { doSetProperty("deferModelScanning", deferModelScanning); return this; } /** * FhirContext is an expensive object to create. To avoid creating * multiple instances, it can be set directly. * * The option is a: <code>ca.uhn.fhir.context.FhirContext</code> type. * * Group: advanced * * @param fhirContext the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder fhirContext(ca.uhn.fhir.context.FhirContext fhirContext) { doSetProperty("fhirContext", fhirContext); return this; } /** * FhirContext is an expensive object to create. To avoid creating * multiple instances, it can be set directly. * * The option will be converted to a * <code>ca.uhn.fhir.context.FhirContext</code> type. * * Group: advanced * * @param fhirContext the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder fhirContext(String fhirContext) { doSetProperty("fhirContext", fhirContext); return this; } /** * Force conformance check. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param forceConformanceCheck the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder forceConformanceCheck(boolean forceConformanceCheck) { doSetProperty("forceConformanceCheck", forceConformanceCheck); return this; } /** * Force conformance check. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param forceConformanceCheck the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder forceConformanceCheck(String forceConformanceCheck) { doSetProperty("forceConformanceCheck", forceConformanceCheck); return this; } /** * HTTP session cookie to add to every request. * * The option is a: <code>java.lang.String</code> type. * * Group: advanced * * @param sessionCookie the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder sessionCookie(String sessionCookie) { doSetProperty("sessionCookie", sessionCookie); return this; } /** * How long to block for individual read/write operations (in ms). * * The option is a: <code>java.lang.Integer</code> type. * * Default: 10000 * Group: advanced * * @param socketTimeout the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder socketTimeout(Integer socketTimeout) { doSetProperty("socketTimeout", socketTimeout); return this; } /** * How long to block for individual read/write operations (in ms). * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Default: 10000 * Group: advanced * * @param socketTimeout the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder socketTimeout(String socketTimeout) { doSetProperty("socketTimeout", socketTimeout); return this; } /** * Request that the server modify the response using the _summary param. * * The option is a: <code>java.lang.String</code> type. * * Group: advanced * * @param summary the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder summary(String summary) { doSetProperty("summary", summary); return this; } /** * When should Camel validate the FHIR Server's conformance statement. * * The option is a: <code>java.lang.String</code> type. * * Default: ONCE * Group: advanced * * @param validationMode the value to set * @return the dsl builder */ default AdvancedFhirEndpointProducerBuilder validationMode(String validationMode) { doSetProperty("validationMode", validationMode); return this; } } /** * Builder for endpoint for the FHIR component. */ public
AdvancedFhirEndpointProducerBuilder
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/profile/SuggestProfilesResponse.java
{ "start": 704, "end": 3119 }
class ____ extends ActionResponse implements ToXContentObject { private final ProfileHit[] profileHits; private final long tookInMillis; private final TotalHits totalHits; public SuggestProfilesResponse(ProfileHit[] profileHits, long tookInMillis, TotalHits totalHits) { this.profileHits = profileHits; this.tookInMillis = tookInMillis; this.totalHits = totalHits; } public ProfileHit[] getProfileHits() { return profileHits; } public long getTookInMillis() { return tookInMillis; } public TotalHits getTotalHits() { return totalHits; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeArray(profileHits); out.writeVLong(tookInMillis); Lucene.writeTotalHits(out, totalHits); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); { builder.field("took", tookInMillis); builder.startObject("total"); { builder.field("value", totalHits.value()); builder.field("relation", totalHits.relation() == TotalHits.Relation.EQUAL_TO ? "eq" : "gte"); } builder.endObject(); builder.startArray("profiles"); { for (ProfileHit profileHit : profileHits) { profileHit.toXContent(builder, params); } } builder.endArray(); } builder.endObject(); return builder; } public record ProfileHit(Profile profile, float score) implements Writeable, ToXContentObject { @Override public void writeTo(StreamOutput out) throws IOException { profile.writeTo(out); out.writeFloat(score); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); { builder.field("uid", profile.uid()); profile.user().toXContent(builder, params); builder.field("labels", profile.labels()); builder.field("data", profile.applicationData()); } builder.endObject(); return builder; } } }
SuggestProfilesResponse
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/FormContentTests.java
{ "start": 1332, "end": 1760 }
class ____ { @Test // SPR-15753 public void formContentIsNotDuplicated() throws Exception { MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Spr15753Controller()) .addFilter(new FormContentFilter()) .build(); mockMvc.perform(put("/").content("d1=a&d2=s").contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andExpect(content().string("d1:a, d2:s.")); } @RestController private static
FormContentTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CountQueryTests.java
{ "start": 15343, "end": 15590 }
class ____ extends IdBased { @ManyToOne private ParentEntity parent; public ChildEntity() { } public ChildEntity(String description, Long id, ParentEntity parent) { super( description, id ); this.parent = parent; } } }
ChildEntity
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_1400/Issue1424.java
{ "start": 458, "end": 2325 }
class ____ { private float v; public void setV(float v) { this.v = v; } @Override public String toString() { return String.valueOf(v); } } public void test_for_issue_int() { Map<String, Long> intOverflowMap = new HashMap<String, Long>(); long intOverflow = Integer.MAX_VALUE; intOverflowMap.put("v", intOverflow + 1); String sIntOverflow = JSON.toJSONString(intOverflowMap); Exception error = null; try { JSON.parseObject(sIntOverflow, IntegerVal.class); } catch (Exception e) { error = e; } assertNotNull(error); } public void test_for_issue_float() { Map<String, Double> floatOverflowMap = new HashMap<String, Double>(); double floatOverflow = Float.MAX_VALUE; floatOverflowMap.put("v", floatOverflow + 1); String sFloatOverflow = JSON.toJSONString(floatOverflowMap); assertEquals("{\"v\":3.4028234663852886E38}", sFloatOverflow); FloatVal floatVal = JSON.parseObject(sFloatOverflow, FloatVal.class); assertEquals(3.4028235E38F, floatVal.v); assertEquals(floatVal.v, Float.parseFloat("3.4028234663852886E38")); } public void test_for_issue_float_infinity() { Map<String, Double> floatOverflowMap = new HashMap<String, Double>(); double floatOverflow = Float.MAX_VALUE; floatOverflowMap.put("v", floatOverflow + floatOverflow); String sFloatOverflow = JSON.toJSONString(floatOverflowMap); System.out.println(sFloatOverflow); assertEquals("{\"v\":6.805646932770577E38}", sFloatOverflow); FloatVal floatVal = JSON.parseObject(sFloatOverflow, FloatVal.class); assertEquals(Float.parseFloat("6.805646932770577E38"), floatVal.v); } }
FloatVal
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/client/internal/ParentTaskAssigningClientTests.java
{ "start": 1540, "end": 6531 }
class ____ extends ESTestCase { public void testSetsParentId() { TaskId[] parentTaskId = new TaskId[] { new TaskId(randomAlphaOfLength(3), randomLong()) }; try (var threadPool = createThreadPool()) { // This mock will do nothing but verify that parentTaskId is set on all requests sent to it. final var mock = new NoOpClient(threadPool) { @Override protected <Request extends ActionRequest, Response extends ActionResponse> void doExecute( ActionType<Response> action, Request request, ActionListener<Response> listener ) { assertEquals(parentTaskId[0], request.getParentTask()); } }; final var client = new ParentTaskAssigningClient(mock, parentTaskId[0]); assertEquals(parentTaskId[0], client.getParentTask()); // All of these should have the parentTaskId set client.bulk(new BulkRequest()); client.search(new SearchRequest()); client.clearScroll(new ClearScrollRequest()); // Now lets verify that unwrapped calls don't have the parentTaskId set parentTaskId[0] = TaskId.EMPTY_TASK_ID; client.unwrap().bulk(new BulkRequest()); client.unwrap().search(new SearchRequest()); client.unwrap().clearScroll(new ClearScrollRequest()); } } public void testRemoteClientIsAlsoAParentAssigningClient() { TaskId parentTaskId = new TaskId(randomAlphaOfLength(3), randomLong()); try (var threadPool = createThreadPool()) { final var mockClient = new NoOpClient(threadPool) { @Override public RemoteClusterClient getRemoteClusterClient( String clusterAlias, Executor responseExecutor, RemoteClusterService.DisconnectedStrategy disconnectedStrategy ) { return new RemoteClusterClient() { @Override public <Request extends ActionRequest, Response extends TransportResponse> void execute( RemoteClusterActionType<Response> action, Request request, ActionListener<Response> listener ) { assertSame(parentTaskId, request.getParentTask()); listener.onFailure(new UnsupportedOperationException("fake remote-cluster client")); } @Override public <Request extends ActionRequest, Response extends TransportResponse> void execute( Transport.Connection connection, RemoteClusterActionType<Response> action, Request request, ActionListener<Response> listener ) { execute(action, request, listener); } @Override public <Request extends ActionRequest> void getConnection( Request request, ActionListener<Transport.Connection> listener ) { listener.onResponse(null); } }; } }; final var client = new ParentTaskAssigningClient(mockClient, parentTaskId); final var remoteClusterClient = client.getRemoteClusterClient( "remote-cluster", EsExecutors.DIRECT_EXECUTOR_SERVICE, randomFrom(RemoteClusterService.DisconnectedStrategy.values()) ); assertEquals( "fake remote-cluster client", safeAwaitFailure( UnsupportedOperationException.class, ClusterStateResponse.class, listener -> remoteClusterClient.execute( ClusterStateAction.REMOTE_TYPE, new RemoteClusterStateRequest(TEST_REQUEST_TIMEOUT), listener ) ).getMessage() ); assertEquals( "fake remote-cluster client", safeAwaitFailure( UnsupportedOperationException.class, ClusterStateResponse.class, listener -> remoteClusterClient.execute( null, ClusterStateAction.REMOTE_TYPE, new RemoteClusterStateRequest(TEST_REQUEST_TIMEOUT), listener ) ).getMessage() ); } } }
ParentTaskAssigningClientTests
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/heap/CopyOnWriteStateMapSnapshot.java
{ "start": 1557, "end": 1796 }
class ____ on proper * copy-on-write semantics through the {@link CopyOnWriteStateMap} that created the snapshot object, * but all objects in this snapshot must be considered as READ-ONLY!. The reason is that the objects * held by this
rely
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/Db2CallMetaDataProvider.java
{ "start": 899, "end": 1043 }
class ____ intended for internal use by the Simple JDBC classes. * * @author Thomas Risberg * @author Juergen Hoeller * @since 2.5 */ public
is
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CouchbaseEndpointBuilderFactory.java
{ "start": 1500, "end": 1639 }
interface ____ { /** * Builder for endpoint consumers for the Couchbase component. */ public
CouchbaseEndpointBuilderFactory
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPoint.java
{ "start": 8601, "end": 9242 }
class ____ implements SourceLocation { @Override public Class<?> getWithinType() { if (methodInvocation.getThis() == null) { throw new UnsupportedOperationException("No source location joinpoint available: target is null"); } return methodInvocation.getThis().getClass(); } @Override public String getFileName() { throw new UnsupportedOperationException(); } @Override public int getLine() { throw new UnsupportedOperationException(); } @Override @Deprecated(since = "4.0") // deprecated by AspectJ public int getColumn() { throw new UnsupportedOperationException(); } } }
SourceLocationImpl
java
elastic__elasticsearch
x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/type/PotentiallyUnmappedKeywordEsField.java
{ "start": 783, "end": 1233 }
class ____ extends KeywordEsField { public PotentiallyUnmappedKeywordEsField(String name) { super(name, Collections.emptyMap(), true, Short.MAX_VALUE, false, false, TimeSeriesFieldType.UNKNOWN); } public PotentiallyUnmappedKeywordEsField(StreamInput in) throws IOException { super(in); } public String getWriteableName() { return "PotentiallyUnmappedKeywordEsField"; } }
PotentiallyUnmappedKeywordEsField
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/TestContext.java
{ "start": 1961, "end": 4710 }
interface ____ extends AttributeAccessor, Serializable { /** * Determine if the {@linkplain ApplicationContext application context} for * this test context is known to be available. * <p>If this method returns {@code true}, a subsequent invocation of * {@link #getApplicationContext()} or {@link #markApplicationContextUnused()} * should succeed. * <p>The default implementation of this method always returns {@code false}. * Custom {@code TestContext} implementations are therefore highly encouraged * to override this method with a more meaningful implementation. Note that * the standard {@code TestContext} implementation in Spring overrides this * method appropriately. * @return {@code true} if the application context has already been loaded * @since 5.2 * @see #getApplicationContext() * @see #markApplicationContextUnused() */ default boolean hasApplicationContext() { return false; } /** * Get the {@linkplain ApplicationContext application context} for this * test context, possibly cached. * <p>Implementations of this method are responsible for loading the * application context if the corresponding context has not already been * loaded, potentially caching the context as well. * @return the application context (never {@code null}) * @throws IllegalStateException if an error occurs while retrieving the * application context * @see #hasApplicationContext() * @see #markApplicationContextUnused() */ ApplicationContext getApplicationContext(); /** * Publish the {@link ApplicationEvent} created by the given {@code eventFactory} * to the {@linkplain ApplicationContext application context} for this * test context. * <p>The {@code ApplicationEvent} will only be published if the application * context for this test context {@linkplain #hasApplicationContext() is available}. * @param eventFactory factory for lazy creation of the {@code ApplicationEvent} * @since 5.2 * @see #hasApplicationContext() * @see #getApplicationContext() */ default void publishEvent(Function<TestContext, ? extends ApplicationEvent> eventFactory) { if (hasApplicationContext()) { getApplicationContext().publishEvent(eventFactory.apply(this)); } } /** * Get the {@linkplain Class test class} for this test context. * <p>Since JUnit Jupiter 5.12, if the * {@link org.springframework.test.context.junit.jupiter.SpringExtension * SpringExtension} is used with a {@linkplain * org.junit.jupiter.api.extension.TestInstantiationAwareExtension.ExtensionContextScope#TEST_METHOD * test-method scoped} {@link org.junit.jupiter.api.extension.ExtensionContext * ExtensionContext}, the {@code Class} returned from this method may refer * to the test
TestContext
java
apache__dubbo
dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java
{ "start": 2452, "end": 6247 }
class ____<T> extends AbstractClusterInvoker<T> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FailbackClusterInvoker.class); private static final long RETRY_FAILED_PERIOD = 5; /** * Number of retries obtained from the configuration, don't contain the first invoke. */ private final int retries; private final int failbackTasks; private volatile Timer failTimer; public FailbackClusterInvoker(Directory<T> directory) { super(directory); int retriesConfig = getUrl().getParameter(RETRIES_KEY, DEFAULT_FAILBACK_TIMES); if (retriesConfig < 0) { retriesConfig = DEFAULT_FAILBACK_TIMES; } int failbackTasksConfig = getUrl().getParameter(FAIL_BACK_TASKS_KEY, DEFAULT_FAILBACK_TASKS); if (failbackTasksConfig <= 0) { failbackTasksConfig = DEFAULT_FAILBACK_TASKS; } retries = retriesConfig; failbackTasks = failbackTasksConfig; } private void addFailed( LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, Invoker<T> lastInvoker, URL consumerUrl) { if (failTimer == null) { synchronized (this) { if (failTimer == null) { failTimer = new HashedWheelTimer( new NamedThreadFactory("failback-cluster-timer", true), 1, TimeUnit.SECONDS, 32, failbackTasks); } } } RetryTimerTask retryTimerTask = new RetryTimerTask( loadbalance, invocation, invokers, lastInvoker, retries, RETRY_FAILED_PERIOD, consumerUrl); try { failTimer.newTimeout(retryTimerTask, RETRY_FAILED_PERIOD, TimeUnit.SECONDS); } catch (Throwable e) { logger.error( CLUSTER_TIMER_RETRY_FAILED, "add newTimeout exception", "", "Failback background works error, invocation->" + invocation + ", exception: " + e.getMessage(), e); } } @Override protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException { Invoker<T> invoker = null; URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl(); try { invoker = select(loadbalance, invocation, invokers, null); // Asynchronous call method must be used here, because failback will retry in the background. // Then the serviceContext will be cleared after the call is completed. return invokeWithContextAsync(invoker, invocation, consumerUrl); } catch (Throwable e) { logger.error( CLUSTER_FAILED_INVOKE_SERVICE, "Failback to invoke method and start to retries", "", "Failback to invoke method " + RpcUtils.getMethodName(invocation) + ", wait for retry in background. Ignored exception: " + e.getMessage() + ", ", e); if (retries > 0) { addFailed(loadbalance, invocation, invokers, invoker, consumerUrl); } return AsyncRpcResult.newDefaultAsyncResult(null, null, invocation); // ignore } } @Override public void destroy() { super.destroy(); if (failTimer != null) { failTimer.stop(); } } /** * RetryTimerTask */ private
FailbackClusterInvoker
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/applicationfieldaccess/NonStandardAccessTest.java
{ "start": 827, "end": 21313 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(MyAbstractMappedSuperClass.class, MyAbstractEntity.class, MyAbstractConfusingEntity.class, MyConcreteEntity.class) .addClass(ExternalClassAccessors.class) .addClass(AccessDelegate.class)) .withConfigurationResource("application.properties"); @Inject EntityManager em; @Test public void nonStandardInstanceGetterSetterPublicField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.nonStandardSetterForPublicField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.nonStandardGetterForPublicField(); } }); } @Test public void nonStandardInstanceGetterSetterProtectedField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.nonStandardSetterForProtectedField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.nonStandardGetterForProtectedField(); } }); } @Test public void nonStandardInstanceGetterSetterPackagePrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.nonStandardSetterForPackagePrivateField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.nonStandardGetterForPackagePrivateField(); } }); } @Test public void nonStandardInstanceGetterSetterPrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.nonStandardSetterForPrivateField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.nonStandardGetterForPrivateField(); } }); } @Test public void staticGetterSetterPublicField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { MyConcreteEntity.staticSetPublicField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return MyConcreteEntity.staticGetPublicField(entity); } }); } @Test public void staticGetterSetterProtectedField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { MyConcreteEntity.staticSetProtectedField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return MyConcreteEntity.staticGetProtectedField(entity); } }); } @Test public void staticGetterSetterPackagePrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { MyConcreteEntity.staticSetPackagePrivateField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return MyConcreteEntity.staticGetPackagePrivateField(entity); } }); } @Test public void staticGetterSetterPrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { MyConcreteEntity.staticSetPrivateField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return MyConcreteEntity.staticGetPrivateField(entity); } }); } @Test public void innerClassStaticGetterSetterPublicField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { MyConcreteEntity.InnerClassAccessors.staticSetPublicField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return MyConcreteEntity.InnerClassAccessors.staticGetPublicField(entity); } }); } @Test public void innerClassStaticGetterSetterProtectedField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { MyConcreteEntity.InnerClassAccessors.staticSetProtectedField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return MyConcreteEntity.InnerClassAccessors.staticGetProtectedField(entity); } }); } @Test public void innerClassStaticGetterSetterPackagePrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { MyConcreteEntity.InnerClassAccessors.staticSetPackagePrivateField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return MyConcreteEntity.InnerClassAccessors.staticGetPackagePrivateField(entity); } }); } @Test public void innerClassStaticGetterSetterPrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { MyConcreteEntity.InnerClassAccessors.staticSetPrivateField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return MyConcreteEntity.InnerClassAccessors.staticGetPrivateField(entity); } }); } @Test public void innerClassInstanceGetterSetterPublicField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { new MyConcreteEntity.InnerClassAccessors().instanceSetPublicField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return new MyConcreteEntity.InnerClassAccessors().instanceGetPublicField(entity); } }); } @Test public void innerClassInstanceGetterSetterProtectedField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { new MyConcreteEntity.InnerClassAccessors().instanceSetProtectedField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return new MyConcreteEntity.InnerClassAccessors().instanceGetProtectedField(entity); } }); } @Test public void innerClassInstanceGetterSetterPackagePrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { new MyConcreteEntity.InnerClassAccessors().instanceSetPackagePrivateField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return new MyConcreteEntity.InnerClassAccessors().instanceGetPackagePrivateField(entity); } }); } @Test public void innerClassInstanceGetterSetterPrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { new MyConcreteEntity.InnerClassAccessors().instanceSetPrivateField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return new MyConcreteEntity.InnerClassAccessors().instanceGetPrivateField(entity); } }); } @Test public void externalClassStaticGetterSetterPublicField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { ExternalClassAccessors.staticSetPublicField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return ExternalClassAccessors.staticGetPublicField(entity); } }); } @Test public void externalClassStaticGetterSetterProtectedField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { ExternalClassAccessors.staticSetProtectedField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return ExternalClassAccessors.staticGetProtectedField(entity); } }); } @Test public void externalClassStaticGetterSetterPackagePrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { ExternalClassAccessors.staticSetPackagePrivateField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return ExternalClassAccessors.staticGetPackagePrivateField(entity); } }); } @Test public void externalClassInstanceGetterSetterPublicField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { new ExternalClassAccessors().instanceSetPublicField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return new ExternalClassAccessors().instanceGetPublicField(entity); } }); } @Test public void externalClassInstanceGetterSetterProtectedField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { new ExternalClassAccessors().instanceSetProtectedField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return new ExternalClassAccessors().instanceGetProtectedField(entity); } }); } @Test public void externalClassInstanceGetterSetterPackagePrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { new ExternalClassAccessors().instanceSetPackagePrivateField(entity, value); } @Override public Long getValue(MyConcreteEntity entity) { return new ExternalClassAccessors().instanceGetPackagePrivateField(entity); } }); } @Test public void mappedSuperClassSubClassInstanceGetterSetterPublicField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.setAbstractEntityPublicField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.getAbstractEntityPublicField(); } }); } @Test public void mappedSuperClassSubClassInstanceGetterSetterProtectedField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.setAbstractEntityProtectedField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.getAbstractEntityProtectedField(); } }); } @Test public void mappedSuperClassSubClassInstanceGetterSetterPackagePrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.setAbstractEntityPackagePrivateField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.getAbstractEntityPackagePrivateField(); } }); } @Test public void mappedSuperClassSubClassNonStandardInstanceGetterSetterPublicField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.nonStandardSetterForAbstractEntityPublicField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.nonStandardGetterForAbstractEntityPublicField(); } }); } @Test public void mappedSuperClassSubClassNonStandardInstanceGetterSetterProtectedField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.nonStandardSetterForAbstractEntityProtectedField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.nonStandardGetterForAbstractEntityProtectedField(); } }); } @Test public void mappedSuperClassSubClassNonStandardInstanceGetterSetterPackagePrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.nonStandardSetterForAbstractEntityPackagePrivateField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.nonStandardGetterForAbstractEntityPackagePrivateField(); } }); } @Test public void entitySubClassInstanceGetterSetterPublicField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.setAbstractEntityPublicField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.getAbstractEntityPublicField(); } }); } @Test public void entitySubClassInstanceGetterSetterProtectedField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.setAbstractEntityProtectedField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.getAbstractEntityProtectedField(); } }); } @Test public void entitySubClassInstanceGetterSetterPackagePrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.setAbstractEntityPackagePrivateField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.getAbstractEntityPackagePrivateField(); } }); } @Test public void entitySubClassNonStandardInstanceGetterSetterPublicField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.nonStandardSetterForAbstractEntityPublicField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.nonStandardGetterForAbstractEntityPublicField(); } }); } @Test public void entitySubClassNonStandardInstanceGetterSetterProtectedField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.nonStandardSetterForAbstractEntityProtectedField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.nonStandardGetterForAbstractEntityProtectedField(); } }); } @Test public void entitySubClassNonStandardInstanceGetterSetterPackagePrivateField() { doTestFieldAccess(new AccessDelegate() { @Override public void setValue(MyConcreteEntity entity, Long value) { entity.nonStandardSetterForAbstractEntityPackagePrivateField(value); } @Override public Long getValue(MyConcreteEntity entity) { return entity.nonStandardGetterForAbstractEntityPackagePrivateField(); } }); } // Ideally we'd make this a @ParameterizedTest and pass the access delegate as parameter, // but we cannot do that due to JUnit using a different classloader than the test. private void doTestFieldAccess(AccessDelegate delegate) { Long id = QuarkusTransaction.disallowingExisting().call(() -> { var entity = new MyConcreteEntity(); em.persist(entity); return entity.id; }); QuarkusTransaction.disallowingExisting().run(() -> { var entity = em.find(MyConcreteEntity.class, id); assertThat(delegate.getValue(entity)) .as("Loaded value before update") .isNull(); }); QuarkusTransaction.disallowingExisting().run(() -> { var entity = em.getReference(MyConcreteEntity.class, id); // Since field access is replaced with accessor calls, // we expect this change to be detected by dirty tracking and persisted. delegate.setValue(entity, 42L); }); QuarkusTransaction.disallowingExisting().run(() -> { var entity = em.find(MyConcreteEntity.class, id); // We're working on an initialized entity. assertThat(entity) .as("find() should return uninitialized entity") .returns(true, Hibernate::isInitialized); // The above should have persisted a value that passes the assertion. assertThat(delegate.getValue(entity)) .as("Loaded value after update") .isEqualTo(42L); }); QuarkusTransaction.disallowingExisting().run(() -> { var entity = em.getReference(MyConcreteEntity.class, id); // We're working on an uninitialized entity. assertThat(entity) .as("getReference() should return uninitialized entity") .returns(false, Hibernate::isInitialized); // The above should have persisted a value that passes the assertion. assertThat(delegate.getValue(entity)) .as("Lazily loaded value after update") .isEqualTo(42L); // Accessing the value should trigger initialization of the entity. assertThat(entity) .as("Getting the value should initialize the entity") .returns(true, Hibernate::isInitialized); }); } @MappedSuperclass public static abstract
NonStandardAccessTest
java
apache__kafka
trogdor/src/main/java/org/apache/kafka/trogdor/fault/NetworkPartitionFaultSpec.java
{ "start": 1281, "end": 2768 }
class ____ extends TaskSpec { private final List<List<String>> partitions; @JsonCreator public NetworkPartitionFaultSpec(@JsonProperty("startMs") long startMs, @JsonProperty("durationMs") long durationMs, @JsonProperty("partitions") List<List<String>> partitions) { super(startMs, durationMs); this.partitions = partitions == null ? new ArrayList<>() : partitions; } @JsonProperty public List<List<String>> partitions() { return partitions; } @Override public TaskController newController(String id) { return new NetworkPartitionFaultController(partitionSets()); } @Override public TaskWorker newTaskWorker(String id) { return new NetworkPartitionFaultWorker(id, partitionSets()); } private List<Set<String>> partitionSets() { List<Set<String>> partitionSets = new ArrayList<>(); HashSet<String> prevNodes = new HashSet<>(); for (List<String> partition : this.partitions()) { for (String nodeName : partition) { if (prevNodes.contains(nodeName)) { throw new RuntimeException("Node " + nodeName + " appears in more than one partition."); } prevNodes.add(nodeName); partitionSets.add(new HashSet<>(partition)); } } return partitionSets; } }
NetworkPartitionFaultSpec
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/job/metrics/DoubleAccumulator.java
{ "start": 4614, "end": 5215 }
class ____ implements DoubleAccumulator { public static final String NAME = "max"; private double value; private DoubleMaximum(double init) { value = init; } @Override public void add(double value) { this.value = Math.max(this.value, value); } @Override public double getValue() { return value; } @Override public String getName() { return NAME; } } /** {@link DoubleAccumulator} that returns the minimum value. */ final
DoubleMaximum
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/filter/headers/observation/ObservedRequestHttpHeadersFilter.java
{ "start": 1544, "end": 4329 }
class ____ implements HttpHeadersFilter { private static final Log log = LogFactory.getLog(ObservedRequestHttpHeadersFilter.class); private final ObservationRegistry observationRegistry; @Nullable private final GatewayObservationConvention customGatewayObservationConvention; public ObservedRequestHttpHeadersFilter(ObservationRegistry observationRegistry) { this(observationRegistry, null); } public ObservedRequestHttpHeadersFilter(ObservationRegistry observationRegistry, @Nullable GatewayObservationConvention customGatewayObservationConvention) { this.observationRegistry = observationRegistry; this.customGatewayObservationConvention = customGatewayObservationConvention; } @Override public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) { HttpHeaders newHeaders = new HttpHeaders(); newHeaders.putAll(input); if (log.isDebugEnabled()) { log.debug("Will instrument the HTTP request headers " + newHeaders); } Observation parentObservation = getParentObservation(exchange); GatewayContext gatewayContext = new GatewayContext(newHeaders, exchange.getRequest(), exchange); Observation childObservation = GatewayDocumentedObservation.GATEWAY_HTTP_CLIENT_OBSERVATION.observation( this.customGatewayObservationConvention, DefaultGatewayObservationConvention.INSTANCE, () -> gatewayContext, this.observationRegistry); if (parentObservation != null) { childObservation.parentObservation(parentObservation); } childObservation.start(); if (log.isDebugEnabled()) { log.debug("Client observation " + childObservation + " created for the request. New headers are " + newHeaders); } exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_OBSERVATION_ATTR, childObservation); return newHeaders; } /** * The "micrometer.observation" key comes from * {@link io.micrometer.observation.contextpropagation.ObservationThreadLocalAccessor} * that requires the Context Propagation library on the classpath. Since we don't know * if it will be there on the classpath we're referencing the key via a String and * then we're testing its presence in tests via a fixed test dependency to Context * Propagation and {@code ObservationThreadLocalAccessor}. * @param exchange server web exchange * @return parent observation or {@code null} when there is none */ @Nullable private Observation getParentObservation(ServerWebExchange exchange) { ContextView contextView = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REACTOR_CONTEXT_ATTR); if (contextView == null) { return null; } return contextView.getOrDefault("micrometer.observation", null); } @Override public boolean supports(Type type) { return type.equals(Type.REQUEST); } }
ObservedRequestHttpHeadersFilter
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/api/graph/JobGraphGeneratorTestBase.java
{ "start": 117880, "end": 119306 }
class ____ extends AbstractStreamOperatorFactory<Integer> implements CoordinatedOperatorFactory<Integer> { private final boolean isOperatorFactorySerializable; SerializationTestOperatorFactory(boolean isOperatorFactorySerializable) { this.isOperatorFactorySerializable = isOperatorFactorySerializable; } @Override public OperatorCoordinator.Provider getCoordinatorProvider( String operatorName, OperatorID operatorID) { return new NonSerializableCoordinatorProvider(); } private void writeObject(ObjectOutputStream oos) throws IOException { if (!isOperatorFactorySerializable) { throw new IOException("This operator factory is not serializable."); } } @Override public <T extends StreamOperator<Integer>> T createStreamOperator( StreamOperatorParameters<Integer> parameters) { // today's lunch is generics spaghetti @SuppressWarnings("unchecked") final T castedOperator = (T) new SerializationTestOperator(); return castedOperator; } @Override public Class<? extends StreamOperator> getStreamOperatorClass(ClassLoader classLoader) { return SerializationTestOperator.class; } } private static
SerializationTestOperatorFactory
java
apache__camel
components/camel-github/src/test/java/org/apache/camel/component/github/services/MockRepositoryService.java
{ "start": 1236, "end": 2157 }
class ____ extends RepositoryService { protected static final Logger LOG = LoggerFactory.getLogger(MockRepositoryService.class); private List<RepositoryTag> tags = new ArrayList<>(); public RepositoryTag addTag(String tagName) { RepositoryTag tag = new RepositoryTag(); tag.setName(tagName); tags.add(tag); return tag; } @Override public Repository getRepository(final String owner, final String name) { Repository repository = new Repository(); User user = new User(); user.setName(owner); user.setLogin(owner); repository.setOwner(user); repository.setName(name); return repository; } @Override public List<RepositoryTag> getTags(IRepositoryIdProvider repository) { LOG.debug("in MockRepositoryService returning {} tags", tags.size()); return tags; } }
MockRepositoryService
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/SplunkHecComponentBuilderFactory.java
{ "start": 1953, "end": 5353 }
interface ____ extends ComponentBuilder<SplunkHECComponent> { /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default SplunkHecComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default SplunkHecComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * Sets the default SSL configuration to use for all the endpoints. You * can also configure it directly at the endpoint level. * * The option is a: * &lt;code&gt;org.apache.camel.support.jsse.SSLContextParameters&lt;/code&gt; type. * * Group: security * * @param sslContextParameters the value to set * @return the dsl builder */ default SplunkHecComponentBuilder sslContextParameters(org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) { doSetProperty("sslContextParameters", sslContextParameters); return this; } /** * Enable usage of global SSL context parameters. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param useGlobalSslContextParameters the value to set * @return the dsl builder */ default SplunkHecComponentBuilder useGlobalSslContextParameters(boolean useGlobalSslContextParameters) { doSetProperty("useGlobalSslContextParameters", useGlobalSslContextParameters); return this; } }
SplunkHecComponentBuilder
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/InterfaceTest.java
{ "start": 826, "end": 892 }
interface ____ { @JSONField(name="Name") String getName(); } }
IB
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/SuggesterTest.java
{ "start": 21216, "end": 21688 }
class ____ { @Deprecated public String foo(String input) { { return input.toLowerCase(); } } } """) .expectUnchanged() .doTest(); } @Test public void ternaryOverMultipleLines() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final
Client
java
elastic__elasticsearch
libs/core/src/main/java/org/elasticsearch/core/ReleasableIterator.java
{ "start": 645, "end": 2201 }
interface ____<T> extends Releasable, Iterator<T> { /** * Returns a single element iterator over the supplied value. */ static <T extends Releasable> ReleasableIterator<T> single(T element) { return new ReleasableIterator<>() { private T value = Objects.requireNonNull(element); @Override public boolean hasNext() { return value != null; } @Override public T next() { final T res = value; value = null; return res; } @Override public void close() { Releasables.close(value); } @Override public String toString() { return "ReleasableIterator[" + value + "]"; } }; } /** * Returns an empty iterator over the supplied value. */ static <T extends Releasable> ReleasableIterator<T> empty() { return new ReleasableIterator<>() { @Override public boolean hasNext() { return false; } @Override public T next() { assert false : "hasNext is always false so next should never be called"; return null; } @Override public void close() {} @Override public String toString() { return "ReleasableIterator[<empty>]"; } }; } }
ReleasableIterator
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/cache/SpringExtensionContextCacheTests.java
{ "start": 2357, "end": 4024 }
class ____ { private static ApplicationContext dirtiedApplicationContext; @Autowired ApplicationContext applicationContext; @BeforeAll static void verifyInitialCacheState() { dirtiedApplicationContext = null; resetContextCache(); assertContextCacheStatistics("BeforeClass", 0, 0, 0, 0); } @AfterAll static void verifyFinalCacheState() { assertContextCacheStatistics("AfterClass", 1, 1, 1, 2); } @Test @DirtiesContext @Order(1) void dirtyContext() { assertContextCacheStatistics("dirtyContext()", 1, 1, 0, 1); assertThat(this.applicationContext).as("The application context should have been autowired.").isNotNull(); SpringExtensionContextCacheTests.dirtiedApplicationContext = this.applicationContext; } @Test @Order(2) void verifyContextDirty() { assertContextCacheStatistics("verifyContextWasDirtied()", 1, 1, 0, 2); assertThat(this.applicationContext).as("The application context should have been autowired.").isNotNull(); assertThat(this.applicationContext).as("The application context should have been 'dirtied'.").isNotSameAs(SpringExtensionContextCacheTests.dirtiedApplicationContext); SpringExtensionContextCacheTests.dirtiedApplicationContext = this.applicationContext; } @Test @Order(3) void verifyContextNotDirty() { assertContextCacheStatistics("verifyContextWasNotDirtied()", 1, 1, 1, 2); assertThat(this.applicationContext).as("The application context should have been autowired.").isNotNull(); assertThat(this.applicationContext).as("The application context should NOT have been 'dirtied'.").isSameAs(SpringExtensionContextCacheTests.dirtiedApplicationContext); } }
SpringExtensionContextCacheTests
java
apache__camel
core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultConsumerTemplate.java
{ "start": 1584, "end": 9716 }
class ____ extends ServiceSupport implements ConsumerTemplate { private static final Logger LOG = LoggerFactory.getLogger(DefaultConsumerTemplate.class); private final CamelContext camelContext; private ConsumerCache consumerCache; private int maximumCacheSize; public DefaultConsumerTemplate(CamelContext camelContext) { this.camelContext = camelContext; } @Override public int getMaximumCacheSize() { return maximumCacheSize; } @Override public void setMaximumCacheSize(int maximumCacheSize) { this.maximumCacheSize = maximumCacheSize; } @Override public int getCurrentCacheSize() { if (consumerCache == null) { return 0; } return consumerCache.size(); } @Override public void cleanUp() { if (consumerCache != null) { consumerCache.cleanUp(); } } @Override public CamelContext getCamelContext() { return camelContext; } @Override public Exchange receive(String endpointUri) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return getConsumerCache().receive(endpoint); } @Override public Exchange receive(Endpoint endpoint) { return receive(endpoint.getEndpointUri()); } @Override public Exchange receive(String endpointUri, long timeout) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return getConsumerCache().receive(endpoint, timeout); } @Override public Exchange receive(Endpoint endpoint, long timeout) { return receive(endpoint.getEndpointUri(), timeout); } @Override public Exchange receiveNoWait(String endpointUri) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return getConsumerCache().receiveNoWait(endpoint); } @Override public Exchange receiveNoWait(Endpoint endpoint) { return receiveNoWait(endpoint.getEndpointUri()); } @Override public Object receiveBody(String endpointUri) { return receiveBody(receive(endpointUri)); } @Override public Object receiveBody(Endpoint endpoint) { return receiveBody(endpoint.getEndpointUri()); } @Override public Object receiveBody(String endpointUri, long timeout) { return receiveBody(receive(endpointUri, timeout)); } @Override public Object receiveBody(Endpoint endpoint, long timeout) { return receiveBody(endpoint.getEndpointUri(), timeout); } @Override public Object receiveBodyNoWait(String endpointUri) { return receiveBody(receiveNoWait(endpointUri)); } private Object receiveBody(Exchange exchange) { Object answer; try { answer = extractResultBody(exchange); } finally { doneUoW(exchange); } return answer; } @Override public Object receiveBodyNoWait(Endpoint endpoint) { return receiveBodyNoWait(endpoint.getEndpointUri()); } @Override @SuppressWarnings("unchecked") public <T> T receiveBody(String endpointUri, Class<T> type) { Object answer; Exchange exchange = receive(endpointUri); try { answer = extractResultBody(exchange); answer = camelContext.getTypeConverter().convertTo(type, exchange, answer); } finally { doneUoW(exchange); } return (T) answer; } @Override public <T> T receiveBody(Endpoint endpoint, Class<T> type) { return receiveBody(endpoint.getEndpointUri(), type); } @Override @SuppressWarnings("unchecked") public <T> T receiveBody(String endpointUri, long timeout, Class<T> type) { Object answer; Exchange exchange = receive(endpointUri, timeout); try { answer = extractResultBody(exchange); answer = camelContext.getTypeConverter().convertTo(type, exchange, answer); } finally { doneUoW(exchange); } return (T) answer; } @Override public <T> T receiveBody(Endpoint endpoint, long timeout, Class<T> type) { return receiveBody(endpoint.getEndpointUri(), timeout, type); } @Override @SuppressWarnings("unchecked") public <T> T receiveBodyNoWait(String endpointUri, Class<T> type) { Object answer; Exchange exchange = receiveNoWait(endpointUri); try { answer = extractResultBody(exchange); answer = camelContext.getTypeConverter().convertTo(type, exchange, answer); } finally { doneUoW(exchange); } return (T) answer; } @Override public <T> T receiveBodyNoWait(Endpoint endpoint, Class<T> type) { return receiveBodyNoWait(endpoint.getEndpointUri(), type); } @Override public void doneUoW(Exchange exchange) { try { // The receiveBody method will get a null exchange if (exchange == null) { return; } if (exchange.getUnitOfWork() == null) { // handover completions and done them manually to ensure they are being executed List<Synchronization> synchronizations = exchange.getExchangeExtension().handoverCompletions(); UnitOfWorkHelper.doneSynchronizations(exchange, synchronizations); } else { // done the unit of work exchange.getUnitOfWork().done(exchange); } } catch (Exception e) { LOG.warn("Exception occurred during done UnitOfWork for Exchange: {}. This exception will be ignored.", exchange, e); } } protected Endpoint resolveMandatoryEndpoint(String endpointUri) { return CamelContextHelper.getMandatoryEndpoint(camelContext, endpointUri); } /** * Extracts the body from the given result. * <p/> * If the exchange pattern is provided it will try to honor it and retrieve the body from either IN or OUT according * to the pattern. * * @param result the result * @return the result, can be <tt>null</tt>. */ protected Object extractResultBody(Exchange result) { Object answer = null; if (result != null) { // rethrow if there was an exception if (result.getException() != null) { throw wrapRuntimeCamelException(result.getException()); } // okay no fault then return the response answer = result.getMessage().getBody(); // in a very seldom situation then getBody can cause an exception to be set on the exchange // rethrow if there was an exception during execution if (result.getException() != null) { throw wrapRuntimeCamelException(result.getException()); } } return answer; } private org.apache.camel.spi.ConsumerCache getConsumerCache() { if (!isStarted()) { throw new IllegalStateException("ConsumerTemplate has not been started"); } return consumerCache; } @Override protected void doBuild() throws Exception { if (consumerCache == null) { consumerCache = new DefaultConsumerCache(this, camelContext, maximumCacheSize); } ServiceHelper.buildService(consumerCache); } @Override protected void doInit() throws Exception { ServiceHelper.initService(consumerCache); } @Override protected void doStart() throws Exception { ServiceHelper.startService(consumerCache); } @Override protected void doStop() throws Exception { ServiceHelper.stopService(consumerCache); } @Override protected void doShutdown() throws Exception { // we should shutdown the services as this is our intention, to not re-use the services anymore ServiceHelper.stopAndShutdownService(consumerCache); consumerCache = null; } }
DefaultConsumerTemplate
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/embeddables/EmbeddableQuery.java
{ "start": 1076, "end": 3575 }
class ____ { private Integer personId; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { // Revision 1 this.personId = scope.fromTransaction( entityManager -> { NameInfo ni = new NameInfo( "John", "Doe" ); Person person1 = new Person( "JDOE", ni ); entityManager.persist( person1 ); return person1.getId(); } ); // Revision 2 scope.inTransaction( entityManager -> { Person person1 = entityManager.find( Person.class, personId ); person1.getNameInfo().setFirstName( "Jane" ); entityManager.merge( person1 ); } ); // Revision 3 scope.inTransaction( entityManager -> { Person person1 = entityManager.find( Person.class, personId ); person1.setName( "JDOE2" ); entityManager.merge( person1 ); } ); } @Test public void testRevisionCounts(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { assertEquals( 3, AuditReaderFactory.get( em ).getRevisions( Person.class, personId ).size() ); } ); } @Test public void testAuditQueryUsingEmbeddableEquals(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final NameInfo nameInfo = new NameInfo( "John", "Doe" ); final AuditQuery query = AuditReaderFactory.get( em ).createQuery() .forEntitiesAtRevision( Person.class, 1 ); query.add( AuditEntity.property( "nameInfo" ).eq( nameInfo ) ); List<?> results = query.getResultList(); assertEquals( 1, results.size() ); final Person person = (Person) results.get( 0 ); assertEquals( nameInfo, person.getNameInfo() ); } ); } @Test public void testAuditQueryUsingEmbeddableNotEquals(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final NameInfo nameInfo = new NameInfo( "Jane", "Doe" ); final AuditQuery query = AuditReaderFactory.get( em ).createQuery() .forEntitiesAtRevision( Person.class, 1 ); query.add( AuditEntity.property( "nameInfo" ).ne( nameInfo ) ); assertEquals( 0, query.getResultList().size() ); } ); } @Test public void testAuditQueryUsingEmbeddableNonEqualityCheck(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { try { final NameInfo nameInfo = new NameInfo( "John", "Doe" ); final AuditQuery query = AuditReaderFactory.get( em ).createQuery() .forEntitiesAtRevision( Person.class, 1 ); query.add( AuditEntity.property( "nameInfo" ).le( nameInfo ) ); } catch (Exception ex) { assertInstanceOf( AuditException.class, ex ); } } ); } }
EmbeddableQuery
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/InternalRealmsSettings.java
{ "start": 1077, "end": 2072 }
class ____ { private InternalRealmsSettings() {} /** * Provides the {@link Setting setting configuration} for each <em>internal</em> realm type. * This excludes the ReservedRealm, as it cannot be configured dynamically. */ public static Set<Setting.AffixSetting<?>> getSettings() { Set<Setting.AffixSetting<?>> set = new HashSet<>(); set.addAll(FileRealmSettings.getSettings()); set.addAll(NativeRealmSettings.getSettings()); set.addAll(LdapRealmSettings.getSettings(LdapRealmSettings.AD_TYPE)); set.addAll(LdapRealmSettings.getSettings(LdapRealmSettings.LDAP_TYPE)); set.addAll(PkiRealmSettings.getSettings()); set.addAll(SingleSpSamlRealmSettings.getSettings()); set.addAll(KerberosRealmSettings.getSettings()); set.addAll(OpenIdConnectRealmSettings.getSettings()); set.addAll(JwtRealmSettings.getSettings()); return Collections.unmodifiableSet(set); } }
InternalRealmsSettings
java
apache__flink
flink-rpc/flink-rpc-akka/src/test/java/org/apache/flink/runtime/rpc/pekko/ContextClassLoadingSettingTest.java
{ "start": 18723, "end": 21399 }
class ____ extends RpcEndpoint implements TestEndpointGateway { private final CompletableFuture<ClassLoader> onStartClassLoader = new CompletableFuture<>(); private final CompletableFuture<ClassLoader> onStopClassLoader = new CompletableFuture<>(); private final CompletableFuture<ClassLoader> voidOperationClassLoader = new CompletableFuture<>(); private final CompletableFuture<Void> rpcResponseFuture = new CompletableFuture<>(); @Nullable private final PickyObject pickyObject; protected TestEndpoint(RpcService rpcService) { this(rpcService, null); } protected TestEndpoint(RpcService rpcService, @Nullable PickyObject pickyObject) { super(rpcService); this.pickyObject = pickyObject; } @Override protected void onStart() throws Exception { onStartClassLoader.complete(Thread.currentThread().getContextClassLoader()); super.onStart(); } @Override protected CompletableFuture<Void> onStop() { onStopClassLoader.complete(Thread.currentThread().getContextClassLoader()); return CompletableFuture.completedFuture(null); } @Override public CompletableFuture<Void> doSomethingAsync() { return rpcResponseFuture; } public CompletableFuture<ClassLoader> doCallAsync() { return callAsync( () -> Thread.currentThread().getContextClassLoader(), Duration.ofSeconds(10)); } public CompletableFuture<ClassLoader> doRunAsync() { final CompletableFuture<ClassLoader> contextClassLoader = new CompletableFuture<>(); runAsync( () -> contextClassLoader.complete( Thread.currentThread().getContextClassLoader())); return contextClassLoader; } @Override public void doSomethingWithoutReturningAnything() { voidOperationClassLoader.complete(Thread.currentThread().getContextClassLoader()); } @Override public CompletableFuture<PickyObject> getPickyObject() { return CompletableFuture.completedFuture(pickyObject); } public void completeRPCFuture() { rpcResponseFuture.complete(null); } @Override @Local public CompletableFuture<ClassLoader> getContextClassLoader() { return CompletableFuture.completedFuture( Thread.currentThread().getContextClassLoader()); } } }
TestEndpoint
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelProcessorEnableAction.java
{ "start": 1163, "end": 1426 }
class ____ extends CamelProcessorAction { public CamelProcessorEnableAction(CamelJBangMain main) { super(main); } @Override protected void onAction(JsonObject root) { root.put("command", "enable"); } }
CamelProcessorEnableAction
java
apache__flink
flink-state-backends/flink-statebackend-forst/src/main/java/org/apache/flink/state/forst/ForStOperationUtils.java
{ "start": 16175, "end": 16708 }
class ____ implements AutoCloseable { public final ColumnFamilyHandle columnFamilyHandle; public final RegisteredStateMetaInfoBase metaInfo; public ForStKvStateInfo( ColumnFamilyHandle columnFamilyHandle, RegisteredStateMetaInfoBase metaInfo) { this.columnFamilyHandle = columnFamilyHandle; this.metaInfo = metaInfo; } @Override public void close() throws Exception { this.columnFamilyHandle.close(); } } }
ForStKvStateInfo
java
apache__rocketmq
test/src/main/java/org/apache/rocketmq/test/client/rmq/RMQPopConsumer.java
{ "start": 1704, "end": 4147 }
class ____ extends RMQNormalConsumer { private static final Logger log = LoggerFactory.getLogger(RMQPopConsumer.class); public static final long POP_TIMEOUT = 3000; public static final long DEFAULT_INVISIBLE_TIME = 30000; private RMQPopClient client; private int maxNum = 16; public RMQPopConsumer(String nsAddr, String topic, String subExpression, String consumerGroup, AbstractListener listener) { super(nsAddr, topic, subExpression, consumerGroup, listener); } public RMQPopConsumer(String nsAddr, String topic, String subExpression, String consumerGroup, AbstractListener listener, int maxNum) { super(nsAddr, topic, subExpression, consumerGroup, listener); this.maxNum = maxNum; } @Override public void start() { client = ConsumerFactory.getRMQPopClient(); log.info("consumer[{}] started!", consumerGroup); } @Override public void shutdown() { client.shutdown(); } public PopResult pop(String brokerAddr, MessageQueue mq) throws Exception { return this.pop(brokerAddr, mq, DEFAULT_INVISIBLE_TIME, 5000); } public PopResult pop(String brokerAddr, MessageQueue mq, long invisibleTime, long timeout) throws InterruptedException, RemotingException, MQClientException, MQBrokerException, ExecutionException, TimeoutException { CompletableFuture<PopResult> future = this.client.popMessageAsync( brokerAddr, mq, invisibleTime, maxNum, consumerGroup, timeout, true, ConsumeInitMode.MIN, false, ExpressionType.TAG, "*"); return future.get(); } public PopResult popOrderly(String brokerAddr, MessageQueue mq) throws Exception { return this.popOrderly(brokerAddr, mq, DEFAULT_INVISIBLE_TIME, 5000); } public PopResult popOrderly(String brokerAddr, MessageQueue mq, long invisibleTime, long timeout) throws InterruptedException, ExecutionException { CompletableFuture<PopResult> future = this.client.popMessageAsync( brokerAddr, mq, invisibleTime, maxNum, consumerGroup, timeout, true, ConsumeInitMode.MIN, true, ExpressionType.TAG, "*"); return future.get(); } public CompletableFuture<AckResult> ackAsync(String brokerAddr, String extraInfo) { return this.client.ackMessageAsync(brokerAddr, topic, consumerGroup, extraInfo); } }
RMQPopConsumer
java
micronaut-projects__micronaut-core
http-client-core/src/main/java/io/micronaut/http/client/sse/SseClientFactory.java
{ "start": 937, "end": 1821 }
interface ____ { /** * Create a new {@link SseClient}. Note that this method should only be used outside the context of an application. Within Micronaut use * {@link jakarta.inject.Inject} to inject a client instead * * @param url The base URL * @return The client */ @NonNull SseClient createSseClient(@Nullable URL url); /** * Create a new {@link SseClient} with the specified configuration. Note that this method should only be used * outside the context of an application. Within Micronaut use {@link jakarta.inject.Inject} to inject a client instead * * @param url The base URL * @param configuration the client configuration * @return The client * @since 2.2.0 */ @NonNull SseClient createSseClient(@Nullable URL url, @NonNull HttpClientConfiguration configuration); }
SseClientFactory
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/runtime/types/GenericArrayTypeImpl.java
{ "start": 175, "end": 1422 }
class ____ implements GenericArrayType { private Type genericComponentType; public GenericArrayTypeImpl(Type genericComponentType) { this.genericComponentType = genericComponentType; } public GenericArrayTypeImpl(Class<?> rawType, Type... actualTypeArguments) { this.genericComponentType = new ParameterizedTypeImpl(rawType, actualTypeArguments); } @Override public Type getGenericComponentType() { return genericComponentType; } @Override public int hashCode() { return ((genericComponentType == null) ? 0 : genericComponentType.hashCode()); } @Override public boolean equals(Object obj) { if (obj instanceof GenericArrayType that) { if (genericComponentType == null) { return that.getGenericComponentType() == null; } else { return genericComponentType.equals(that.getGenericComponentType()); } } else { return false; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(genericComponentType.toString()); sb.append("[]"); return sb.toString(); } }
GenericArrayTypeImpl
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/CodeTemplates.java
{ "start": 14457, "end": 14780 }
class ____ { @Advice.OnMethodEnter static void enter(@Advice.FieldValue(EnhancerConstants.TRACKER_COMPOSITE_FIELD_NAME) CompositeOwnerTracker $$_hibernate_compositeOwners) { if ( $$_hibernate_compositeOwners != null ) { $$_hibernate_compositeOwners.callOwner( "" ); } } } static
CompositeDirtyCheckingHandler
java
apache__camel
components/camel-google/camel-google-sheets/src/test/java/org/apache/camel/component/google/sheets/SheetsSpreadsheetsValuesIT.java
{ "start": 7064, "end": 10188 }
class ____ extends AbstractGoogleSheetsTestSupport { private Spreadsheet testSheet = getSpreadsheet(); private List<List<Object>> data = Collections.singletonList(Arrays.asList("A10", "B10", "C10")); private String range = TEST_SHEET + "!A10"; private String updateRange = TEST_SHEET + "!" + data.get(0).get(0) + ":" + data.get(0).get(data.get(0).size() - 1); @Test public void test() throws Exception { final Map<String, Object> headers = new HashMap<>(); // parameter type is String headers.put(GoogleSheetsConstants.PROPERTY_PREFIX + "spreadsheetId", testSheet.getSpreadsheetId()); // parameter type is String headers.put(GoogleSheetsConstants.PROPERTY_PREFIX + "range", range); // parameter type is com.google.api.services.sheets.v4.model.ValueRange headers.put(GoogleSheetsConstants.PROPERTY_PREFIX + "values", new ValueRange().setValues(data)); // parameter type is String headers.put(GoogleSheetsConstants.PROPERTY_PREFIX + "valueInputOption", "USER_ENTERED"); final AppendValuesResponse result = requestBodyAndHeaders("direct://APPEND", null, headers); assertNotNull(result, "append result is null"); assertEquals(testSheet.getSpreadsheetId(), result.getSpreadsheetId()); assertEquals(updateRange, result.getUpdates().getUpdatedRange()); assertEquals(data.size(), result.getUpdates().getUpdatedRows()); assertEquals(data.get(0).size(), result.getUpdates().getUpdatedCells()); LOG.debug("append: {}", result); } @Override protected GoogleSheetsClientFactory getClientFactory() throws Exception { return new MockGoogleSheetsClientFactory( new MockLowLevelHttpResponse() .setContent( "{" + "\"spreadsheetId\": \"" + testSheet.getSpreadsheetId() + "\"," + "\"updates\":" + "{" + "\"spreadsheetId\": \"" + testSheet.getSpreadsheetId() + "\"," + "\"updatedRange\": \"" + updateRange + "\"," + "\"updatedRows\": " + data.size() + "," + "\"updatedColumns\": " + Optional.ofNullable(data.get(0)).map(Collection::size).orElse(0) + "," + "\"updatedCells\": " + data.size() * Optional.ofNullable(data.get(0)).map(Collection::size).orElse(0) + "}" + "}")); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct://APPEND") .to("google-sheets://" + PATH_PREFIX + "/append"); } }; } } @Nested
AppendIT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingWithUnidirectionalOneToOneJoinColumn.java
{ "start": 686, "end": 1665 }
class ____ extends BaseInsertOrderingTest { @Override protected Class<?>[] getAnnotatedClasses() { return new Class<?>[] { Person.class, Address.class }; } @Test public void testBatchingWithEmbeddableId() { sessionFactoryScope().inTransaction( session -> { final PersonAddressId id = new PersonAddressId(); id.setId( 1 ); Person person = new Person(); person.setId( id ); session.persist( person ); Address address = new Address(); address.setId( id ); address.setPerson( person ); session.persist( address ); clearBatches(); } ); verifyContainsBatches( new Batch( "insert into Person (name,id) values (?,?)" ), new Batch( "insert into Address (street,id) values (?,?)" ) ); sessionFactoryScope().inTransaction( session -> { Query query = session.createQuery( "FROM Person" ); assertEquals( 1, query.getResultList().size() ); } ); } @Embeddable public static
InsertOrderingWithUnidirectionalOneToOneJoinColumn
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/filter/FilterParameterTests.java
{ "start": 15454, "end": 15583 }
class ____ implements Supplier<String> { @Override public String get() { return "FIRST"; } } }
EntityFourDepartmentResolver
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/HandlerMethodArgumentResolverComposite.java
{ "start": 1276, "end": 4403 }
class ____ implements HandlerMethodArgumentResolver { private final List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>(); private final Map<MethodParameter, HandlerMethodArgumentResolver> argumentResolverCache = new ConcurrentHashMap<>(256); /** * Add the given {@link HandlerMethodArgumentResolver}. */ public HandlerMethodArgumentResolverComposite addResolver(HandlerMethodArgumentResolver resolver) { this.argumentResolvers.add(resolver); return this; } /** * Add the given {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers}. * @since 4.3 */ public HandlerMethodArgumentResolverComposite addResolvers( @Nullable HandlerMethodArgumentResolver... resolvers) { if (resolvers != null) { Collections.addAll(this.argumentResolvers, resolvers); } return this; } /** * Add the given {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers}. */ public HandlerMethodArgumentResolverComposite addResolvers( @Nullable List<? extends HandlerMethodArgumentResolver> resolvers) { if (resolvers != null) { this.argumentResolvers.addAll(resolvers); } return this; } /** * Return a read-only list with the contained resolvers, or an empty list. */ public List<HandlerMethodArgumentResolver> getResolvers() { return Collections.unmodifiableList(this.argumentResolvers); } /** * Clear the list of configured resolvers and the resolver cache. */ public void clear() { this.argumentResolvers.clear(); this.argumentResolverCache.clear(); } /** * Whether the given {@linkplain MethodParameter method parameter} is * supported by any registered {@link HandlerMethodArgumentResolver}. */ @Override public boolean supportsParameter(MethodParameter parameter) { return getArgumentResolver(parameter) != null; } /** * Iterate over registered * {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers} * and invoke the one that supports it. * @throws IllegalArgumentException if no suitable argument resolver is found */ @Override public @Nullable Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter); if (resolver == null) { throw new IllegalArgumentException("Unsupported parameter type [" + parameter.getParameterType().getName() + "]. supportsParameter should be called first."); } return resolver.resolveArgument(parameter, message); } /** * Find a registered {@link HandlerMethodArgumentResolver} that supports * the given method parameter. */ private @Nullable HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) { HandlerMethodArgumentResolver result = this.argumentResolverCache.get(parameter); if (result == null) { for (HandlerMethodArgumentResolver resolver : this.argumentResolvers) { if (resolver.supportsParameter(parameter)) { result = resolver; this.argumentResolverCache.put(parameter, result); break; } } } return result; } }
HandlerMethodArgumentResolverComposite
java
grpc__grpc-java
okhttp/src/main/java/io/grpc/okhttp/OkHttpTlsUpgrader.java
{ "start": 1275, "end": 3581 }
class ____ { /* * List of ALPN/NPN protocols in order of preference. GRPC_EXP requires that * HTTP_2 be present and that GRPC_EXP should be preferenced over HTTP_2. */ @VisibleForTesting static final List<Protocol> TLS_PROTOCOLS = Collections.unmodifiableList(Arrays.asList(Protocol.HTTP_2)); /** * Upgrades given Socket to be an SSLSocket. * * @throws IOException if an IO error was encountered during the upgrade handshake. * @throws RuntimeException if the upgrade negotiation failed. */ public static SSLSocket upgrade(SSLSocketFactory sslSocketFactory, @Nonnull HostnameVerifier hostnameVerifier, Socket socket, String host, int port, ConnectionSpec spec) throws IOException { Preconditions.checkNotNull(sslSocketFactory, "sslSocketFactory"); Preconditions.checkNotNull(socket, "socket"); Preconditions.checkNotNull(spec, "spec"); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket( socket, host, port, true /* auto close */); spec.apply(sslSocket, false); String negotiatedProtocol = OkHttpProtocolNegotiator.get().negotiate( sslSocket, host, spec.supportsTlsExtensions() ? TLS_PROTOCOLS : null); Preconditions.checkState( TLS_PROTOCOLS.contains(Protocol.get(negotiatedProtocol)), "Only " + TLS_PROTOCOLS + " are supported, but negotiated protocol is %s", negotiatedProtocol); if (!hostnameVerifier.verify(canonicalizeHost(host), sslSocket.getSession())) { throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host); } return sslSocket; } /** * Converts a host from URI to X509 format. * * <p>IPv6 host addresses derived from URIs are enclosed in square brackets per RFC2732, but * omit these brackets in X509 certificate subjectAltName extensions per RFC5280. * * @see <a href="https://www.ietf.org/rfc/rfc2732.txt">RFC2732</a> * @see <a href="https://tools.ietf.org/html/rfc5280#section-4.2.1.6">RFC5280</a> * * @return {@code host} in a form consistent with X509 certificates */ @VisibleForTesting static String canonicalizeHost(String host) { if (host.startsWith("[") && host.endsWith("]")) { return host.substring(1, host.length() - 1); } return host; } }
OkHttpTlsUpgrader
java
apache__kafka
streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/VersionedKeyValueStoreIntegrationTest.java
{ "start": 34257, "end": 34559 }
class ____ implements Query<String> { } /** * Supplies a custom {@link VersionedKeyValueStore} implementation solely for the purpose * of testing IQv2 queries. A hard-coded "success" result is returned in response to * {@code TestQuery} queries. */ private static
TestQuery
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/test/Wait.java
{ "start": 4891, "end": 6102 }
class ____<T> { private Duration duration = Duration.ofSeconds(10); private Sleeper sleeper = new ThreadSleep(Duration.ofMillis(10)); private Function<T, String> messageFunction; private Supplier<T> supplier; private Predicate<T> check; private WaitCondition waitCondition; public WaitBuilder<T> during(Duration duration) { this.duration = duration; return this; } public WaitBuilder<T> message(String message) { this.messageFunction = o -> message; return this; } @SuppressWarnings("unchecked") public void waitOrTimeout() { Waiter waiter = new Waiter(); waiter.duration = duration; waiter.sleeper = sleeper; waiter.messageFunction = (Function<Object, String>) messageFunction; if (waitCondition != null) { waiter.waitOrTimeout(waitCondition, supplier); } else { waiter.waitOrTimeout(supplier, check); } } } /** * Utility to await until a {@link WaitCondition} yields {@code true}. */ private static
WaitBuilder
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/heap/HeapMetaInfoRestoreOperation.java
{ "start": 1865, "end": 6183 }
class ____<K> { private final StateSerializerProvider<K> keySerializerProvider; private final HeapPriorityQueueSetFactory priorityQueueSetFactory; @Nonnull private final KeyGroupRange keyGroupRange; @Nonnegative private final int numberOfKeyGroups; private final StateTableFactory<K> stateTableFactory; private final InternalKeyContext<K> keyContext; HeapMetaInfoRestoreOperation( StateSerializerProvider<K> keySerializerProvider, HeapPriorityQueueSetFactory priorityQueueSetFactory, @Nonnull KeyGroupRange keyGroupRange, int numberOfKeyGroups, StateTableFactory<K> stateTableFactory, InternalKeyContext<K> keyContext) { this.keySerializerProvider = keySerializerProvider; this.priorityQueueSetFactory = priorityQueueSetFactory; this.keyGroupRange = keyGroupRange; this.numberOfKeyGroups = numberOfKeyGroups; this.stateTableFactory = stateTableFactory; this.keyContext = keyContext; } Map<Integer, StateMetaInfoSnapshot> createOrCheckStateForMetaInfo( List<StateMetaInfoSnapshot> restoredMetaInfo, Map<String, StateTable<K, ?, ?>> registeredKVStates, Map<String, HeapPriorityQueueSnapshotRestoreWrapper<?>> registeredPQStates) { final Map<Integer, StateMetaInfoSnapshot> kvStatesById = new HashMap<>(); for (StateMetaInfoSnapshot metaInfoSnapshot : restoredMetaInfo) { final StateSnapshotRestore registeredState; switch (metaInfoSnapshot.getBackendStateType()) { case KEY_VALUE: registeredState = registeredKVStates.get(metaInfoSnapshot.getName()); if (registeredState == null) { RegisteredKeyValueStateBackendMetaInfo<?, ?> registeredKeyedBackendStateMetaInfo = new RegisteredKeyValueStateBackendMetaInfo<>( metaInfoSnapshot); registeredKVStates.put( metaInfoSnapshot.getName(), stateTableFactory.newStateTable( keyContext, registeredKeyedBackendStateMetaInfo, keySerializerProvider.currentSchemaSerializer())); } break; case PRIORITY_QUEUE: registeredState = registeredPQStates.get(metaInfoSnapshot.getName()); if (registeredState == null) { registeredPQStates.put( metaInfoSnapshot.getName(), createInternal( new RegisteredPriorityQueueStateBackendMetaInfo<>( metaInfoSnapshot))); } break; default: throw new IllegalStateException( "Unexpected state type: " + metaInfoSnapshot.getBackendStateType() + "."); } // always put metaInfo into kvStatesById, because kvStatesById is KeyGroupsStateHandle // related kvStatesById.put(kvStatesById.size(), metaInfoSnapshot); } return kvStatesById; } @SuppressWarnings({"unchecked", "rawtypes"}) private <T extends HeapPriorityQueueElement & PriorityComparable<? super T> & Keyed<?>> HeapPriorityQueueSnapshotRestoreWrapper<T> createInternal( RegisteredPriorityQueueStateBackendMetaInfo metaInfo) { final String stateName = metaInfo.getName(); final HeapPriorityQueueSet<T> priorityQueue = priorityQueueSetFactory.create(stateName, metaInfo.getElementSerializer()); return new HeapPriorityQueueSnapshotRestoreWrapper<>( priorityQueue, metaInfo, KeyExtractorFunction.forKeyedObjects(), keyGroupRange, numberOfKeyGroups); } }
HeapMetaInfoRestoreOperation
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/BigDecimalScaleAssert.java
{ "start": 655, "end": 1157 }
class ____<T> extends AbstractBigDecimalScaleAssert<BigDecimalAssert> { private AbstractBigDecimalAssert<BigDecimalAssert> bigDecimalAssert; public BigDecimalScaleAssert(AbstractBigDecimalAssert<BigDecimalAssert> bigDecimalAssert) { super(bigDecimalAssert.actual.scale(), BigDecimalScaleAssert.class); this.bigDecimalAssert = bigDecimalAssert; } @Override public AbstractBigDecimalAssert<BigDecimalAssert> returnToBigDecimal() { return bigDecimalAssert; } }
BigDecimalScaleAssert
java
apache__flink
flink-core/src/main/java/org/apache/flink/core/execution/JobStatusChangedListenerUtils.java
{ "start": 1342, "end": 3697 }
class ____ { /** * Create job status changed listeners from configuration for job. * * @param configuration The job configuration. * @return the job status changed listeners. */ public static List<JobStatusChangedListener> createJobStatusChangedListeners( ClassLoader userClassLoader, Configuration configuration, Executor ioExecutor) { List<String> jobStatusChangedListeners = configuration.get(JOB_STATUS_CHANGED_LISTENERS); if (jobStatusChangedListeners == null || jobStatusChangedListeners.isEmpty()) { return Collections.emptyList(); } return jobStatusChangedListeners.stream() .map( fac -> { try { return InstantiationUtil.instantiate( fac, JobStatusChangedListenerFactory.class, userClassLoader) .createListener( new JobStatusChangedListenerFactory.Context() { @Override public Configuration getConfiguration() { return configuration; } @Override public ClassLoader getUserClassLoader() { return userClassLoader; } @Override public Executor getIOExecutor() { return ioExecutor; } }); } catch (FlinkException e) { throw new RuntimeException(e); } }) .collect(Collectors.toList()); } }
JobStatusChangedListenerUtils
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestRpcBase.java
{ "start": 8326, "end": 9326 }
class ____ extends ConnectionId { private static final int PRIME = 16777619; private final int index; public MockConnectionId(InetSocketAddress address, Class<?> protocol, UserGroupInformation ticket, int rpcTimeout, RetryPolicy connectionRetryPolicy, Configuration conf, int index) { super(address, protocol, ticket, rpcTimeout, connectionRetryPolicy, conf); this.index = index; } @Override public int hashCode() { return new HashCodeBuilder() .append(PRIME * super.hashCode()) .append(this.index) .toHashCode(); } @Override public boolean equals(Object obj) { if (!super.equals(obj)) { return false; } if (obj instanceof MockConnectionId) { MockConnectionId other = (MockConnectionId)obj; return new EqualsBuilder() .append(this.index, other.index) .isEquals(); } return false; } } public static
MockConnectionId
java
apache__flink
flink-core-api/src/main/java/org/apache/flink/util/function/QuadFunction.java
{ "start": 1200, "end": 1565 }
interface ____<S, T, U, V, R> { /** * Applies this function to the given arguments. * * @param s the first function argument * @param t the second function argument * @param u the third function argument * @param v the fourth function argument * @return the function result */ R apply(S s, T t, U u, V v); }
QuadFunction
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnsafeReflectiveConstructionCastTest.java
{ "start": 3131, "end": 3461 }
class ____<T> {} ; private Fn<String> newInstanceOnGetDeclaredConstructorChained() throws Exception { return (Fn<String>) Class.forName("Fn").getDeclaredConstructor().newInstance(); } } """) .addOutputLines( "out/Test.java", """
Fn
java
apache__flink
flink-tests/src/test/java/org/apache/flink/runtime/operators/coordination/OperatorEventSendingCheckpointITCase.java
{ "start": 3191, "end": 12003 }
class ____ extends TestLogger { private static final int PARALLELISM = 1; private static MiniCluster flinkCluster; @BeforeClass public static void setupMiniClusterAndEnv() throws Exception { Configuration config = new Configuration(); // uncomment to run test with adaptive scheduler // config.set(JobManagerOptions.SCHEDULER, JobManagerOptions.SchedulerType.Adaptive); flinkCluster = new MiniClusterWithRpcIntercepting(PARALLELISM, config); flinkCluster.start(); TestStreamEnvironment.setAsContext(flinkCluster, PARALLELISM); } @AfterClass public static void clearEnvAndStopMiniCluster() throws Exception { TestStreamEnvironment.unsetAsContext(); if (flinkCluster != null) { flinkCluster.close(); flinkCluster = null; } } // ------------------------------------------------------------------------ // tests // ------------------------------------------------------------------------ /** * Every second assign split event is lost. Eventually, the enumerator must recognize that an * event was lost and trigger recovery to prevent data loss. Data loss would manifest in a * stalled test, because we could wait forever to collect the required number of events back. */ @Test public void testOperatorEventLostNoReaderFailure() throws Exception { final int[] eventsToLose = new int[] {2, 4, 6}; OpEventRpcInterceptor.currentHandler = new OperatorEventRpcHandler( (task, operator, event, originalRpcHandler) -> askTimeoutFuture(), eventsToLose); runTest(false); } /** * First and third assign split events are lost. In the middle of all events being processed * (which is after the second successful event delivery, the fourth event), there is * additionally a failure on the reader that triggers recovery. */ @Test public void testOperatorEventLostWithReaderFailure() throws Exception { final int[] eventsToLose = new int[] {1, 3}; OpEventRpcInterceptor.currentHandler = new OperatorEventRpcHandler( (task, operator, event, originalRpcHandler) -> askTimeoutFuture(), eventsToLose); runTest(true); } /** * This test the case that the enumerator must handle the case of presumably lost splits that * were actually delivered. * * <p>Some split assignment events happen normally, but for some their acknowledgement never * comes back. The enumerator must assume the assignments were unsuccessful, even though the * split assignment was received by the reader. */ @Test public void testOperatorEventAckLost() throws Exception { final int[] eventsWithLostAck = new int[] {2, 4}; OpEventRpcInterceptor.currentHandler = new OperatorEventRpcHandler( (task, operator, event, originalRpcHandler) -> { // forward call originalRpcHandler.apply(task, operator, event); // but return an ack future that times out to simulate lost response return askTimeoutFuture(); }, eventsWithLostAck); runTest(false); } /** * This tests the case where the status of an assignment remains unknown across checkpoints. * * <p>Some split assignment events happen normally, but for some their acknowledgement comes * very late, so that we expect multiple checkpoints would have normally happened in the * meantime. We trigger a failure (which happens after the second split) */ @Test public void testOperatorEventAckDelay() throws Exception { final int[] eventsWithLateAck = new int[] {2, 4}; OpEventRpcInterceptor.currentHandler = new OperatorEventRpcHandler( (task, operator, event, originalRpcHandler) -> { // forward call final CompletableFuture<Acknowledge> result = originalRpcHandler.apply(task, operator, event); // but return an ack future that completes late, after // multiple checkpoints should have happened final CompletableFuture<Acknowledge> late = lateFuture(); return result.thenCompose((v) -> late); }, eventsWithLateAck); runTest(false); } /** * Runs the test program, which uses a single reader (parallelism = 1) and has three splits of * data, to be assigned to the same reader. * * <p>If an intermittent failure should happen, it will happen after the second split was * assigned. */ private void runTest(boolean intermittentFailure) throws Exception { final int numElements = 100; final int failAt = intermittentFailure ? numElements / 2 : numElements * 2; final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); env.enableCheckpointing(50); // This test depends on checkpoints persisting progress from the source before the // artificial exception gets triggered. Otherwise, the job will run for a long time (or // forever) because the exception will be thrown before any checkpoint successfully // completes. // // Checkpoints are triggered once the checkpoint scheduler gets started + a random initial // delay. For DefaultScheduler, this mechanism is fine, because DS starts the checkpoint // coordinator, then requests the required slots and then deploys the tasks. These // operations take enough time to have a checkpoint triggered by the time the task starts // running. AdaptiveScheduler starts the CheckpointCoordinator right before deploying tasks // (when slots are available already), hence tasks will start running almost immediately, // and the checkpoint gets triggered too late (it won't be able to complete before the // artificial failure from this test) // Therefore, the TestingNumberSequenceSource waits for a checkpoint before emitting all // required messages. final DataStream<Long> numbers = env.fromSource( new NumberSequenceSourceWithWaitForCheckpoint(1L, numElements, 3), WatermarkStrategy.noWatermarks(), "numbers") .map( new MapFunction<Long, Long>() { private int num; @Override public Long map(Long value) throws Exception { if (++num > failAt) { throw new Exception("Artificial intermittent failure."); } return value; } }); final List<Long> sequence = numbers.executeAndCollect(numElements); // the recovery may change the order of splits, so the sequence might be out-of-order sequence.sort(Long::compareTo); final List<Long> expectedSequence = LongStream.rangeClosed(1L, numElements).boxed().collect(Collectors.toList()); assertEquals(expectedSequence, sequence); } private static CompletableFuture<Acknowledge> askTimeoutFuture() { final CompletableFuture<Acknowledge> future = new CompletableFuture<>(); final long timeout = 500; FutureUtils.orTimeout( future, timeout, TimeUnit.MILLISECONDS, String.format("Future timed out after %s ms.", timeout)); return future; } private static CompletableFuture<Acknowledge> lateFuture() { final CompletableFuture<Acknowledge> future = new CompletableFuture<>(); FutureUtils.completeDelayed(future, Acknowledge.get(), Duration.ofMillis(500)); return future; } // ------------------------------------------------------------------------ // Source Operator Event specific intercepting // ------------------------------------------------------------------------ private static
OperatorEventSendingCheckpointITCase
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/GloballyTerminalJobStatusListener.java
{ "start": 1147, "end": 1702 }
class ____ implements JobStatusListener { private final CompletableFuture<JobStatus> globallyTerminalJobStatusFuture = new CompletableFuture<>(); @Override public void jobStatusChanges(JobID jobId, JobStatus newJobStatus, long timestamp) { if (newJobStatus.isGloballyTerminalState()) { globallyTerminalJobStatusFuture.complete(newJobStatus); } } public CompletableFuture<JobStatus> getTerminationFuture() { return globallyTerminalJobStatusFuture; } }
GloballyTerminalJobStatusListener
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2400/Issue2428.java
{ "start": 545, "end": 1329 }
class ____ { private String myId; } public void test_for_issue() { Issue2428 demoBean = new Issue2428(); demoBean.setMyName("test name"); demoBean.setNestedBean(new NestedBean("test id")); String text = JSON.toJSONString(JSON.toJSON(demoBean), SerializerFeature.SortField); assertEquals("{\"nestedBean\":{\"myId\":\"test id\"},\"myName\":\"test name\"}", text); SerializeConfig serializeConfig = new SerializeConfig(); serializeConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase; text = JSON.toJSONString(JSON.toJSON(demoBean, serializeConfig), SerializerFeature.SortField); assertEquals("{\"my_name\":\"test name\",\"nested_bean\":{\"my_id\":\"test id\"}}", text); } }
NestedBean
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/operators/util/SlotSharingGroupUtilsTest.java
{ "start": 1189, "end": 2527 }
class ____ { @Test void testCovertToResourceSpec() { final ExternalResource gpu = new ExternalResource("gpu", 1); final ResourceSpec resourceSpec = ResourceSpec.newBuilder(1.0, 100) .setManagedMemoryMB(200) .setTaskOffHeapMemoryMB(300) .setExtendedResource(gpu) .build(); final SlotSharingGroup slotSharingGroup1 = SlotSharingGroup.newBuilder("ssg") .setCpuCores(resourceSpec.getCpuCores().getValue().doubleValue()) .setTaskHeapMemory(resourceSpec.getTaskHeapMemory()) .setTaskOffHeapMemory(resourceSpec.getTaskOffHeapMemory()) .setManagedMemory(resourceSpec.getManagedMemory()) .setExternalResource(gpu.getName(), gpu.getValue().doubleValue()) .build(); final SlotSharingGroup slotSharingGroup2 = SlotSharingGroup.newBuilder("ssg").build(); assertThat(SlotSharingGroupUtils.extractResourceSpec(slotSharingGroup1)) .isEqualTo(resourceSpec); assertThat(SlotSharingGroupUtils.extractResourceSpec(slotSharingGroup2)) .isEqualTo(ResourceSpec.UNKNOWN); } }
SlotSharingGroupUtilsTest
java
apache__camel
components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpTcpServerConsumerOptionalEndOfDataWithValidationTest.java
{ "start": 1160, "end": 3271 }
class ____ extends TcpServerConsumerEndOfDataAndValidationTestSupport { @Override boolean validatePayload() { return true; } @Override boolean requireEndOfData() { return false; } @Override @Test public void testInvalidMessage() { expectedInvalidCount = 1; assertDoesNotThrow(this::runInvalidMessage); } @Override @Test public void testNthInvalidMessage() { expectedInvalidCount = 1; assertDoesNotThrow(this::runNthInvalidMessage); } @Override @Test public void testMessageContainingEmbeddedStartOfBlock() { expectedInvalidCount = 1; assertDoesNotThrow(this::runMessageContainingEmbeddedStartOfBlock); } @Override @Test public void testNthMessageContainingEmbeddedStartOfBlock() { expectedInvalidCount = 1; assertDoesNotThrow(this::runNthMessageContainingEmbeddedStartOfBlock); } @Override @Test public void testMessageContainingEmbeddedEndOfBlock() { expectedInvalidCount = 1; setExpectedCounts(); NotifyBuilder done = new NotifyBuilder(context()).whenDone(1).create(); mllpClient.sendFramedData( Hl7TestMessageGenerator.generateMessage().replaceFirst("PID", "PID" + MllpProtocolConstants.END_OF_BLOCK)); assertTrue(done.matches(5, TimeUnit.SECONDS), "Exchange should have completed"); } @Override @Test public void testInvalidMessageContainingEmbeddedEndOfBlock() { expectedInvalidCount = 1; assertDoesNotThrow(this::runInvalidMessageContainingEmbeddedEndOfBlock); } @Override @Test public void testNthMessageContainingEmbeddedEndOfBlock() { expectedInvalidCount = 1; assertDoesNotThrow(this::runNthMessageContainingEmbeddedEndOfBlock); } @Override @Test public void testMessageWithoutEndOfDataByte() { expectedCompleteCount = 2; assertDoesNotThrow(this::runMessageWithoutEndOfDataByte); } }
MllpTcpServerConsumerOptionalEndOfDataWithValidationTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/MetadataFieldMapper.java
{ "start": 3014, "end": 3731 }
class ____ implements TypeParser { final Function<MappingParserContext, MetadataFieldMapper> mapperParser; public FixedTypeParser(Function<MappingParserContext, MetadataFieldMapper> mapperParser) { this.mapperParser = mapperParser; } @Override public Builder parse(String name, Map<String, Object> node, MappingParserContext parserContext) throws MapperParsingException { throw new MapperParsingException(name + " is not configurable"); } @Override public MetadataFieldMapper getDefault(MappingParserContext parserContext) { return mapperParser.apply(parserContext); } } public static
FixedTypeParser
java
apache__camel
core/camel-main/src/main/java/org/apache/camel/main/DefaultRoutesCollector.java
{ "start": 4005, "end": 11916 }
class ____, so we need to make // name as path so we can use ant patch matcher exclude = exclude.replace('.', '/'); // there may be multiple separated by comma String[] parts = exclude.split(","); for (String part : parts) { // must negate when excluding, and hence ! match = !matcher.match(part, name); log.trace("Java RoutesBuilder: {} exclude filter: {} -> {}", name, part, match); if (!match) { break; } } } // exclude take precedence over include if (match && ObjectHelper.isNotEmpty(excludePattern)) { // there may be multiple separated by comma String[] parts = excludePattern.split(","); for (String part : parts) { // must negate when excluding, and hence ! match = !matcher.match(part, name); log.trace("Java RoutesBuilder: {} exclude filter: {} -> {}", name, part, match); if (!match) { break; } } } if (match && ObjectHelper.isNotEmpty(includePattern)) { // there may be multiple separated by comma String[] parts = includePattern.split(","); for (String part : parts) { match = matcher.match(part, name); log.trace("Java RoutesBuilder: {} include filter: {} -> {}", name, part, match); if (match) { break; } } } log.debug("Java RoutesBuilder: {} accepted by include/exclude filter: {}", name, match); if (match) { routes.add(routesBuilder); } } } // the route may have source code available so attempt to load as resource for (RoutesBuilder route : routes) { if (route instanceof ResourceAware ra && ra.getResource() == null) { Resource r = ResourceHelper.resolveResource(camelContext, "source:" + route.getClass().getName()); if (r != null && r.exists()) { ra.setResource(r); } } } return routes; } @Override public Collection<RoutesBuilder> collectRoutesFromDirectory( CamelContext camelContext, String excludePattern, String includePattern) { final List<RoutesBuilder> answer = new ArrayList<>(); StopWatch watch = new StopWatch(); // include pattern may indicate a resource is optional, so we need to scan twice String pattern = includePattern; String optionalPattern = null; if (pattern != null && pattern.contains("?optional=true")) { StringJoiner sj1 = new StringJoiner(","); StringJoiner sj2 = new StringJoiner(","); for (String p : pattern.split(",")) { if (p.endsWith("?optional=true")) { sj2.add(p.substring(0, p.length() - 14)); } else { sj1.add(p); } } pattern = sj1.length() > 0 ? sj1.toString() : null; optionalPattern = sj2.length() > 0 ? sj2.toString() : null; } if (optionalPattern == null) { // only mandatory pattern doCollectRoutesFromDirectory(camelContext, answer, excludePattern, pattern, false); } else { // find optional first doCollectRoutesFromDirectory(camelContext, answer, excludePattern, optionalPattern, true); if (pattern != null) { // and then any mandatory doCollectRoutesFromDirectory(camelContext, answer, excludePattern, pattern, false); } } if (!answer.isEmpty()) { log.debug("Loaded {} ({} millis) additional RoutesBuilder from: {}", answer.size(), watch.taken(), includePattern); } else { log.debug("No additional RoutesBuilder discovered from: {}", includePattern); } return answer; } protected void doCollectRoutesFromDirectory( CamelContext camelContext, List<RoutesBuilder> builders, String excludePattern, String includePattern, boolean optional) { RoutesLoader loader = PluginHelper.getRoutesLoader(camelContext); Collection<Resource> accepted = findRouteResourcesFromDirectory(camelContext, excludePattern, includePattern); try { Collection<RoutesBuilder> found = loader.findRoutesBuilders(accepted, optional); if (!found.isEmpty()) { log.debug("Found {} route builder from locations: {}", builders.size(), found); builders.addAll(found); } } catch (Exception e) { if (isIgnoreLoadingError()) { log.warn("Ignore Loading error: {} due to: {}. This exception is ignored.", accepted, e.getMessage()); } else { throw RuntimeCamelException.wrapRuntimeException(e); } } } @Override public Collection<Resource> findRouteResourcesFromDirectory( CamelContext camelContext, String excludePattern, String includePattern) { final PackageScanResourceResolver resolver = PluginHelper.getPackageScanResourceResolver(camelContext); final String[] includes = includePattern != null ? includePattern.split(",") : null; final String[] excludes = excludePattern != null ? excludePattern.split(",") : null; if (includes == null || ObjectHelper.equal("false", includePattern)) { log.debug("Include pattern is empty/false, no routes will be discovered from resources"); return new ArrayList<>(); } Collection<Resource> accepted = new ArrayList<>(); for (String include : includes) { if (include.endsWith("?optional=true")) { include = include.substring(0, include.length() - 14); } log.debug("Finding additional routes from: {}", include); try { for (Resource resource : resolver.findResources(include)) { // filter unwanted resources if (!"false".equals(excludePattern) && AntPathMatcher.INSTANCE.anyMatch(excludes, resource.getLocation())) { continue; } accepted.add(resource); } } catch (Exception e) { throw RuntimeCamelException.wrapRuntimeException(e); } } return accepted; } /** * Strategy to allow collecting additional routes from registry. * * @param camelContext the context * @param excludePattern the exclusion pattern * @param includePattern the inclusion pattern */ @SuppressWarnings("unused") protected Collection<RoutesBuilder> collectAdditionalRoutesFromRegistry( CamelContext camelContext, String excludePattern, String includePattern) { return null; } /** * Strategy to discover a specific route builder type from the registry. This allows Spring Boot or other runtimes * to do custom lookup. */ protected <T> Collection<T> findByType(CamelContext camelContext, Class<T> type) { return camelContext.getRegistry().findByType(type); } }
names
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/transforms/TransformConfigUpdate.java
{ "start": 1336, "end": 12343 }
class ____ implements Writeable { public static final String NAME = "data_frame_transform_config_update"; public static final TransformConfigUpdate EMPTY = new TransformConfigUpdate(null, null, null, null, null, null, null, null); private static final ConstructingObjectParser<TransformConfigUpdate, String> PARSER = new ConstructingObjectParser<>( NAME, false, (args) -> { SourceConfig source = (SourceConfig) args[0]; DestConfig dest = (DestConfig) args[1]; TimeValue frequency = args[2] == null ? null : TimeValue.parseTimeValue((String) args[2], TransformField.FREQUENCY.getPreferredName()); SyncConfig syncConfig = (SyncConfig) args[3]; String description = (String) args[4]; SettingsConfig settings = (SettingsConfig) args[5]; @SuppressWarnings("unchecked") Map<String, Object> metadata = (Map<String, Object>) args[6]; RetentionPolicyConfig retentionPolicyConfig = (RetentionPolicyConfig) args[7]; return new TransformConfigUpdate(source, dest, frequency, syncConfig, description, settings, metadata, retentionPolicyConfig); } ); static { PARSER.declareObject(optionalConstructorArg(), (p, c) -> SourceConfig.fromXContent(p, false), TransformField.SOURCE); PARSER.declareObject(optionalConstructorArg(), (p, c) -> DestConfig.fromXContent(p, false), TransformField.DESTINATION); PARSER.declareString(optionalConstructorArg(), TransformField.FREQUENCY); PARSER.declareNamedObject(optionalConstructorArg(), (p, c, n) -> p.namedObject(SyncConfig.class, n, c), TransformField.SYNC); PARSER.declareString(optionalConstructorArg(), TransformField.DESCRIPTION); PARSER.declareObject(optionalConstructorArg(), (p, c) -> SettingsConfig.fromXContent(p, false), TransformField.SETTINGS); PARSER.declareObject(optionalConstructorArg(), (p, c) -> p.mapOrdered(), TransformField.METADATA); PARSER.declareObjectOrNull(optionalConstructorArg(), (p, c) -> { XContentParser.Token token = p.nextToken(); assert token == XContentParser.Token.FIELD_NAME; String currentName = p.currentName(); RetentionPolicyConfig namedObject = p.namedObject(RetentionPolicyConfig.class, currentName, c); token = p.nextToken(); assert token == XContentParser.Token.END_OBJECT; return namedObject; }, NullRetentionPolicyConfig.INSTANCE, TransformField.RETENTION_POLICY); } private final SourceConfig source; private final DestConfig dest; private final TimeValue frequency; private final SyncConfig syncConfig; private final String description; private final SettingsConfig settings; private final Map<String, Object> metadata; private final RetentionPolicyConfig retentionPolicyConfig; private Map<String, String> headers; public TransformConfigUpdate( final SourceConfig source, final DestConfig dest, final TimeValue frequency, final SyncConfig syncConfig, final String description, final SettingsConfig settings, final Map<String, Object> metadata, final RetentionPolicyConfig retentionPolicyConfig ) { this.source = source; this.dest = dest; this.frequency = frequency; this.syncConfig = syncConfig; this.description = description; if (this.description != null && this.description.length() > MAX_DESCRIPTION_LENGTH) { throw new IllegalArgumentException("[description] must be less than 1000 characters in length."); } this.settings = settings; this.metadata = metadata; this.retentionPolicyConfig = retentionPolicyConfig; } public TransformConfigUpdate(final StreamInput in) throws IOException { source = in.readOptionalWriteable(SourceConfig::new); dest = in.readOptionalWriteable(DestConfig::new); frequency = in.readOptionalTimeValue(); description = in.readOptionalString(); syncConfig = in.readOptionalNamedWriteable(SyncConfig.class); if (in.readBoolean()) { setHeaders(in.readMap(StreamInput::readString)); } settings = in.readOptionalWriteable(SettingsConfig::new); metadata = in.readGenericMap(); retentionPolicyConfig = in.readOptionalNamedWriteable(RetentionPolicyConfig.class); } public SourceConfig getSource() { return source; } public DestConfig getDestination() { return dest; } public TimeValue getFrequency() { return frequency; } public SyncConfig getSyncConfig() { return syncConfig; } @Nullable public String getDescription() { return description; } @Nullable public SettingsConfig getSettings() { return settings; } @Nullable public Map<String, Object> getMetadata() { return metadata; } @Nullable public RetentionPolicyConfig getRetentionPolicyConfig() { return retentionPolicyConfig; } public Map<String, String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } @Override public void writeTo(final StreamOutput out) throws IOException { out.writeOptionalWriteable(source); out.writeOptionalWriteable(dest); out.writeOptionalTimeValue(frequency); out.writeOptionalString(description); out.writeOptionalNamedWriteable(syncConfig); if (headers != null) { out.writeBoolean(true); out.writeMap(headers, StreamOutput::writeString); } else { out.writeBoolean(false); } out.writeOptionalWriteable(settings); out.writeGenericMap(metadata); out.writeOptionalNamedWriteable(retentionPolicyConfig); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } final TransformConfigUpdate that = (TransformConfigUpdate) other; return Objects.equals(this.source, that.source) && Objects.equals(this.dest, that.dest) && Objects.equals(this.frequency, that.frequency) && Objects.equals(this.syncConfig, that.syncConfig) && Objects.equals(this.description, that.description) && Objects.equals(this.settings, that.settings) && Objects.equals(this.metadata, that.metadata) && Objects.equals(this.retentionPolicyConfig, that.retentionPolicyConfig) && Objects.equals(this.headers, that.headers); } @Override public int hashCode() { return Objects.hash(source, dest, frequency, syncConfig, description, settings, metadata, retentionPolicyConfig, headers); } public static TransformConfigUpdate fromXContent(final XContentParser parser) { return PARSER.apply(parser, null); } public boolean isEmpty() { return this.equals(EMPTY); } boolean isNoop(TransformConfig config) { return isNullOrEqual(source, config.getSource()) && isNullOrEqual(dest, config.getDestination()) && isNullOrEqual(frequency, config.getFrequency()) && isNullOrEqual(syncConfig, config.getSyncConfig()) && isNullOrEqual(description, config.getDescription()) && isNullOrEqual(settings, config.getSettings()) && isNullOrEqual(metadata, config.getMetadata()) && isNullOrEqual(retentionPolicyConfig, config.getRetentionPolicyConfig()) && isNullOrEqual(headers, config.getHeaders()); } public boolean changesSettings(TransformConfig config) { return isNullOrEqual(settings, config.getSettings()) == false; } public boolean changesHeaders(TransformConfig config) { return isNullOrEqual(headers, config.getHeaders()) == false; } public boolean changesDestIndex(TransformConfig config) { var updatedIndex = dest == null ? null : dest.getIndex(); return isNullOrEqual(updatedIndex, config.getDestination().getIndex()) == false; } public boolean changesFrequency(TransformConfig config) { return isNullOrEqual(frequency, config.getFrequency()) == false; } private static boolean isNullOrEqual(Object lft, Object rgt) { return lft == null || lft.equals(rgt); } public TransformConfig apply(TransformConfig config) { if (isNoop(config)) { return config; } TransformConfig.Builder builder = new TransformConfig.Builder(config); if (source != null) { builder.setSource(source); } if (dest != null) { builder.setDest(dest); } if (frequency != null) { builder.setFrequency(frequency); } if (syncConfig != null) { String currentConfigName = config.getSyncConfig() == null ? "null" : config.getSyncConfig().getWriteableName(); if (syncConfig.getWriteableName().equals(currentConfigName) == false) { throw new ElasticsearchStatusException( TransformMessages.getMessage( TransformMessages.TRANSFORM_UPDATE_CANNOT_CHANGE_SYNC_METHOD, config.getId(), currentConfigName, syncConfig.getWriteableName() ), RestStatus.BAD_REQUEST ); } builder.setSyncConfig(syncConfig); } if (description != null) { builder.setDescription(description); } if (headers != null) { builder.setHeaders(headers); } if (settings != null) { // settings are partially updateable, that means we only overwrite changed settings but keep others SettingsConfig.Builder settingsBuilder = new SettingsConfig.Builder(config.getSettings()); settingsBuilder.update(settings); builder.setSettings(settingsBuilder.build()); } if (metadata != null) { // Unlike with settings, we fully replace the old metadata with the new metadata builder.setMetadata(metadata); } if (retentionPolicyConfig != null) { if (NullRetentionPolicyConfig.INSTANCE.equals(retentionPolicyConfig)) { builder.setRetentionPolicyConfig(null); } else { builder.setRetentionPolicyConfig(retentionPolicyConfig); } } builder.setVersion(TransformConfigVersion.CURRENT); return builder.build(); } }
TransformConfigUpdate
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/introspect/IntrospectorPairTest.java
{ "start": 3644, "end": 9707 }
class ____ /****************************************************** */ @Override public PropertyName findRootName(MapperConfig<?> config, AnnotatedClass ac) { return (PropertyName) values.get("findRootName"); } @Override public JsonIgnoreProperties.Value findPropertyIgnoralByName(MapperConfig<?> config, Annotated a) { return (JsonIgnoreProperties.Value) values.get("findPropertyIgnoralByName"); } @Override public Boolean isIgnorableType(MapperConfig<?> config, AnnotatedClass ac) { return (Boolean) values.get("isIgnorableType"); } @Override public Object findFilterId(MapperConfig<?> config, Annotated ann) { return (Object) values.get("findFilterId"); } @Override public Object findNamingStrategy(MapperConfig<?> config, AnnotatedClass ac) { return (Object) values.get("findNamingStrategy"); } @Override public String findClassDescription(MapperConfig<?> config, AnnotatedClass ac) { return (String) values.get("findClassDescription"); } /* /****************************************************** /* Property auto-detection /****************************************************** */ @Override public VisibilityChecker findAutoDetectVisibility(MapperConfig<?> config, AnnotatedClass ac, VisibilityChecker checker) { VisibilityChecker vc = (VisibilityChecker) values.get("findAutoDetectVisibility"); // not really good but: return (vc == null) ? checker : vc; } /* /****************************************************** /* Type handling /****************************************************** */ @SuppressWarnings("unchecked") @Override public List<NamedType> findSubtypes(MapperConfig<?> config, Annotated a) { return (List<NamedType>) values.get("findSubtypes"); } @Override public String findTypeName(MapperConfig<?> config, AnnotatedClass ac) { return (String) values.get("findTypeName"); } /* /****************************************************** /* General member (field, method/constructor) annotations /****************************************************** */ @Override public PropertyName findWrapperName(MapperConfig<?> config, Annotated ann) { return (PropertyName) values.get("findWrapperName"); } /* /****************************************************** /* Serialization introspection /****************************************************** */ @Override public Boolean hasAsKey(MapperConfig<?> config, Annotated a) { return (Boolean) values.get("hasAsKey"); } @Override public Boolean hasAsValue(MapperConfig<?> config, Annotated a) { return (Boolean) values.get("hasAsValue"); } @Override public Boolean hasAnyGetter(MapperConfig<?> config, Annotated ann) { return (Boolean) values.get("hasAnyGetter"); } /* /****************************************************** /* Deserialization introspection /****************************************************** */ @Override public Boolean hasAnySetter(MapperConfig<?> config, Annotated a) { return (Boolean) values.get("hasAnySetter"); } /* /****************************************************** /* Helper methods /****************************************************** */ private boolean _boolean(String key) { Object ob = values.get(key); return Boolean.TRUE.equals(ob); } } /* /********************************************************** /* Test methods, misc /********************************************************** */ private final AnnotationIntrospector NO_ANNOTATIONS = AnnotationIntrospector.nopInstance(); @Test public void testVersion() throws Exception { Version v = new Version(1, 2, 3, null, "com.fasterxml", "IntrospectorPairTest"); IntrospectorWithMap withVersion = new IntrospectorWithMap() .version(v); assertEquals(v, new AnnotationIntrospectorPair(withVersion, NO_ANNOTATIONS).version()); IntrospectorWithMap noVersion = new IntrospectorWithMap(); assertEquals(Version.unknownVersion(), new AnnotationIntrospectorPair(noVersion, withVersion).version()); } @Test public void testAccess() throws Exception { IntrospectorWithMap intr1 = new IntrospectorWithMap(); AnnotationIntrospectorPair pair = new AnnotationIntrospectorPair(intr1, NO_ANNOTATIONS); Collection<AnnotationIntrospector> intrs = pair.allIntrospectors(); assertEquals(2, intrs.size()); Iterator<AnnotationIntrospector> it = intrs.iterator(); assertSame(intr1, it.next()); assertSame(NO_ANNOTATIONS, it.next()); } @Test public void testAnnotationBundle() throws Exception { IntrospectorWithMap isBundle = new IntrospectorWithMap() .add("isAnnotationBundle", true); assertTrue(new AnnotationIntrospectorPair(NO_ANNOTATIONS, isBundle) .isAnnotationBundle(null)); assertTrue(new AnnotationIntrospectorPair(isBundle, NO_ANNOTATIONS) .isAnnotationBundle(null)); assertFalse(new AnnotationIntrospectorPair(NO_ANNOTATIONS, NO_ANNOTATIONS) .isAnnotationBundle(null)); } /* /********************************************************** /* Test methods, general
annotations
java
apache__logging-log4j2
log4j-1.2-api/src/main/java/org/apache/log4j/jmx/LoggerDynamicMBean.java
{ "start": 1832, "end": 4088 }
class ____ extends AbstractDynamicMBean implements NotificationListener { // This Logger instance is for logging. private static final Logger cat = Logger.getLogger(LoggerDynamicMBean.class); private final MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[1]; private final MBeanOperationInfo[] dOperations = new MBeanOperationInfo[1]; private final Vector dAttributes = new Vector(); private final String dClassName = this.getClass().getName(); private final String dDescription = "This MBean acts as a management facade for a org.apache.log4j.Logger instance."; // We wrap this Logger instance. private final Logger logger; public LoggerDynamicMBean(final Logger logger) { this.logger = logger; buildDynamicMBeanInfo(); } void addAppender(final String appenderClass, final String appenderName) { cat.debug("addAppender called with " + appenderClass + ", " + appenderName); final Appender appender = (Appender) OptionConverter.instantiateByClassName(appenderClass, org.apache.log4j.Appender.class, null); appender.setName(appenderName); logger.addAppender(appender); // appenderMBeanRegistration(); } void appenderMBeanRegistration() { final Enumeration enumeration = logger.getAllAppenders(); while (enumeration.hasMoreElements()) { final Appender appender = (Appender) enumeration.nextElement(); registerAppenderMBean(appender); } } private void buildDynamicMBeanInfo() { final Constructor[] constructors = this.getClass().getConstructors(); dConstructors[0] = new MBeanConstructorInfo( "HierarchyDynamicMBean(): Constructs a HierarchyDynamicMBean instance", constructors[0]); dAttributes.add( new MBeanAttributeInfo("name", "java.lang.String", "The name of this Logger.", true, false, false)); dAttributes.add(new MBeanAttributeInfo( "priority", "java.lang.String", "The priority of this logger.", true, true, false)); final MBeanParameterInfo[] params = new MBeanParameterInfo[2]; params[0] = new MBeanParameterInfo("
LoggerDynamicMBean
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/DecompressorStream.java
{ "start": 1174, "end": 7780 }
class ____ extends CompressionInputStream { /** * The maximum input buffer size. */ private static final int MAX_INPUT_BUFFER_SIZE = 512; /** * MAX_SKIP_BUFFER_SIZE is used to determine the maximum buffer size to * use when skipping. See {@link java.io.InputStream}. */ private static final int MAX_SKIP_BUFFER_SIZE = 2048; private byte[] skipBytes; private byte[] oneByte = new byte[1]; protected Decompressor decompressor = null; protected byte[] buffer; protected boolean eof = false; protected boolean closed = false; private int lastBytesSent = 0; @VisibleForTesting DecompressorStream(InputStream in, Decompressor decompressor, int bufferSize, int skipBufferSize) throws IOException { super(in); if (decompressor == null) { throw new NullPointerException(); } else if (bufferSize <= 0) { throw new IllegalArgumentException("Illegal bufferSize"); } this.decompressor = decompressor; buffer = new byte[bufferSize]; skipBytes = new byte[skipBufferSize]; } public DecompressorStream(InputStream in, Decompressor decompressor, int bufferSize) throws IOException { this(in, decompressor, bufferSize, MAX_SKIP_BUFFER_SIZE); } public DecompressorStream(InputStream in, Decompressor decompressor) throws IOException { this(in, decompressor, MAX_INPUT_BUFFER_SIZE); } /** * Allow derived classes to directly set the underlying stream. * * @param in Underlying input stream. * @throws IOException raised on errors performing I/O. */ protected DecompressorStream(InputStream in) throws IOException { super(in); } @Override public int read() throws IOException { checkStream(); return (read(oneByte, 0, oneByte.length) == -1) ? -1 : (oneByte[0] & 0xff); } @Override public int read(byte[] b, int off, int len) throws IOException { checkStream(); if ((off | len | (off + len) | (b.length - (off + len))) < 0) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } return decompress(b, off, len); } protected int decompress(byte[] b, int off, int len) throws IOException { int n; while ((n = decompressor.decompress(b, off, len)) == 0) { if (decompressor.needsDictionary()) { eof = true; return -1; } if (decompressor.finished()) { // First see if there was any leftover buffered input from previous // stream; if not, attempt to refill buffer. If refill -> EOF, we're // all done; else reset, fix up input buffer, and get ready for next // concatenated substream/"member". int nRemaining = decompressor.getRemaining(); if (nRemaining == 0) { int m = getCompressedData(); if (m == -1) { // apparently the previous end-of-stream was also end-of-file: // return success, as if we had never called getCompressedData() eof = true; return -1; } decompressor.reset(); decompressor.setInput(buffer, 0, m); lastBytesSent = m; } else { // looks like it's a concatenated stream: reset low-level zlib (or // other engine) and buffers, then "resend" remaining input data decompressor.reset(); int leftoverOffset = lastBytesSent - nRemaining; assert (leftoverOffset >= 0); // this recopies userBuf -> direct buffer if using native libraries: decompressor.setInput(buffer, leftoverOffset, nRemaining); // NOTE: this is the one place we do NOT want to save the number // of bytes sent (nRemaining here) into lastBytesSent: since we // are resending what we've already sent before, offset is nonzero // in general (only way it could be zero is if it already equals // nRemaining), which would then screw up the offset calculation // _next_ time around. IOW, getRemaining() is in terms of the // original, zero-offset bufferload, so lastBytesSent must be as // well. Cheesy ASCII art: // // <------------ m, lastBytesSent -----------> // +===============================================+ // buffer: |1111111111|22222222222222222|333333333333| | // +===============================================+ // #1: <-- off -->|<-------- nRemaining ---------> // #2: <----------- off ----------->|<-- nRem. --> // #3: (final substream: nRemaining == 0; eof = true) // // If lastBytesSent is anything other than m, as shown, then "off" // will be calculated incorrectly. } } else if (decompressor.needsInput()) { int m = getCompressedData(); if (m == -1) { throw new EOFException("Unexpected end of input stream"); } decompressor.setInput(buffer, 0, m); lastBytesSent = m; } } return n; } protected int getCompressedData() throws IOException { checkStream(); // note that the _caller_ is now required to call setInput() or throw return in.read(buffer, 0, buffer.length); } protected void checkStream() throws IOException { if (closed) { throw new IOException("Stream closed"); } } @Override public void resetState() throws IOException { decompressor.reset(); } @Override public long skip(long n) throws IOException { // Sanity checks if (n < 0) { throw new IllegalArgumentException("negative skip length"); } checkStream(); // Read 'n' bytes int skipped = 0; while (skipped < n) { int len = Math.min(((int)n - skipped), skipBytes.length); len = read(skipBytes, 0, len); if (len == -1) { eof = true; break; } skipped += len; } return skipped; } @Override public int available() throws IOException { checkStream(); return (eof) ? 0 : 1; } @Override public void close() throws IOException { if (!closed) { try { super.close(); } finally { closed = true; } } } @Override public boolean markSupported() { return false; } @Override public synchronized void mark(int readlimit) { } @Override public synchronized void reset() throws IOException { throw new IOException("mark/reset not supported"); } }
DecompressorStream
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/data/BooleanArrayBlock.java
{ "start": 792, "end": 872 }
class ____ generated. Edit {@code X-ArrayBlock.java.st} instead. */ public final
is
java
apache__rocketmq
client/src/test/java/org/apache/rocketmq/client/impl/mqclient/MQClientAPITest.java
{ "start": 1414, "end": 5137 }
class ____ { private NameserverAccessConfig nameserverAccessConfig; private final ClientRemotingProcessor clientRemotingProcessor = new DoNothingClientRemotingProcessor(null); private final RPCHook rpcHook = null; private ScheduledExecutorService scheduledExecutorService; private MQClientAPIFactory mqClientAPIFactory; @Before public void setUp() { scheduledExecutorService = ThreadUtils.newSingleThreadScheduledExecutor("TestScheduledExecutorService", true); } @After public void tearDown() { scheduledExecutorService.shutdownNow(); } @Test public void testInitWithNamesrvAddr() { nameserverAccessConfig = new NameserverAccessConfig("127.0.0.1:9876", "", ""); mqClientAPIFactory = new MQClientAPIFactory( nameserverAccessConfig, "TestPrefix", 2, clientRemotingProcessor, rpcHook, scheduledExecutorService ); assertEquals("127.0.0.1:9876", System.getProperty("rocketmq.namesrv.addr")); } @Test public void testInitWithNamesrvDomain() { nameserverAccessConfig = new NameserverAccessConfig("", "test-domain", ""); mqClientAPIFactory = new MQClientAPIFactory( nameserverAccessConfig, "TestPrefix", 2, clientRemotingProcessor, rpcHook, scheduledExecutorService ); assertEquals("test-domain", System.getProperty("rocketmq.namesrv.domain")); } @Test public void testInitThrowsExceptionWhenBothEmpty() { nameserverAccessConfig = new NameserverAccessConfig("", "", ""); RuntimeException exception = assertThrows(RuntimeException.class, () -> new MQClientAPIFactory( nameserverAccessConfig, "TestPrefix", 2, clientRemotingProcessor, rpcHook, scheduledExecutorService )); assertEquals("The configuration item NamesrvAddr is not configured", exception.getMessage()); } @Test public void testStartCreatesClients() throws Exception { nameserverAccessConfig = new NameserverAccessConfig("127.0.0.1:9876", "", ""); mqClientAPIFactory = new MQClientAPIFactory( nameserverAccessConfig, "TestPrefix", 2, clientRemotingProcessor, rpcHook, scheduledExecutorService ); System.setProperty(MixAll.NAMESRV_ADDR_PROPERTY, "127.0.0.1:123"); mqClientAPIFactory.start(); // Assert MQClientAPIExt client = mqClientAPIFactory.getClient(); List<String> nameServerAddressList = client.getNameServerAddressList(); assertEquals(1, nameServerAddressList.size()); assertEquals("127.0.0.1:9876", nameServerAddressList.get(0)); } @Test public void testOnNameServerAddressChangeUpdatesAllClients() throws Exception { nameserverAccessConfig = new NameserverAccessConfig("127.0.0.1:9876", "", ""); mqClientAPIFactory = new MQClientAPIFactory( nameserverAccessConfig, "TestPrefix", 2, clientRemotingProcessor, rpcHook, scheduledExecutorService ); mqClientAPIFactory.start(); // Act mqClientAPIFactory.onNameServerAddressChange("new-address0;new-address1"); MQClientAPIExt client = mqClientAPIFactory.getClient(); List<String> nameServerAddressList = client.getNameServerAddressList(); assertEquals(2, nameServerAddressList.size()); assertTrue(nameServerAddressList.contains("new-address0")); } }
MQClientAPITest
java
alibaba__nacos
sys/src/main/java/com/alibaba/nacos/sys/file/FileChangeEvent.java
{ "start": 1565, "end": 2397 }
class ____ { private String paths; private Object context; private FileChangeEventBuilder() { } public FileChangeEventBuilder paths(String paths) { this.paths = paths; return this; } public FileChangeEventBuilder context(Object context) { this.context = context; return this; } /** * build FileChangeEvent. * * @return {@link FileChangeEvent} */ public FileChangeEvent build() { FileChangeEvent fileChangeEvent = new FileChangeEvent(); fileChangeEvent.setPaths(paths); fileChangeEvent.setContext(context); return fileChangeEvent; } } }
FileChangeEventBuilder
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/StateTrackingMockExecutionGraph.java
{ "start": 4593, "end": 5788 }
class ____ implements ExecutionGraph { private static final Logger LOG = LoggerFactory.getLogger(StateTrackingMockExecutionGraph.class); private JobStatus state = JobStatus.INITIALIZING; private JobType jobType = JobType.STREAMING; private final CompletableFuture<JobStatus> terminationFuture = new CompletableFuture<>(); private final JobID jobId = new JobID(); private static final ArchivedExecutionConfig archivedExecutionConfig = new ExecutionConfig().archive(); private final Map<ExecutionAttemptID, TestingAccessExecution> executions = new HashMap<>(); private void transitionToState(JobStatus targetState) { if (!state.isTerminalState()) { this.state = targetState; } else { LOG.warn( "Trying to transition into state {} while being in terminal state {}", targetState, state); } } // ---- methods to control the mock void completeTerminationFuture(JobStatus finalStatus) { terminationFuture.complete(finalStatus); transitionToState(finalStatus); } // ----
StateTrackingMockExecutionGraph
java
quarkusio__quarkus
independent-projects/qute/core/src/main/java/io/quarkus/qute/ValueResolvers.java
{ "start": 602, "end": 811 }
class ____ { static final String THIS = "this"; static final String ELVIS = "?:"; static final String COLON = ":"; public static final String OR = "or"; private static abstract
ValueResolvers
java
elastic__elasticsearch
x-pack/plugin/enrich/src/test/java/org/elasticsearch/xpack/monitoring/collector/enrich/EnrichCoordinatorDocTests.java
{ "start": 1448, "end": 7230 }
class ____ extends BaseMonitoringDocTestCase<EnrichCoordinatorDoc> { static final DateFormatter DATE_TIME_FORMATTER = DateFormatter.forPattern("strict_date_time").withZone(ZoneOffset.UTC); private CoordinatorStats stats; @Override public void setUp() throws Exception { super.setUp(); stats = new CoordinatorStats( randomAlphaOfLength(4), randomIntBetween(0, Integer.MAX_VALUE), randomIntBetween(0, Integer.MAX_VALUE), randomNonNegativeLong(), randomNonNegativeLong() ); } @Override protected EnrichCoordinatorDoc createMonitoringDoc( String cluster, long timestamp, long interval, MonitoringDoc.Node node, MonitoredSystem system, String type, String id ) { return new EnrichCoordinatorDoc(cluster, timestamp, interval, node, stats); } @Override protected void assertMonitoringDoc(EnrichCoordinatorDoc document) { assertThat(document.getSystem(), is(MonitoredSystem.ES)); assertThat(document.getType(), is(EnrichCoordinatorDoc.TYPE)); assertThat(document.getId(), nullValue()); assertThat(document.getCoordinatorStats(), equalTo(stats)); } @Override public void testToXContent() throws IOException { final long timestamp = System.currentTimeMillis(); final long intervalMillis = System.currentTimeMillis(); final long nodeTimestamp = System.currentTimeMillis(); final MonitoringDoc.Node node = new MonitoringDoc.Node("_uuid", "_host", "_addr", "_ip", "_name", nodeTimestamp); final EnrichCoordinatorDoc document = new EnrichCoordinatorDoc("_cluster", timestamp, intervalMillis, node, stats); final BytesReference xContent = XContentHelper.toXContent(document, XContentType.JSON, false); assertThat( xContent.utf8ToString(), equalTo( XContentHelper.stripWhitespace( Strings.format( """ { "cluster_uuid": "_cluster", "timestamp": "%s", "interval_ms": %s, "type": "enrich_coordinator_stats", "source_node": { "uuid": "_uuid", "host": "_host", "transport_address": "_addr", "ip": "_ip", "name": "_name", "timestamp": "%s" }, "enrich_coordinator_stats": { "node_id": "%s", "queue_size": %s, "remote_requests_current": %s, "remote_requests_total": %s, "executed_searches_total": %s } }""", DATE_TIME_FORMATTER.formatMillis(timestamp), intervalMillis, DATE_TIME_FORMATTER.formatMillis(nodeTimestamp), stats.nodeId(), stats.queueSize(), stats.remoteRequestsCurrent(), stats.remoteRequestsTotal(), stats.executedSearchesTotal() ) ) ) ); } public void testEnrichCoordinatorStatsFieldsMapped() throws IOException { XContentBuilder builder = jsonBuilder(); builder.startObject(); builder.value(stats); builder.endObject(); Map<String, Object> serializedStatus = XContentHelper.convertToMap(XContentType.JSON.xContent(), Strings.toString(builder), false); byte[] loadedTemplate = MonitoringTemplateRegistry.getTemplateConfigForMonitoredSystem(MonitoredSystem.ES).loadBytes(); Map<String, Object> template = XContentHelper.convertToMap( XContentType.JSON.xContent(), loadedTemplate, 0, loadedTemplate.length, false ); Map<?, ?> followStatsMapping = (Map<?, ?>) XContentMapValues.extractValue( "mappings._doc.properties.enrich_coordinator_stats.properties", template ); assertThat(serializedStatus.size(), equalTo(followStatsMapping.size())); for (Map.Entry<String, Object> entry : serializedStatus.entrySet()) { String fieldName = entry.getKey(); Map<?, ?> fieldMapping = (Map<?, ?>) followStatsMapping.get(fieldName); assertThat("no field mapping for field [" + fieldName + "]", fieldMapping, notNullValue()); Object fieldValue = entry.getValue(); String fieldType = (String) fieldMapping.get("type"); if (fieldValue instanceof Long || fieldValue instanceof Integer) { assertThat("expected long field type for field [" + fieldName + "]", fieldType, anyOf(equalTo("long"), equalTo("integer"))); } else if (fieldValue instanceof String) { assertThat( "expected keyword field type for field [" + fieldName + "]", fieldType, anyOf(equalTo("keyword"), equalTo("text")) ); } else { // Manual test specific object fields and if not just fail: fail("unexpected field value type [" + fieldValue.getClass() + "] for field [" + fieldName + "]"); } } } }
EnrichCoordinatorDocTests
java
apache__thrift
lib/java/src/test/java/org/apache/thrift/TestMultiplexedProcessor.java
{ "start": 2062, "end": 3084 }
class ____ implements TProcessor { @Override public void process(TProtocol in, TProtocol out) throws TException { TMessage msg = in.readMessageBegin(); if (!"func".equals(msg.name) || msg.type != TMessageType.CALL || msg.seqid != 42) { throw new TException("incorrect parameters"); } out.writeMessageBegin(new TMessage("func", TMessageType.REPLY, 42)); } } @Test public void testExistingService() throws TException { when(iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.CALL, 42)); mp.registerProcessor("service", new StubProcessor()); mp.process(iprot, oprot); verify(oprot).writeMessageBegin(any(TMessage.class)); } @Test public void testDefaultService() throws TException { when(iprot.readMessageBegin()).thenReturn(new TMessage("func", TMessageType.CALL, 42)); mp.registerDefault(new StubProcessor()); mp.process(iprot, oprot); verify(oprot).writeMessageBegin(any(TMessage.class)); } }
StubProcessor
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/HttpSecurityProcessor.java
{ "start": 52813, "end": 53287 }
class ____ implements BooleanSupplier { private final boolean alwaysPropagateSecurityIdentity; AlwaysPropagateSecurityIdentity(VertxHttpBuildTimeConfig buildTimeConfig) { this.alwaysPropagateSecurityIdentity = buildTimeConfig.auth().propagateSecurityIdentity(); } @Override public boolean getAsBoolean() { return alwaysPropagateSecurityIdentity; } } static final
AlwaysPropagateSecurityIdentity
java
apache__camel
core/camel-management/src/test/java/org/apache/camel/management/ManagedMBeansLevelRoutesOnlyTest.java
{ "start": 1136, "end": 1571 }
class ____ extends ManagedMBeansLevelTestSupport { public ManagedMBeansLevelRoutesOnlyTest() { super(ManagementMBeansLevel.RoutesOnly); } @Override void assertResults(Set<ObjectName> contexts, Set<ObjectName> routes, Set<ObjectName> processors) { assertEquals(1, contexts.size()); assertEquals(1, routes.size()); assertEquals(0, processors.size()); } }
ManagedMBeansLevelRoutesOnlyTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/security/token/block/BlockTokenSelector.java
{ "start": 1221, "end": 1734 }
class ____ implements TokenSelector<BlockTokenIdentifier> { @Override @SuppressWarnings("unchecked") public Token<BlockTokenIdentifier> selectToken(Text service, Collection<Token<? extends TokenIdentifier>> tokens) { if (service == null) { return null; } for (Token<? extends TokenIdentifier> token : tokens) { if (BlockTokenIdentifier.KIND_NAME.equals(token.getKind())) { return (Token<BlockTokenIdentifier>) token; } } return null; } }
BlockTokenSelector
java
spring-projects__spring-boot
module/spring-boot-data-redis/src/main/java/org/springframework/boot/data/redis/autoconfigure/DataRedisProperties.java
{ "start": 7080, "end": 7849 }
class ____ { /** * List of "host:port" pairs to bootstrap from. This represents an "initial" list * of cluster nodes and is required to have at least one entry. */ private @Nullable List<String> nodes; /** * Maximum number of redirects to follow when executing commands across the * cluster. */ private @Nullable Integer maxRedirects; public @Nullable List<String> getNodes() { return this.nodes; } public void setNodes(@Nullable List<String> nodes) { this.nodes = nodes; } public @Nullable Integer getMaxRedirects() { return this.maxRedirects; } public void setMaxRedirects(@Nullable Integer maxRedirects) { this.maxRedirects = maxRedirects; } } /** * Master Replica properties. */ public static
Cluster
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/DynamicRouterExchangePropertiesTest.java
{ "start": 1153, "end": 4217 }
class ____ extends ContextTestSupport { private static final List<String> bodies = new ArrayList<>(); @Test public void testDynamicRouter() throws Exception { getMockEndpoint("mock:a").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:a").expectedPropertyReceived("invoked", 1); getMockEndpoint("mock:b").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:b").expectedPropertyReceived("invoked", 2); getMockEndpoint("mock:c").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:c").expectedPropertyReceived("invoked", 2); getMockEndpoint("mock:foo").expectedBodiesReceived("Bye World"); getMockEndpoint("mock:foo").expectedPropertyReceived("invoked", 3); getMockEndpoint("mock:result").expectedBodiesReceived("Bye World"); getMockEndpoint("mock:result").expectedPropertyReceived("invoked", 4); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); assertEquals(5, bodies.size()); assertEquals("Hello World", bodies.get(0)); assertEquals("Hello World", bodies.get(1)); assertEquals("Hello World", bodies.get(2)); assertEquals("Bye World", bodies.get(3)); assertEquals("Bye World", bodies.get(4)); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") // use a bean as the dynamic router .dynamicRouter(method(DynamicRouterExchangePropertiesTest.class, "slip")); from("direct:foo").transform(constant("Bye World")).to("mock:foo"); } }; } // START SNIPPET: e2 /** * Use this method to compute dynamic where we should route next. * * @param body the message body * @param properties the exchange properties where we can store state between invocations * @return endpoints to go, or <tt>null</tt> to indicate the end */ public String slip(String body, @ExchangeProperties Map<String, Object> properties) { bodies.add(body); // get the state from the exchange properties and keep track how many // times // we have been invoked int invoked = 0; Object current = properties.get("invoked"); if (current != null) { invoked = Integer.valueOf(current.toString()); } invoked++; // and store the state back on the properties properties.put("invoked", invoked); if (invoked == 1) { return "mock:a"; } else if (invoked == 2) { return "mock:b,mock:c"; } else if (invoked == 3) { return "direct:foo"; } else if (invoked == 4) { return "mock:result"; } // no more so return null return null; } // END SNIPPET: e2 }
DynamicRouterExchangePropertiesTest
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/kstream/SlidingWindowsTest.java
{ "start": 1191, "end": 4240 }
class ____ { private static final long ANY_SIZE = 123L; private static final long ANY_GRACE = 1024L; @Test public void shouldSetTimeDifference() { assertEquals(ANY_SIZE, SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(ANY_SIZE), ofMillis(ANY_GRACE)).timeDifferenceMs()); assertEquals(ANY_SIZE, SlidingWindows.ofTimeDifferenceWithNoGrace(ofMillis(ANY_SIZE)).timeDifferenceMs()); } @Test public void timeDifferenceMustNotBeNegative() { assertThrows(IllegalArgumentException.class, () -> SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(-1), ofMillis(5))); } @Test public void shouldSetGracePeriod() { assertEquals(ANY_SIZE, SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(10), ofMillis(ANY_SIZE)).gracePeriodMs()); } @Test public void gracePeriodMustNotBeNegative() { assertThrows(IllegalArgumentException.class, () -> SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(10), ofMillis(-1))); } @Test public void equalsAndHashcodeShouldBeValidForPositiveCases() { final long grace = 1L + (long) (Math.random() * (20L - 1L)); final long timeDifference = 1L + (long) (Math.random() * (20L - 1L)); verifyEquality( SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(timeDifference), ofMillis(grace)), SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(timeDifference), ofMillis(grace)) ); verifyEquality( SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(timeDifference), ofMillis(grace)), SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(timeDifference), ofMillis(grace)) ); verifyEquality( SlidingWindows.ofTimeDifferenceWithNoGrace(ofMillis(timeDifference)), SlidingWindows.ofTimeDifferenceWithNoGrace(ofMillis(timeDifference)) ); } @Test public void equalsAndHashcodeShouldNotBeEqualForDifferentTimeDifference() { final long grace = 1L + (long) (Math.random() * (10L - 1L)); final long timeDifferenceOne = 1L + (long) (Math.random() * (10L - 1L)); final long timeDifferenceTwo = 21L + (long) (Math.random() * (41L - 21L)); verifyInEquality( SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(timeDifferenceOne), ofMillis(grace)), SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(timeDifferenceTwo), ofMillis(grace)) ); } @Test public void equalsAndHashcodeShouldNotBeEqualForDifferentGracePeriod() { final long timeDifference = 1L + (long) (Math.random() * (10L - 1L)); final long graceOne = 1L + (long) (Math.random() * (10L - 1L)); final long graceTwo = 21L + (long) (Math.random() * (41L - 21L)); verifyInEquality( SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(timeDifference), ofMillis(graceOne)), SlidingWindows.ofTimeDifferenceAndGrace(ofMillis(timeDifference), ofMillis(graceTwo)) ); } }
SlidingWindowsTest