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
junit-team__junit5
junit-platform-launcher/src/main/java/org/junit/platform/launcher/core/ExecutionListenerAdapter.java
{ "start": 971, "end": 2686 }
class ____ implements EngineExecutionListener { private final TestPlan testPlan; private final TestExecutionListener testExecutionListener; ExecutionListenerAdapter(TestPlan testPlan, TestExecutionListener testExecutionListener) { this.testPlan = testPlan; this.testExecutionListener = testExecutionListener; } @Override public void dynamicTestRegistered(TestDescriptor testDescriptor) { TestIdentifier testIdentifier = TestIdentifier.from(testDescriptor); this.testPlan.addInternal(testIdentifier); this.testExecutionListener.dynamicTestRegistered(testIdentifier); } @Override public void executionStarted(TestDescriptor testDescriptor) { this.testExecutionListener.executionStarted(getTestIdentifier(testDescriptor)); } @Override public void executionSkipped(TestDescriptor testDescriptor, String reason) { this.testExecutionListener.executionSkipped(getTestIdentifier(testDescriptor), reason); } @Override public void executionFinished(TestDescriptor testDescriptor, TestExecutionResult testExecutionResult) { this.testExecutionListener.executionFinished(getTestIdentifier(testDescriptor), testExecutionResult); } @Override public void reportingEntryPublished(TestDescriptor testDescriptor, ReportEntry entry) { this.testExecutionListener.reportingEntryPublished(getTestIdentifier(testDescriptor), entry); } @Override public void fileEntryPublished(TestDescriptor testDescriptor, FileEntry file) { this.testExecutionListener.fileEntryPublished(getTestIdentifier(testDescriptor), file); } private TestIdentifier getTestIdentifier(TestDescriptor testDescriptor) { return this.testPlan.getTestIdentifier(testDescriptor.getUniqueId()); } }
ExecutionListenerAdapter
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RTimeSeries.java
{ "start": 950, "end": 14019 }
interface ____<V, L> extends RExpirable, Iterable<V>, RTimeSeriesAsync<V, L>, RDestroyable { /** * Adds element to this time-series collection * by specified <code>timestamp</code>. * * @param timestamp object timestamp * @param object object itself */ void add(long timestamp, V object); /** * Adds element with <code>label</code> to this time-series collection * by specified <code>timestamp</code>. * * @param timestamp object timestamp * @param object object itself * @param label object label */ void add(long timestamp, V object, L label); /** * Adds all elements contained in the specified map to this time-series collection. * Map contains of timestamp mapped by object. * * @param objects - map of elements to add */ void addAll(Map<Long, V> objects); /** * Adds all entries collection to this time-series collection. * * @param entries collection of time series entries */ void addAll(Collection<TimeSeriesEntry<V, L>> entries); /** * Use {@link #add(long, Object, Duration)} instead * * @param timestamp - object timestamp * @param object - object itself * @param timeToLive - time to live interval * @param timeUnit - unit of time to live interval */ @Deprecated void add(long timestamp, V object, long timeToLive, TimeUnit timeUnit); /** * Adds element to this time-series collection * by specified <code>timestamp</code>. * * @param timestamp object timestamp * @param object object itself * @param timeToLive time to live interval */ void add(long timestamp, V object, Duration timeToLive); /** * Adds element with <code>label</code> to this time-series collection * by specified <code>timestamp</code>. * * @param timestamp object timestamp * @param object object itself * @param label object label * @param timeToLive time to live interval */ void add(long timestamp, V object, L label, Duration timeToLive); /** * Use {@link #addAll(Map, Duration)} instead * * @param objects - map of elements to add * @param timeToLive - time to live interval * @param timeUnit - unit of time to live interval */ @Deprecated void addAll(Map<Long, V> objects, long timeToLive, TimeUnit timeUnit); /** * Adds all elements contained in the specified map to this time-series collection. * Map contains of timestamp mapped by object. * * @param objects map of elements to add * @param timeToLive time to live interval */ void addAll(Map<Long, V> objects, Duration timeToLive); /** * Adds all time series entries collection to this time-series collection. * Specified time to live interval applied to all entries defined in collection. * * @param entries collection of time series entries * @param timeToLive time to live interval */ void addAll(Collection<TimeSeriesEntry<V, L>> entries, Duration timeToLive); /** * Returns size of this set. * * @return size */ int size(); /** * Returns object by specified <code>timestamp</code> or <code>null</code> if it doesn't exist. * * @param timestamp - object timestamp * @return object */ V get(long timestamp); /** * Returns time series entry by specified <code>timestamp</code> or <code>null</code> if it doesn't exist. * * @param timestamp object timestamp * @return time series entry */ TimeSeriesEntry<V, L> getEntry(long timestamp); /** * Removes object by specified <code>timestamp</code>. * * @param timestamp - object timestamp * @return <code>true</code> if an element was removed as a result of this call */ boolean remove(long timestamp); /** * Removes and returns object by specified <code>timestamp</code>. * * @param timestamp - object timestamp * @return object or <code>null</code> if it doesn't exist */ V getAndRemove(long timestamp); /** * Removes and returns entry by specified <code>timestamp</code>. * * @param timestamp - object timestamp * @return entry or <code>null</code> if it doesn't exist */ TimeSeriesEntry<V, L> getAndRemoveEntry(long timestamp); /** * Removes and returns the head elements * * @param count - elements amount * @return collection of head elements */ Collection<V> pollFirst(int count); /** * Removes and returns head entries * * @param count - entries amount * @return collection of head entries */ Collection<TimeSeriesEntry<V, L>> pollFirstEntries(int count); /** * Removes and returns the tail elements or {@code null} if this time-series collection is empty. * * @param count - elements amount * @return the tail element or {@code null} if this time-series collection is empty */ Collection<V> pollLast(int count); /** * Removes and returns tail entries * * @param count - entries amount * @return collection of tail entries */ Collection<TimeSeriesEntry<V, L>> pollLastEntries(int count); /** * Removes and returns the head element or {@code null} if this time-series collection is empty. * * @return the head element, * or {@code null} if this time-series collection is empty */ V pollFirst(); /** * Removes and returns head entry or {@code null} if this time-series collection is empty. * * @return the head entry, * or {@code null} if this time-series collection is empty */ TimeSeriesEntry<V, L> pollFirstEntry(); /** * Removes and returns the tail element or {@code null} if this time-series collection is empty. * * @return the tail element or {@code null} if this time-series collection is empty */ V pollLast(); /** * Removes and returns the tail entry or {@code null} if this time-series collection is empty. * * @return the tail entry or {@code null} if this time-series collection is empty */ TimeSeriesEntry<V, L> pollLastEntry(); /** * Returns the tail element or {@code null} if this time-series collection is empty. * * @return the tail element or {@code null} if this time-series collection is empty */ V last(); /** * Returns the tail entry or {@code null} if this time-series collection is empty. * * @return the tail entry or {@code null} if this time-series collection is empty */ TimeSeriesEntry<V, L> lastEntry(); /** * Returns the head element or {@code null} if this time-series collection is empty. * * @return the head element or {@code null} if this time-series collection is empty */ V first(); /** * Returns the head entry or {@code null} if this time-series collection is empty. * * @return the head entry or {@code null} if this time-series collection is empty */ TimeSeriesEntry<V, L> firstEntry(); /** * Returns timestamp of the head timestamp or {@code null} if this time-series collection is empty. * * @return timestamp or {@code null} if this time-series collection is empty */ Long firstTimestamp(); /** * Returns timestamp of the tail element or {@code null} if this time-series collection is empty. * * @return timestamp or {@code null} if this time-series collection is empty */ Long lastTimestamp(); /** * Returns the tail elements of this time-series collection. * * @param count - elements amount * @return the tail elements */ Collection<V> last(int count); /** * Returns the tail entries of this time-series collection. * * @param count - entries amount * @return the tail entries */ Collection<TimeSeriesEntry<V, L>> lastEntries(int count); /** * Returns the head elements of this time-series collection. * * @param count - elements amount * @return the head elements */ Collection<V> first(int count); /** * Returns the head entries of this time-series collection. * * @param count - entries amount * @return the head entries */ Collection<TimeSeriesEntry<V, L>> firstEntries(int count); /** * Removes values within timestamp range. Including boundary values. * * @param startTimestamp - start timestamp * @param endTimestamp - end timestamp * @return number of removed elements */ int removeRange(long startTimestamp, long endTimestamp); /** * Returns ordered elements of this time-series collection within timestamp range. Including boundary values. * * @param startTimestamp - start timestamp * @param endTimestamp - end timestamp * @return elements collection */ Collection<V> range(long startTimestamp, long endTimestamp); /** * Returns ordered elements of this time-series collection within timestamp range. Including boundary values. * * @param startTimestamp start timestamp * @param endTimestamp end timestamp * @param limit result size limit * @return elements collection */ Collection<V> range(long startTimestamp, long endTimestamp, int limit); /** * Returns elements of this time-series collection in reverse order within timestamp range. Including boundary values. * * @param startTimestamp - start timestamp * @param endTimestamp - end timestamp * @return elements collection */ Collection<V> rangeReversed(long startTimestamp, long endTimestamp); /** * Returns elements of this time-series collection in reverse order within timestamp range. Including boundary values. * * @param startTimestamp start timestamp * @param endTimestamp end timestamp * @param limit result size limit * @return elements collection */ Collection<V> rangeReversed(long startTimestamp, long endTimestamp, int limit); /** * Returns ordered entries of this time-series collection within timestamp range. Including boundary values. * * @param startTimestamp - start timestamp * @param endTimestamp - end timestamp * @return elements collection */ Collection<TimeSeriesEntry<V, L>> entryRange(long startTimestamp, long endTimestamp); /** * Returns ordered entries of this time-series collection within timestamp range. Including boundary values. * * @param startTimestamp start timestamp * @param endTimestamp end timestamp * @param limit result size limit * @return elements collection */ Collection<TimeSeriesEntry<V, L>> entryRange(long startTimestamp, long endTimestamp, int limit); /** * Returns entries of this time-series collection in reverse order within timestamp range. Including boundary values. * * @param startTimestamp - start timestamp * @param endTimestamp - end timestamp * @return elements collection */ Collection<TimeSeriesEntry<V, L>> entryRangeReversed(long startTimestamp, long endTimestamp); /** * Returns entries of this time-series collection in reverse order within timestamp range. Including boundary values. * * @param startTimestamp start timestamp * @param endTimestamp end timestamp * @param limit result size limit * @return elements collection */ Collection<TimeSeriesEntry<V, L>> entryRangeReversed(long startTimestamp, long endTimestamp, int limit); /** * Returns stream of elements in this time-series collection. * Elements are loaded in batch. Batch size is 10. * * @return stream of elements */ Stream<V> stream(); /** * Returns stream of elements in this time-series collection. * Elements are loaded in batch. Batch size is defined by <code>count</code> param. * * @param count - size of elements batch * @return stream of elements */ Stream<V> stream(int count); /** * Returns an iterator over elements in this time-series collection. * Elements are loaded in batch. Batch size is defined by <code>count</code> param. * * @param count - size of elements batch * @return iterator */ Iterator<V> iterator(int count); /** * Adds object event listener * * @see org.redisson.api.listener.TrackingListener * @see org.redisson.api.listener.ScoredSortedSetAddListener * @see org.redisson.api.listener.ScoredSortedSetRemoveListener * @see org.redisson.api.ExpiredObjectListener * @see org.redisson.api.DeletedObjectListener * * @param listener - object event listener * @return listener id */ @Override int addListener(ObjectListener listener); }
RTimeSeries
java
micronaut-projects__micronaut-core
http-client-tck/src/main/java/io/micronaut/http/client/tck/tests/RedirectTest.java
{ "start": 2426, "end": 9330 }
class ____ { private static final String SPEC_NAME = "RedirectTest"; private static final String BODY = "It works"; private static final BodyAssertion<String, String> EXPECTED_BODY = BodyAssertion.builder().body(BODY).equals(); private static final String REDIRECT = "redirect"; @ParameterizedTest(name = "blocking={0}") @ValueSource(booleans = {true, false}) void absoluteRedirection(boolean blocking) throws IOException { asserts(SPEC_NAME, Map.of(BLOCKING_CLIENT_PROPERTY, blocking), HttpRequest.GET("/redirect/redirect"), (server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body(EXPECTED_BODY) .build()) ); } @Test void clientRedirection() throws IOException { try (ServerUnderTest server = ServerUnderTestProviderUtils.getServerUnderTestProvider().getServer(SPEC_NAME)) { RedirectClient client = server.getApplicationContext().getBean(RedirectClient.class); assertEquals(BODY, client.redirect()); } } @Test void clientRelativeUriDirect() throws IOException { try (ServerUnderTest server = ServerUnderTestProviderUtils.getServerUnderTestProvider().getServer(SPEC_NAME); HttpClient client = server.getApplicationContext().createBean(HttpClient.class, relativeLoadBalancer(server, "/redirect"))) { var exchange = Flux.from(client.exchange(HttpRequest.GET("direct"), String.class)).blockFirst(); assertEquals(HttpStatus.OK, exchange.getStatus()); assertEquals(BODY, exchange.body()); } } @Test void blockingClientRelativeUriDirect() throws IOException { try (ServerUnderTest server = ServerUnderTestProviderUtils.getServerUnderTestProvider().getServer(SPEC_NAME); HttpClient client = server.getApplicationContext().createBean(HttpClient.class, relativeLoadBalancer(server, "/redirect"))) { var exchange = client.toBlocking().exchange(HttpRequest.GET("direct"), String.class); assertEquals(HttpStatus.OK, exchange.getStatus()); assertEquals(BODY, exchange.body()); } } @Test void clientRelativeUriNoSlash() throws IOException { try (ServerUnderTest server = ServerUnderTestProviderUtils.getServerUnderTestProvider().getServer(SPEC_NAME); HttpClient client = server.getApplicationContext().createBean(HttpClient.class, relativeLoadBalancer(server, REDIRECT))) { var exchange = Flux.from(client.exchange(HttpRequest.GET("direct"), String.class)).blockFirst(); assertEquals(HttpStatus.OK, exchange.getStatus()); assertEquals(BODY, exchange.body()); } } @Test void blockingClientRelativeUriNoSlash() throws IOException { try (ServerUnderTest server = ServerUnderTestProviderUtils.getServerUnderTestProvider().getServer(SPEC_NAME); HttpClient client = server.getApplicationContext().createBean(HttpClient.class, relativeLoadBalancer(server, REDIRECT))) { var exchange = client.toBlocking().exchange(HttpRequest.GET("direct"), String.class); assertEquals(HttpStatus.OK, exchange.getStatus()); assertEquals(BODY, exchange.body()); } } @Test @SuppressWarnings("java:S3655") void clientRelativeUriRedirectAbsolute() throws IOException { try (ServerUnderTest server = ServerUnderTestProviderUtils.getServerUnderTestProvider().getServer(SPEC_NAME); HttpClient client = server.getApplicationContext().createBean(HttpClient.class, server.getURL().get() + "/redirect")) { var response = Flux.from(client.exchange(HttpRequest.GET(REDIRECT), String.class)).blockFirst(); assertEquals(HttpStatus.OK, response.getStatus()); assertEquals(BODY, response.body()); } } @Test @SuppressWarnings("java:S3655") void blockingClientRelativeUriRedirectAbsolute() throws IOException { try (ServerUnderTest server = ServerUnderTestProviderUtils.getServerUnderTestProvider().getServer(SPEC_NAME); HttpClient client = server.getApplicationContext().createBean(HttpClient.class, server.getURL().get() + "/redirect")) { var response = client.toBlocking().exchange(HttpRequest.GET(REDIRECT), String.class); assertEquals(HttpStatus.OK, response.getStatus()); assertEquals(BODY, response.body()); } } @ParameterizedTest(name = "blocking={0}") @ValueSource(booleans = {true, false}) @SuppressWarnings("java:S3655") void hostHeaderIsCorrectForRedirect(boolean blocking) throws IOException { try (ServerUnderTest otherServer = ServerUnderTestProviderUtils.getServerUnderTestProvider().getServer(SPEC_NAME, Collections.singletonMap("redirect.server", "true"))) { int otherPort = otherServer.getPort().get(); asserts(SPEC_NAME, Map.of(BLOCKING_CLIENT_PROPERTY, blocking), HttpRequest.GET("/redirect/redirect-host").header(REDIRECT, "http://localhost:" + otherPort + "/redirect/host-header"), (server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body(BodyAssertion.builder().body("localhost:" + otherPort).equals()) .build()) ); } } @Test @Disabled("not supported, see -- io.micronaut.http.client.ClientRedirectSpec#test - client: full uri, redirect: relative") void relativeRedirection() throws IOException { asserts(SPEC_NAME, HttpRequest.GET("/redirect/redirect-relative"), (server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body(EXPECTED_BODY) .build()) ); } @SuppressWarnings("java:S3655") private LoadBalancer relativeLoadBalancer(ServerUnderTest server, String path) { return new LoadBalancer() { @Override public Publisher<ServiceInstance> select(@Nullable Object discriminator) { URL url = server.getURL().get(); return Publishers.just(ServiceInstance.of(url.getHost(), url)); } @Override public Optional<String> getContextPath() { return Optional.of(path); } }; } @Requires(property = "spec.name", value = SPEC_NAME) @Controller("/redirect") @SuppressWarnings("checkstyle:MissingJavadocType") static
RedirectTest
java
micronaut-projects__micronaut-core
json-core/src/main/java/io/micronaut/json/tree/JsonScalar.java
{ "start": 721, "end": 832 }
class ____ scalar values (null, number, string, boolean). * * @author Jonas Konrad * @since 3.1 */ abstract
for
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AbstractStateIterator.java
{ "start": 1627, "end": 1819 }
class ____ maintain more variables in need. Any subclass should * implement two methods, {@link #hasNextLoading()} and {@link #nextPayloadForContinuousLoading()}. * The philosophy behind this
to
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/stream/NestedCollectionFetchStreamTest.java
{ "start": 1362, "end": 3168 }
class ____ { @BeforeAll public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityB b = new EntityB(); b.getC().addAll( Stream.generate( EntityC::new ).limit( 3 ).collect( Collectors.toSet() ) ); session.persist( b ); session.persist( new EntityA( b ) ); } ); } @AfterAll public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "delete from EntityA" ).executeUpdate(); session.createMutationQuery( "delete from EntityC" ).executeUpdate(); session.createMutationQuery( "delete from EntityB" ).executeUpdate(); } ); } @Test public void testImplicitNestedCollection(SessionFactoryScope scope) { scope.inTransaction( session -> { try (final Stream<EntityA> stream = session.createQuery( "select a from EntityA a left join fetch a.b b left join fetch b.c c", EntityA.class ).getResultStream()) { final List<EntityA> list = stream.collect( Collectors.toList() ); assertThat( list ).hasSize( 1 ); assertThat( list.get( 0 ).getB() ).isNotNull(); assertThat( list.get( 0 ).getB().getC() ).hasSize( 3 ); } } ); } @Test public void testExplicitNestedCollection(SessionFactoryScope scope) { scope.inTransaction( session -> { try (final Stream<Tuple> stream = session.createQuery( "select a, b from EntityA a left join fetch a.b b left join fetch b.c c", Tuple.class ).getResultStream()) { final List<Tuple> list = stream.collect( Collectors.toList() ); assertThat( list ).hasSize( 1 ); assertThat( list.get( 0 ).get( 1, EntityB.class ) ).isNotNull(); assertThat( list.get( 0 ).get( 1, EntityB.class ).getC() ).hasSize( 3 ); } } ); } @MappedSuperclass public static abstract
NestedCollectionFetchStreamTest
java
grpc__grpc-java
xds/src/generated/thirdparty/grpc/io/envoyproxy/envoy/service/load_stats/v3/LoadReportingServiceGrpc.java
{ "start": 5328, "end": 7603 }
interface ____ { /** * <pre> * Advanced API to allow for multi-dimensional load balancing by remote * server. For receiving LB assignments, the steps are: * 1, The management server is configured with per cluster/zone/load metric * capacity configuration. The capacity configuration definition is * outside of the scope of this document. * 2. Envoy issues a standard {Stream,Fetch}Endpoints request for the clusters * to balance. * Independently, Envoy will initiate a StreamLoadStats bidi stream with a * management server: * 1. Once a connection establishes, the management server publishes a * LoadStatsResponse for all clusters it is interested in learning load * stats about. * 2. For each cluster, Envoy load balances incoming traffic to upstream hosts * based on per-zone weights and/or per-instance weights (if specified) * based on intra-zone LbPolicy. This information comes from the above * {Stream,Fetch}Endpoints. * 3. When upstream hosts reply, they optionally add header &lt;define header * name&gt; with ASCII representation of EndpointLoadMetricStats. * 4. Envoy aggregates load reports over the period of time given to it in * LoadStatsResponse.load_reporting_interval. This includes aggregation * stats Envoy maintains by itself (total_requests, rpc_errors etc.) as * well as load metrics from upstream hosts. * 5. When the timer of load_reporting_interval expires, Envoy sends new * LoadStatsRequest filled with load reports for each cluster. * 6. The management server uses the load reports from all reported Envoys * from around the world, computes global assignment and prepares traffic * assignment destined for each zone Envoys are located in. Goto 2. * </pre> */ default io.grpc.stub.StreamObserver<io.envoyproxy.envoy.service.load_stats.v3.LoadStatsRequest> streamLoadStats( io.grpc.stub.StreamObserver<io.envoyproxy.envoy.service.load_stats.v3.LoadStatsResponse> responseObserver) { return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getStreamLoadStatsMethod(), responseObserver); } } /** * Base
AsyncService
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/availability/ApplicationAvailability.java
{ "start": 1262, "end": 2899 }
interface ____ { /** * Return the {@link LivenessState} of the application. * @return the liveness state */ default LivenessState getLivenessState() { return getState(LivenessState.class, LivenessState.BROKEN); } /** * Return the {@link ReadinessState} of the application. * @return the readiness state */ default ReadinessState getReadinessState() { return getState(ReadinessState.class, ReadinessState.REFUSING_TRAFFIC); } /** * Return {@link AvailabilityState} information for the application. * @param <S> the state type * @param stateType the state type * @param defaultState the default state to return if no event of the given type has * been published yet (must not be {@code null}). * @return the readiness state * @see #getState(Class) */ <S extends AvailabilityState> S getState(Class<S> stateType, S defaultState); /** * Return {@link AvailabilityState} information for the application. * @param <S> the state type * @param stateType the state type * @return the readiness state or {@code null} if no event of the given type has been * published yet * @see #getState(Class, AvailabilityState) */ <S extends AvailabilityState> @Nullable S getState(Class<S> stateType); /** * Return the last {@link AvailabilityChangeEvent} received for a given state type. * @param <S> the state type * @param stateType the state type * @return the readiness state or {@code null} if no event of the given type has been * published yet */ <S extends AvailabilityState> @Nullable AvailabilityChangeEvent<S> getLastChangeEvent(Class<S> stateType); }
ApplicationAvailability
java
apache__camel
components/camel-github/src/main/java/org/apache/camel/component/github/GitHubComponent.java
{ "start": 1149, "end": 2249 }
class ____ extends HealthCheckComponent { @Metadata(label = "security", secret = true) private String oauthToken; @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { GitHubEndpoint endpoint = new GitHubEndpoint(uri, this); endpoint.setOauthToken(oauthToken); setProperties(endpoint, parameters); String[] parts = remaining.split("/"); if (parts.length >= 1) { String s = parts[0]; GitHubType type = getCamelContext().getTypeConverter().convertTo(GitHubType.class, s); endpoint.setType(type); if (parts.length > 1) { s = parts[1]; endpoint.setBranchName(s); } } return endpoint; } public String getOauthToken() { return oauthToken; } /** * GitHub OAuth token. Must be configured on either component or endpoint. */ public void setOauthToken(String oauthToken) { this.oauthToken = oauthToken; } }
GitHubComponent
java
google__auto
value/src/main/java/com/google/auto/value/processor/AutoBuilderProcessor.java
{ "start": 4830, "end": 5419 }
interface ____ { // ... // MyAnnot build(); // } // // public static MyAnnotBuilder myAnnotBuilder() { // return new AutoBuilder_Annotations_MyAnnotBuilder(); // } // } // // Then we will detect that the ofClass type is an annotation. Since annotations can have neither // constructors nor static methods, we know this isn't a regular @AutoBuilder. We want to // generate an implementation of the MyAnnot annotation, and we know we can do that if we have a // suitable @AutoAnnotation method. So we generate: // //
MyAnnotBuilder
java
quarkusio__quarkus
extensions/azure-functions/runtime/src/main/java/io/quarkus/azure/functions/runtime/QuarkusAzureFunctionsMiddleware.java
{ "start": 350, "end": 978 }
class ____ implements Middleware { @Override public void invoke(MiddlewareContext middlewareContext, MiddlewareChain middlewareChain) throws Exception { ManagedContext requestContext = Arc.container().requestContext(); boolean alreadyActive = requestContext.isActive(); if (!alreadyActive) { requestContext.activate(); } try { middlewareChain.doNext(middlewareContext); } finally { if (!alreadyActive && requestContext.isActive()) { requestContext.terminate(); } } } }
QuarkusAzureFunctionsMiddleware
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
{ "start": 261193, "end": 261316 }
class ____ { private final String param1; public Obj(String param1){ this.param1 = param1; } } public static
Obj
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/ITestAzureBlobFileSystemMainOperation.java
{ "start": 1196, "end": 2924 }
class ____ extends FSMainOperationsBaseTest { private static final String TEST_ROOT_DIR = "/tmp/TestAzureBlobFileSystemMainOperations"; private final ABFSContractTestBinding binding; public ITestAzureBlobFileSystemMainOperation () throws Exception { super(TEST_ROOT_DIR); // Note: There are shared resources in this test suite (eg: "test/new/newfile") // To make sure this test suite can be ran in parallel, different containers // will be used for each test. binding = new ABFSContractTestBinding(false); } @BeforeEach @Override public void setUp() throws Exception { binding.setup(); fSys = binding.getFileSystem(); } @AfterEach @Override public void tearDown() throws Exception { // Note: Because "tearDown()" is called during the testing, // here we should not call binding.tearDown() to destroy the container. // Instead we should remove the test containers manually with // AbfsTestUtils. super.tearDown(); } @Override protected FileSystem createFileSystem() throws Exception { return fSys; } @Override @Disabled("Permission check for getFileInfo doesn't match the HdfsPermissionsGuide") public void testListStatusThrowsExceptionForUnreadableDir() { // Permission Checks: // https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/HdfsPermissionsGuide.html } @Override @Disabled("Permission check for getFileInfo doesn't match the HdfsPermissionsGuide") public void testGlobStatusThrowsExceptionForUnreadableDir() { // Permission Checks: // https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/HdfsPermissionsGuide.html } }
ITestAzureBlobFileSystemMainOperation
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/mutationquery/MutationQueriesCollectionTableTest.java
{ "start": 834, "end": 1218 }
class ____ { @Test public void testDelete(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createQuery( "delete from Table1 where name = :name" ) .setParameter( "name", "test" ) .executeUpdate(); } ); } @Entity(name = "Base1") @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public abstract static
MutationQueriesCollectionTableTest
java
elastic__elasticsearch
x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/TrainedModelIT.java
{ "start": 1685, "end": 19514 }
class ____ extends ESRestTestCase { private static final String BASIC_AUTH_VALUE = UsernamePasswordToken.basicAuthHeaderValue( "x_pack_rest_user", SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING ); @Override protected Settings restClientSettings() { return Settings.builder().put(super.restClientSettings()).put(ThreadContext.PREFIX + ".Authorization", BASIC_AUTH_VALUE).build(); } @Override protected boolean preserveTemplatesUponCompletion() { return true; } public void testGetTrainedModels() throws IOException { String modelId = "a_test_regression_model"; String modelId2 = "a_test_regression_model-2"; putRegressionModel(modelId); putRegressionModel(modelId2); Response getModel = client().performRequest(new Request("GET", MachineLearning.BASE_PATH + "trained_models/" + modelId)); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); String response = EntityUtils.toString(getModel.getEntity()); assertThat(response, containsString("\"model_id\":\"a_test_regression_model\"")); assertThat(response, containsString("\"count\":1")); getModel = client().performRequest(new Request("GET", MachineLearning.BASE_PATH + "trained_models/a_test_regression*")); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); response = EntityUtils.toString(getModel.getEntity()); assertThat(response, containsString("\"model_id\":\"a_test_regression_model\"")); assertThat(response, containsString("\"model_id\":\"a_test_regression_model-2\"")); assertThat(response, not(containsString("\"definition\""))); assertThat(response, containsString("\"count\":2")); getModel = client().performRequest( new Request("GET", MachineLearning.BASE_PATH + "trained_models/a_test_regression_model?human=true&include=definition") ); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); response = EntityUtils.toString(getModel.getEntity()); assertThat(response, containsString("\"model_id\":\"a_test_regression_model\"")); assertThat(response, containsString("\"model_size_bytes\"")); assertThat(response, containsString("\"model_size\"")); assertThat(response, containsString("\"model_type\":\"tree_ensemble\"")); assertThat(response, containsString("\"definition\"")); assertThat(response, not(containsString("\"compressed_definition\""))); assertThat(response, containsString("\"count\":1")); getModel = client().performRequest( new Request( "GET", MachineLearning.BASE_PATH + "trained_models/a_test_regression_model?decompress_definition=false&include=definition" ) ); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); response = EntityUtils.toString(getModel.getEntity()); assertThat(response, containsString("\"model_id\":\"a_test_regression_model\"")); assertThat(response, containsString("\"model_size_bytes\"")); assertThat(response, containsString("\"compressed_definition\"")); assertThat(response, not(containsString("\"definition\""))); assertThat(response, containsString("\"count\":1")); ResponseException responseException = expectThrows( ResponseException.class, () -> client().performRequest( new Request("GET", MachineLearning.BASE_PATH + "trained_models/a_test_regression*?human=true&include=definition") ) ); assertThat( EntityUtils.toString(responseException.getResponse().getEntity()), containsString(Messages.INFERENCE_TOO_MANY_DEFINITIONS_REQUESTED) ); getModel = client().performRequest( new Request("GET", MachineLearning.BASE_PATH + "trained_models/a_test_regression_model,a_test_regression_model-2") ); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); response = EntityUtils.toString(getModel.getEntity()); assertThat(response, containsString("\"model_id\":\"a_test_regression_model\"")); assertThat(response, containsString("\"model_id\":\"a_test_regression_model-2\"")); assertThat(response, containsString("\"count\":2")); getModel = client().performRequest( new Request("GET", MachineLearning.BASE_PATH + "trained_models/classification*?allow_no_match=true") ); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); response = EntityUtils.toString(getModel.getEntity()); assertThat(response, containsString("\"count\":0")); ResponseException ex = expectThrows( ResponseException.class, () -> client().performRequest( new Request("GET", MachineLearning.BASE_PATH + "trained_models/classification*?allow_no_match=false") ) ); assertThat(ex.getResponse().getStatusLine().getStatusCode(), equalTo(404)); getModel = client().performRequest(new Request("GET", MachineLearning.BASE_PATH + "trained_models?from=0&size=1")); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); response = EntityUtils.toString(getModel.getEntity()); assertThat(response, containsString("\"count\":3")); assertThat(response, containsString("\"model_id\":\"a_test_regression_model\"")); assertThat(response, not(containsString("\"model_id\":\"a_test_regression_model-2\""))); getModel = client().performRequest(new Request("GET", MachineLearning.BASE_PATH + "trained_models?from=1&size=1")); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); response = EntityUtils.toString(getModel.getEntity()); assertThat(response, containsString("\"count\":3")); assertThat(response, not(containsString("\"model_id\":\"a_test_regression_model\""))); assertThat(response, containsString("\"model_id\":\"a_test_regression_model-2\"")); } public void testDeleteTrainedModels() throws IOException { String modelId = "test_delete_regression_model"; putRegressionModel(modelId); Response delModel = client().performRequest(new Request("DELETE", MachineLearning.BASE_PATH + "trained_models/" + modelId)); String response = EntityUtils.toString(delModel.getEntity()); assertThat(response, containsString("\"acknowledged\":true")); ResponseException responseException = expectThrows( ResponseException.class, () -> client().performRequest(new Request("DELETE", MachineLearning.BASE_PATH + "trained_models/" + modelId)) ); assertThat(responseException.getResponse().getStatusLine().getStatusCode(), equalTo(404)); responseException = expectThrows( ResponseException.class, () -> client().performRequest( new Request("GET", InferenceIndexConstants.LATEST_INDEX_NAME + "/_doc/" + TrainedModelDefinitionDoc.docId(modelId, 0)) ) ); assertThat(responseException.getResponse().getStatusLine().getStatusCode(), equalTo(404)); responseException = expectThrows( ResponseException.class, () -> client().performRequest(new Request("GET", InferenceIndexConstants.LATEST_INDEX_NAME + "/_doc/" + modelId)) ); assertThat(responseException.getResponse().getStatusLine().getStatusCode(), equalTo(404)); } public void testGetPrePackagedModels() throws IOException { Response getModel = client().performRequest( new Request("GET", MachineLearning.BASE_PATH + "trained_models/lang_ident_model_1?human=true&include=definition") ); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); String response = EntityUtils.toString(getModel.getEntity()); assertThat(response, containsString("lang_ident_model_1")); assertThat(response, containsString("\"definition\"")); } @SuppressWarnings("unchecked") public void testExportImportModel() throws IOException { String modelId = "regression_model_to_export"; putRegressionModel(modelId); Response getModel = client().performRequest(new Request("GET", MachineLearning.BASE_PATH + "trained_models/" + modelId)); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); String response = EntityUtils.toString(getModel.getEntity()); assertThat(response, containsString("\"model_id\":\"regression_model_to_export\"")); assertThat(response, containsString("\"count\":1")); getModel = client().performRequest( new Request( "GET", MachineLearning.BASE_PATH + "trained_models/" + modelId + "?include=definition&decompress_definition=false&exclude_generated=true" ) ); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); Map<String, Object> exportedModel = entityAsMap(getModel); Map<String, Object> modelDefinition = ((List<Map<String, Object>>) exportedModel.get("trained_model_configs")).get(0); modelDefinition.remove("model_id"); String importedModelId = "regression_model_to_import"; try (XContentBuilder builder = XContentFactory.jsonBuilder()) { builder.map(modelDefinition); Request model = new Request("PUT", "_ml/trained_models/" + importedModelId); model.setJsonEntity(XContentHelper.convertToJson(BytesReference.bytes(builder), false, XContentType.JSON)); assertThat(client().performRequest(model).getStatusLine().getStatusCode(), equalTo(200)); } getModel = client().performRequest(new Request("GET", MachineLearning.BASE_PATH + "trained_models/regression*")); assertThat(getModel.getStatusLine().getStatusCode(), equalTo(200)); response = EntityUtils.toString(getModel.getEntity()); assertThat(response, containsString("\"model_id\":\"regression_model_to_export\"")); assertThat(response, containsString("\"model_id\":\"regression_model_to_import\"")); assertThat(response, containsString("\"count\":2")); } private void putRegressionModel(String modelId) throws IOException { String modelConfig = """ { "definition": { "trained_model": { "ensemble": { "feature_names": ["field.foo", "field.bar", "animal_cat", "animal_dog"], "trained_models": [{ "tree": { "feature_names": ["field.foo", "field.bar", "animal_cat", "animal_dog"], "tree_structure": [{ "threshold": 0.5, "split_feature": 0, "node_index": 0, "left_child": 1, "right_child": 2 }, { "node_index": 1, "leaf_value": [0.3] }, { "threshold": 0.0, "split_feature": 3, "node_index": 2, "left_child": 3, "right_child": 4 }, { "node_index": 3, "leaf_value": [0.1] }, { "node_index": 4, "leaf_value": [0.2] }] } }, { "tree": { "feature_names": ["field.foo", "field.bar", "animal_cat", "animal_dog"], "tree_structure": [{ "threshold": 1.0, "split_feature": 2, "node_index": 0, "left_child": 1, "right_child": 2 }, { "node_index": 1, "leaf_value": [1.5] }, { "node_index": 2, "leaf_value": [0.9] }] } }, { "tree": { "feature_names": ["field.foo", "field.bar", "animal_cat", "animal_dog"], "tree_structure": [{ "threshold": 0.2, "split_feature": 1, "node_index": 0, "left_child": 1, "right_child": 2 }, { "node_index": 1, "leaf_value": [1.5] }, { "node_index": 2, "leaf_value": [0.9] }] } }], "aggregate_output": { "weighted_sum": { "weights": [0.5, 0.5, 0.5] } }, "target_type": "regression" } }, "preprocessors": [] }, "input": { "field_names": ["col1", "col2", "col3"] }, "inference_config": { "regression": {} } } """; Request model = new Request("PUT", "_ml/trained_models/" + modelId); model.setJsonEntity(modelConfig); assertThat(client().performRequest(model).getStatusLine().getStatusCode(), equalTo(200)); } public void testStartDeploymentWithInconsistentTotalLengths() throws IOException { String modelId = "inconsistent-size-model"; putPyTorchModel(modelId); putModelDefinitionPart(modelId, 500, 3, 0); putModelDefinitionPart(modelId, 500, 3, 1); putModelDefinitionPart(modelId, 600, 3, 2); ResponseException responseException = expectThrows(ResponseException.class, () -> startDeployment(modelId)); assertThat( responseException.getMessage(), containsString( "[total_definition_length] must be the same in all model definition parts. " + "The value [600] in model definition part [2] does not match the value [500] in part [0]" ) ); } private void putPyTorchModel(String modelId) throws IOException { Request request = new Request("PUT", "/_ml/trained_models/" + modelId); request.setJsonEntity(""" { "description": "simple model for testing", "model_type": "pytorch", "inference_config": { "pass_through": {} } }"""); client().performRequest(request); } private void putModelDefinitionPart(String modelId, int totalSize, int numParts, int partNumber) throws IOException { Request request = new Request("PUT", "_ml/trained_models/" + modelId + "/definition/" + partNumber); request.setJsonEntity(Strings.format(""" { "total_definition_length": %s, "definition": "UEsDBAAACAgAAAAAAAAAAAAAAAAAAAAAAAAUAA4Ac2ltcGxlbW9kZW==", "total_parts": %s }""", totalSize, numParts)); client().performRequest(request); } private void startDeployment(String modelId) throws IOException { Request request = new Request("POST", "/_ml/trained_models/" + modelId + "/deployment/_start?timeout=40s"); client().performRequest(request); } @After public void clearMlState() throws Exception { new MlRestTestStateCleaner(logger, adminClient()).resetFeatures(); ESRestTestCase.waitForPendingTasks(adminClient()); } }
TrainedModelIT
java
dropwizard__dropwizard
dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/TransactionHandlingTest.java
{ "start": 6663, "end": 7000 }
class ____ { @Nullable private Dog dog; public Optional<Dog> getDog() { return Optional.ofNullable(dog); } public void setDog(@Nullable Dog dog) { this.dog = dog; } } @Path("/dogs/{name}") @Produces(MediaType.APPLICATION_JSON) public static
DogResult
java
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsAsyncStartListenerTest.java
{ "start": 1322, "end": 2651 }
class ____ extends AbstractPersistentJMSTest { protected final String componentName = "activemq"; @Test public void testAsyncStartListener() throws Exception { MockEndpoint result = getMockEndpoint("mock:result"); result.expectedMessageCount(2); template.sendBody("activemq:queue:JmsAsyncStartListenerTest", "Hello World"); template.sendBody("activemq:queue:JmsAsyncStartListenerTest", "Goodbye World"); result.assertIsSatisfied(); } @Override protected void createConnectionFactory(CamelContext camelContext) { // use a persistent queue as the consumer is started asynchronously // so we need a persistent store in case no active consumers when we send the messages ConnectionFactory connectionFactory = ConnectionFactoryHelper.createConnectionFactory(service); JmsComponent jms = jmsComponentAutoAcknowledge(connectionFactory); jms.getConfiguration().setAsyncStartListener(true); camelContext.addComponent(componentName, jms); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("activemq:queue:JmsAsyncStartListenerTest").to("mock:result"); } }; } }
JmsAsyncStartListenerTest
java
apache__camel
components/camel-jms/src/main/java/org/apache/camel/component/jms/PassThroughJmsKeyFormatStrategy.java
{ "start": 954, "end": 1194 }
class ____ implements JmsKeyFormatStrategy { @Override public String encodeKey(String key) { return key; } @Override public String decodeKey(String key) { return key; } }
PassThroughJmsKeyFormatStrategy
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/impl/FromMultipleEndpointTest.java
{ "start": 1175, "end": 2315 }
class ____ extends ContextTestSupport { @Test public void testMultipleFromEndpoint() throws Exception { MockEndpoint mock = getMockEndpoint("mock:results"); mock.expectedMessageCount(2); template.sendBody("direct:foo", "foo"); template.sendBody("seda:bar", "bar"); mock.assertIsSatisfied(); List<Exchange> list = mock.getReceivedExchanges(); Exchange exchange = list.get(0); Endpoint fromEndpoint = exchange.getFromEndpoint(); assertEquals("direct://foo", fromEndpoint.getEndpointUri(), "fromEndpoint URI"); exchange = list.get(1); fromEndpoint = exchange.getFromEndpoint(); assertEquals("seda://bar", fromEndpoint.getEndpointUri(), "fromEndpoint URI"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { getContext().setTracing(true); from("direct:foo").to("mock:results"); from("seda:bar").to("mock:results"); } }; } }
FromMultipleEndpointTest
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/utils/LicenseUtils.java
{ "start": 669, "end": 2930 }
enum ____ { SEARCH_APPLICATION("search application", License.OperationMode.PLATINUM), BEHAVIORAL_ANALYTICS("behavioral analytics", License.OperationMode.PLATINUM), QUERY_RULES("query rules", License.OperationMode.ENTERPRISE),; private final String name; private final License.OperationMode requiredLicense; Product(String name, License.OperationMode requiredLicense) { this.name = name; this.requiredLicense = requiredLicense; } public String getName() { return name; } public LicensedFeature.Momentary getLicensedFeature() { return switch (requiredLicense) { case PLATINUM -> PLATINUM_LICENSED_FEATURE; case ENTERPRISE -> ENTERPRISE_LICENSED_FEATURE; default -> throw new IllegalStateException("Unknown license operation mode: " + requiredLicense); }; } } public static final LicensedFeature.Momentary PLATINUM_LICENSED_FEATURE = LicensedFeature.momentary( null, XPackField.ENTERPRISE_SEARCH, License.OperationMode.PLATINUM ); public static final LicensedFeature.Momentary ENTERPRISE_LICENSED_FEATURE = LicensedFeature.momentary( null, XPackField.ENTERPRISE_SEARCH, License.OperationMode.ENTERPRISE ); public static boolean supportedLicense(Product product, XPackLicenseState licenseState) { return product.getLicensedFeature().check(licenseState); } public static ElasticsearchSecurityException newComplianceException(XPackLicenseState licenseState, Product product) { String licenseStatus = licenseState.statusDescription(); String requiredLicenseStatus = product.requiredLicense.toString().toLowerCase(Locale.ROOT); ElasticsearchSecurityException e = new ElasticsearchSecurityException( "Current license is non-compliant for " + product.getName() + ". Current license is {}. " + "This feature requires an active trial, {}, or higher license.", RestStatus.FORBIDDEN, licenseStatus, requiredLicenseStatus ); return e; } }
Product
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/FSOperations.java
{ "start": 58376, "end": 60594 }
class ____ implements FileSystemAccess.FileSystemExecutor<String> { private final Path path; private final String oldSnapshotName; private final String snapshotName; private final String snapshotDiffStartPath; private final int snapshotDiffIndex; /** * Creates a getSnapshotDiffListing executor. * * @param path directory path of the snapshots to be examined. * @param oldSnapshotName Older snapshot name. * @param snapshotName Newer snapshot name. * @param snapshotDiffStartPath snapshot diff start path. * @param snapshotDiffIndex snapshot diff index. */ public FSGetSnapshotDiffListing(String path, String oldSnapshotName, String snapshotName, String snapshotDiffStartPath, int snapshotDiffIndex) { this.path = new Path(path); this.oldSnapshotName = oldSnapshotName; this.snapshotName = snapshotName; this.snapshotDiffStartPath = snapshotDiffStartPath; this.snapshotDiffIndex = snapshotDiffIndex; } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * @return A serialized JSON string of snapshot diffs. * @throws IOException thrown if an IO error occurred. */ @Override public String execute(FileSystem fs) throws IOException { SnapshotDiffReportListing snapshotDiffReportListing = null; if (fs instanceof DistributedFileSystem) { DistributedFileSystem dfs = (DistributedFileSystem) fs; snapshotDiffReportListing = dfs.getSnapshotDiffReportListing(path, oldSnapshotName, snapshotName, snapshotDiffStartPath, snapshotDiffIndex); } else { throw new UnsupportedOperationException("getSnapshotDiffListing is not " + "supported for HttpFs on " + fs.getClass() + ". Please check your fs.defaultFS configuration"); } if (snapshotDiffReportListing != null) { return JsonUtil.toJsonString(snapshotDiffReportListing); } else { return ""; } } } /** * Executor that performs a getSnapshottableDirListing operation. */ @InterfaceAudience.Private public static
FSGetSnapshotDiffListing
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/BugCheckerTest.java
{ "start": 7451, "end": 7911 }
class ____ extends BugChecker implements VariableTreeMatcher { @Override public Description matchVariable(VariableTree tree, VisitorState state) { return describeMatch(tree); } } @BugPattern( name = "OnlySuppressedInsideDeprecatedCode", summary = "Can be suppressed using `@Deprecated`, but not `@SuppressWarnings`", severity = ERROR, suppressionAnnotations = Deprecated.class) public static final
SuppressibleCheck
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/InfiniteRecursionTest.java
{ "start": 8298, "end": 8587 }
class ____ { Runnable f() { return () -> f(); } } """) .doTest(); } @Test public void positiveGeneric() { compilationHelper .addSourceLines( "Test.java", """
Test
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/grant/MySqlGrantTest_6.java
{ "start": 969, "end": 2377 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "GRANT SELECT, INSERT ON mydb.mytbl TO 'someuser'@'somehost';"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); // print(statementList); assertEquals(1, statementList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); String output = SQLUtils.toMySqlString(stmt); assertEquals("GRANT SELECT, INSERT ON mydb.mytbl TO 'someuser'@'somehost';", // output); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("City"))); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("t2"))); // assertTrue(visitor.getColumns().contains(new Column("t2", "id"))); } }
MySqlGrantTest_6
java
google__guava
guava-tests/test/com/google/common/hash/BloomFilterTest.java
{ "start": 1942, "end": 15417 }
class ____ extends TestCase { private static final int NUM_PUTS = 100_000; private static final ThreadLocal<Random> random = new ThreadLocal<Random>() { @Override protected Random initialValue() { return new Random(); } }; private static final int GOLDEN_PRESENT_KEY = random.get().nextInt(); @AndroidIncompatible // OutOfMemoryError public void testLargeBloomFilterDoesntOverflow() { long numBits = Integer.MAX_VALUE; numBits++; LockFreeBitArray bitArray = new LockFreeBitArray(numBits); assertTrue( "BitArray.bitSize() must return a positive number, but was " + bitArray.bitSize(), bitArray.bitSize() > 0); // Ideally we would also test the bitSize() overflow of this BF, but it runs out of heap space // BloomFilter.create(Funnels.unencodedCharsFunnel(), 244412641, 1e-11); } /** * Asserts that {@link BloomFilter#approximateElementCount} is within 1 percent of the expected * value. */ private static void assertApproximateElementCountGuess(BloomFilter<?> bf, int sizeGuess) { assertThat(bf.approximateElementCount()).isAtLeast((long) (sizeGuess * 0.99)); assertThat(bf.approximateElementCount()).isAtMost((long) (sizeGuess * 1.01)); } public void testCreateAndCheckMitz32BloomFilterWithKnownFalsePositives() { int numInsertions = 1000000; BloomFilter<String> bf = BloomFilter.create( Funnels.unencodedCharsFunnel(), numInsertions, 0.03, BloomFilterStrategies.MURMUR128_MITZ_32); // Insert "numInsertions" even numbers into the BF. for (int i = 0; i < numInsertions * 2; i += 2) { bf.put(Integer.toString(i)); } assertApproximateElementCountGuess(bf, numInsertions); // Assert that the BF "might" have all of the even numbers. for (int i = 0; i < numInsertions * 2; i += 2) { assertTrue(bf.mightContain(Integer.toString(i))); } // Now we check for known false positives using a set of known false positives. // (These are all of the false positives under 900.) ImmutableSet<Integer> falsePositives = ImmutableSet.of( 49, 51, 59, 163, 199, 321, 325, 363, 367, 469, 545, 561, 727, 769, 773, 781); for (int i = 1; i < 900; i += 2) { if (!falsePositives.contains(i)) { assertFalse("BF should not contain " + i, bf.mightContain(Integer.toString(i))); } } // Check that there are exactly 29824 false positives for this BF. int knownNumberOfFalsePositives = 29824; int numFpp = 0; for (int i = 1; i < numInsertions * 2; i += 2) { if (bf.mightContain(Integer.toString(i))) { numFpp++; } } assertEquals(knownNumberOfFalsePositives, numFpp); double expectedReportedFpp = (double) knownNumberOfFalsePositives / numInsertions; double actualReportedFpp = bf.expectedFpp(); assertThat(actualReportedFpp).isWithin(0.00015).of(expectedReportedFpp); } public void testCreateAndCheckBloomFilterWithKnownFalsePositives64() { int numInsertions = 1000000; BloomFilter<String> bf = BloomFilter.create( Funnels.unencodedCharsFunnel(), numInsertions, 0.03, BloomFilterStrategies.MURMUR128_MITZ_64); // Insert "numInsertions" even numbers into the BF. for (int i = 0; i < numInsertions * 2; i += 2) { bf.put(Integer.toString(i)); } assertApproximateElementCountGuess(bf, numInsertions); // Assert that the BF "might" have all of the even numbers. for (int i = 0; i < numInsertions * 2; i += 2) { assertTrue(bf.mightContain(Integer.toString(i))); } // Now we check for known false positives using a set of known false positives. // (These are all of the false positives under 900.) ImmutableSet<Integer> falsePositives = ImmutableSet.of(15, 25, 287, 319, 381, 399, 421, 465, 529, 697, 767, 857); for (int i = 1; i < 900; i += 2) { if (!falsePositives.contains(i)) { assertFalse("BF should not contain " + i, bf.mightContain(Integer.toString(i))); } } // Check that there are exactly 30104 false positives for this BF. int knownNumberOfFalsePositives = 30104; int numFpp = 0; for (int i = 1; i < numInsertions * 2; i += 2) { if (bf.mightContain(Integer.toString(i))) { numFpp++; } } assertEquals(knownNumberOfFalsePositives, numFpp); double expectedReportedFpp = (double) knownNumberOfFalsePositives / numInsertions; double actualReportedFpp = bf.expectedFpp(); assertThat(actualReportedFpp).isWithin(0.00033).of(expectedReportedFpp); } public void testCreateAndCheckBloomFilterWithKnownUtf8FalsePositives64() { int numInsertions = 1000000; BloomFilter<String> bf = BloomFilter.create( Funnels.stringFunnel(UTF_8), numInsertions, 0.03, BloomFilterStrategies.MURMUR128_MITZ_64); // Insert "numInsertions" even numbers into the BF. for (int i = 0; i < numInsertions * 2; i += 2) { bf.put(Integer.toString(i)); } assertApproximateElementCountGuess(bf, numInsertions); // Assert that the BF "might" have all of the even numbers. for (int i = 0; i < numInsertions * 2; i += 2) { assertTrue(bf.mightContain(Integer.toString(i))); } // Now we check for known false positives using a set of known false positives. // (These are all of the false positives under 900.) ImmutableSet<Integer> falsePositives = ImmutableSet.of(129, 471, 723, 89, 751, 835, 871); for (int i = 1; i < 900; i += 2) { if (!falsePositives.contains(i)) { assertFalse("BF should not contain " + i, bf.mightContain(Integer.toString(i))); } } // Check that there are exactly 29763 false positives for this BF. int knownNumberOfFalsePositives = 29763; int numFpp = 0; for (int i = 1; i < numInsertions * 2; i += 2) { if (bf.mightContain(Integer.toString(i))) { numFpp++; } } assertEquals(knownNumberOfFalsePositives, numFpp); double expectedReportedFpp = (double) knownNumberOfFalsePositives / numInsertions; double actualReportedFpp = bf.expectedFpp(); assertThat(actualReportedFpp).isWithin(0.00033).of(expectedReportedFpp); } /** Sanity checking with many combinations of false positive rates and expected insertions */ public void testBasic() { for (double fpr = 0.0000001; fpr < 0.1; fpr *= 10) { for (int expectedInsertions = 1; expectedInsertions <= 10000; expectedInsertions *= 10) { checkSanity(BloomFilter.create(HashTestUtils.BAD_FUNNEL, expectedInsertions, fpr)); } } } public void testPreconditions() { assertThrows( IllegalArgumentException.class, () -> BloomFilter.create(Funnels.unencodedCharsFunnel(), -1)); assertThrows( IllegalArgumentException.class, () -> BloomFilter.create(Funnels.unencodedCharsFunnel(), -1, 0.03)); assertThrows( IllegalArgumentException.class, () -> BloomFilter.create(Funnels.unencodedCharsFunnel(), 1, 0.0)); assertThrows( IllegalArgumentException.class, () -> BloomFilter.create(Funnels.unencodedCharsFunnel(), 1, 1.0)); } public void testFailureWhenMoreThan255HashFunctionsAreNeeded() { int n = 1000; double p = 0.00000000000000000000000000000000000000000000000000000000000000000000000000000001; assertThrows( IllegalArgumentException.class, () -> { BloomFilter.create(Funnels.unencodedCharsFunnel(), n, p); }); } public void testNullPointers() { NullPointerTester tester = new NullPointerTester(); tester.testAllPublicInstanceMethods(BloomFilter.create(Funnels.unencodedCharsFunnel(), 100)); tester.testAllPublicStaticMethods(BloomFilter.class); } /** Tests that we never get an optimal hashes number of zero. */ public void testOptimalHashes() { for (int n = 1; n < 1000; n++) { for (double p = 0.1; p > 1e-10; p /= 10) { assertThat(BloomFilter.optimalNumOfHashFunctions(p)).isGreaterThan(0); } } } // https://github.com/google/guava/issues/1781 public void testOptimalNumOfHashFunctionsRounding() { assertEquals(5, BloomFilter.optimalNumOfHashFunctions(0.03)); } /** Tests that we always get a non-negative optimal size. */ public void testOptimalSize() { for (int n = 1; n < 1000; n++) { for (double fpp = Double.MIN_VALUE; fpp < 1.0; fpp += 0.001) { assertThat(BloomFilter.optimalNumOfBits(n, fpp)).isAtLeast(0); } } // some random values Random random = new Random(0); for (int repeats = 0; repeats < 10000; repeats++) { assertThat(BloomFilter.optimalNumOfBits(random.nextInt(1 << 16), random.nextDouble())) .isAtLeast(0); } // and some crazy values (this used to be capped to Integer.MAX_VALUE, now it can go bigger assertEquals(3327428144502L, BloomFilter.optimalNumOfBits(Integer.MAX_VALUE, Double.MIN_VALUE)); IllegalArgumentException expected = assertThrows( IllegalArgumentException.class, () -> { BloomFilter<String> unused = BloomFilter.create(HashTestUtils.BAD_FUNNEL, Integer.MAX_VALUE, Double.MIN_VALUE); }); assertThat(expected) .hasMessageThat() .isEqualTo("Could not create BloomFilter of 3327428144502 bits"); } @AndroidIncompatible // OutOfMemoryError public void testLargeNumberOfInsertions() { // We use horrible FPPs here to keep Java from OOM'ing BloomFilter<String> unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), Integer.MAX_VALUE / 2, 0.30); unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), 45L * Integer.MAX_VALUE, 0.99); } @SuppressWarnings({"deprecation", "InlineMeInliner"}) // test of a deprecated method private static void checkSanity(BloomFilter<Object> bf) { assertFalse(bf.mightContain(new Object())); assertFalse(bf.apply(new Object())); assertFalse(bf.test(new Object())); for (int i = 0; i < 100; i++) { Object o = new Object(); bf.put(o); assertTrue(bf.mightContain(o)); assertTrue(bf.apply(o)); assertTrue(bf.test(o)); } } public void testCopy() { BloomFilter<String> original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100); BloomFilter<String> copy = original.copy(); assertNotSame(original, copy); assertEquals(original, copy); } public void testExpectedFpp() { BloomFilter<Object> bf = BloomFilter.create(HashTestUtils.BAD_FUNNEL, 10, 0.03); double fpp = bf.expectedFpp(); assertThat(fpp).isEqualTo(0.0); // usually completed in less than 200 iterations while (fpp != 1.0) { boolean changed = bf.put(new Object()); double newFpp = bf.expectedFpp(); // if changed, the new fpp is strictly higher, otherwise it is the same assertTrue(changed ? newFpp > fpp : newFpp == fpp); fpp = newFpp; } } @AndroidIncompatible // slow public void testBitSize() { double fpp = 0.03; for (int i = 1; i < 10000; i++) { long numBits = BloomFilter.optimalNumOfBits(i, fpp); int arraySize = Ints.checkedCast(LongMath.divide(numBits, 64, RoundingMode.CEILING)); assertEquals( arraySize * Long.SIZE, BloomFilter.create(Funnels.unencodedCharsFunnel(), i, fpp).bitSize()); } } public void testApproximateElementCount() { int numInsertions = 1000; BloomFilter<Integer> bf = BloomFilter.create(Funnels.integerFunnel(), numInsertions); bf.put(-1); for (int i = 0; i < numInsertions; i++) { bf.put(i); } assertApproximateElementCountGuess(bf, numInsertions); } public void testEquals_empty() { new EqualsTester() .addEqualityGroup(BloomFilter.create(Funnels.byteArrayFunnel(), 100, 0.01)) .addEqualityGroup(BloomFilter.create(Funnels.byteArrayFunnel(), 100, 0.02)) .addEqualityGroup(BloomFilter.create(Funnels.byteArrayFunnel(), 200, 0.01)) .addEqualityGroup(BloomFilter.create(Funnels.byteArrayFunnel(), 200, 0.02)) .addEqualityGroup(BloomFilter.create(Funnels.unencodedCharsFunnel(), 100, 0.01)) .addEqualityGroup(BloomFilter.create(Funnels.unencodedCharsFunnel(), 100, 0.02)) .addEqualityGroup(BloomFilter.create(Funnels.unencodedCharsFunnel(), 200, 0.01)) .addEqualityGroup(BloomFilter.create(Funnels.unencodedCharsFunnel(), 200, 0.02)) .testEquals(); } public void testEquals() { BloomFilter<String> bf1 = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100); bf1.put("1"); bf1.put("2"); BloomFilter<String> bf2 = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100); bf2.put("1"); bf2.put("2"); new EqualsTester().addEqualityGroup(bf1, bf2).testEquals(); bf2.put("3"); new EqualsTester().addEqualityGroup(bf1).addEqualityGroup(bf2).testEquals(); } public void testEqualsWithCustomFunnel() { BloomFilter<Long> bf1 = BloomFilter.create(new CustomFunnel(), 100); BloomFilter<Long> bf2 = BloomFilter.create(new CustomFunnel(), 100); assertEquals(bf1, bf2); } public void testSerializationWithCustomFunnel() { SerializableTester.reserializeAndAssert(BloomFilter.create(new CustomFunnel(), 100)); } private static final
BloomFilterTest
java
square__retrofit
retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/CancelDisposeTestSync.java
{ "start": 1038, "end": 1762 }
interface ____ { @GET("/") Observable<String> go(); } private final OkHttpClient client = new OkHttpClient(); private Service service; @Before public void setUp() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new StringConverterFactory()) .addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous()) .callFactory(client) .build(); service = retrofit.create(Service.class); } @SuppressWarnings("ResultOfMethodCallIgnored") @Test public void disposeBeforeExecuteDoesNotEnqueue() { service.go().test(true); assertEquals(0, server.getRequestCount()); } }
Service
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/OtherMultipartResource.java
{ "start": 279, "end": 613 }
class ____ { @Path("simple") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.MULTIPART_FORM_DATA) @POST public String simple(@BeanParam OtherFormData formData) { return formData.first + " - " + formData.last + " - " + formData.finalField + " - " + OtherFormData.staticField; } }
OtherMultipartResource
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/discovery/ParameterizedBeanTypeWithVariableTest.java
{ "start": 702, "end": 797 }
class ____<T> { protected String ping() { return "foo"; } } }
Foo
java
google__guava
android/guava-testlib/test/com/google/common/collect/testing/MyTester.java
{ "start": 1137, "end": 1297 }
class ____ extends AbstractTester<@Nullable Void> { static int timesTestClassWasRun = 0; public void testNothing() { timesTestClassWasRun++; } }
MyTester
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/exec/internal/lock/CollectionLockingAction.java
{ "start": 1412, "end": 6077 }
class ____ implements PostAction { // Used by Hibernate Reactive protected final LoadedValuesCollectorImpl loadedValuesCollector; // Used by Hibernate Reactive protected final LockMode lockMode; // Used by Hibernate Reactive protected final Timeout lockTimeout; // Used by Hibernate Reactive protected CollectionLockingAction( LoadedValuesCollectorImpl loadedValuesCollector, LockMode lockMode, Timeout lockTimeout) { this.loadedValuesCollector = loadedValuesCollector; this.lockMode = lockMode; this.lockTimeout = lockTimeout; } public static void apply( LockOptions lockOptions, QuerySpec lockingTarget, JdbcSelectWithActionsBuilder jdbcSelectBuilder) { assert lockOptions.getScope() == Locking.Scope.INCLUDE_COLLECTIONS; final var loadedValuesCollector = resolveLoadedValuesCollector( lockingTarget ); // NOTE: we need to set this separately so that it can get incorporated into // the JdbcValuesSourceProcessingState for proper callbacks jdbcSelectBuilder.setLoadedValuesCollector( loadedValuesCollector ); // additionally, add a post-action which uses the collected values. jdbcSelectBuilder.appendPostAction( new CollectionLockingAction( loadedValuesCollector, lockOptions.getLockMode(), lockOptions.getTimeout() ) ); } @Override public void performPostAction( StatementAccess jdbcStatementAccess, Connection jdbcConnection, ExecutionContext executionContext) { performPostAction( executionContext ); } // Used by Hibernate Reactive protected void performPostAction(ExecutionContext executionContext) { LockingHelper.logLoadedValues( loadedValuesCollector ); final var session = executionContext.getSession(); // NOTE: we deal with effective graphs here to make sure embedded associations are treated as lazy final var effectiveEntityGraph = session.getLoadQueryInfluencers().getEffectiveEntityGraph(); final var initialGraph = effectiveEntityGraph.getGraph(); final var initialSemantic = effectiveEntityGraph.getSemantic(); // collect registrations by entity type final var entitySegments = segmentLoadedValues( loadedValuesCollector ); try { // for each entity-type, prepare a locking select statement per table. // this is based on the attributes for "state array" ordering purposes - // we match each attribute to the table it is mapped to and add it to // the select-list for that table-segment. entitySegments.forEach( (entityMappingType, entityKeys) -> { if ( SQL_EXEC_LOGGER.isDebugEnabled() ) { SQL_EXEC_LOGGER.startingIncludeCollectionsLockingProcess( entityMappingType.getEntityName() ); } // apply an empty "fetch graph" to make sure any embedded associations reachable from // any of the DomainResults we will create are treated as lazy final var graph = entityMappingType.createRootGraph( session ); effectiveEntityGraph.clear(); effectiveEntityGraph.applyGraph( graph, GraphSemantic.FETCH ); // create a cross-reference of information related to an entity based on its identifier. // we use this as the collection owners whose collections need to be locked final var entityDetailsMap = LockingHelper.resolveEntityKeys( entityKeys, executionContext ); SqmMutationStrategyHelper.visitCollectionTables( entityMappingType, (attribute) -> { // we may need to lock the "collection table". // the conditions are a bit unclear as to directionality, etc., so for now lock each. LockingHelper.lockCollectionTable( attribute, lockMode, lockTimeout, entityDetailsMap, executionContext ); } ); } ); } finally { // reset the effective graph to whatever it was when we started effectiveEntityGraph.clear(); session.getLoadQueryInfluencers().applyEntityGraph( initialGraph, initialSemantic ); } } // Used by Hibernate Reactive protected static LoadedValuesCollectorImpl resolveLoadedValuesCollector(QuerySpec lockingTarget) { return new LoadedValuesCollectorImpl( lockingTarget.getRootPathsForLocking() ); } // Used by Hibernate Reactive protected static Map<EntityMappingType, List<EntityKey>> segmentLoadedValues(LoadedValuesCollector loadedValuesCollector) { final Map<EntityMappingType, List<EntityKey>> map = new IdentityHashMap<>(); LockingHelper.segmentLoadedValues( loadedValuesCollector.getCollectedEntities(), map ); if ( map.isEmpty() ) { // NOTE: this may happen with Session#lock routed through SqlAstBasedLockingStrategy. // however, we cannot tell that is the code path from here. } return map; } // Used by Hibernate Reactive protected static
CollectionLockingAction
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestWritableJobConf.java
{ "start": 1367, "end": 3778 }
class ____ { private static final Configuration CONF = new Configuration(); private <K> K serDeser(K conf) throws Exception { SerializationFactory factory = new SerializationFactory(CONF); Serializer<K> serializer = factory.getSerializer(GenericsUtil.getClass(conf)); Deserializer<K> deserializer = factory.getDeserializer(GenericsUtil.getClass(conf)); DataOutputBuffer out = new DataOutputBuffer(); serializer.open(out); serializer.serialize(conf); serializer.close(); DataInputBuffer in = new DataInputBuffer(); in.reset(out.getData(), out.getLength()); deserializer.open(in); K after = deserializer.deserialize(null); deserializer.close(); return after; } private void assertEquals(Configuration conf1, Configuration conf2) { // We ignore deprecated keys because after deserializing, both the // deprecated and the non-deprecated versions of a config are set. // This is consistent with both the set and the get methods. Iterator<Map.Entry<String, String>> iterator1 = conf1.iterator(); Map<String, String> map1 = new HashMap<String,String>(); while (iterator1.hasNext()) { Map.Entry<String, String> entry = iterator1.next(); if (!Configuration.isDeprecated(entry.getKey())) { map1.put(entry.getKey(), entry.getValue()); } } Iterator<Map.Entry<String, String>> iterator2 = conf2.iterator(); Map<String, String> map2 = new HashMap<String,String>(); while (iterator2.hasNext()) { Map.Entry<String, String> entry = iterator2.next(); if (!Configuration.isDeprecated(entry.getKey())) { map2.put(entry.getKey(), entry.getValue()); } } assertTrue(map1.equals(map2)); } @Test public void testEmptyConfiguration() throws Exception { JobConf conf = new JobConf(); Configuration deser = serDeser(conf); assertEquals(conf, deser); } @Test public void testNonEmptyConfiguration() throws Exception { JobConf conf = new JobConf(); conf.set("a", "A"); conf.set("b", "B"); Configuration deser = serDeser(conf); assertEquals(conf, deser); } @Test public void testConfigurationWithDefaults() throws Exception { JobConf conf = new JobConf(false); conf.set("a", "A"); conf.set("b", "B"); Configuration deser = serDeser(conf); assertEquals(conf, deser); } }
TestWritableJobConf
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaWindowFunctionTest.java
{ "start": 1923, "end": 14538 }
class ____ { @BeforeEach public void prepareData(SessionFactoryScope scope) { scope.inTransaction( em -> { Date now = new Date(); EntityOfBasics entity1 = new EntityOfBasics(); entity1.setId( 1 ); entity1.setTheString( "5" ); entity1.setTheInt( 5 ); entity1.setTheInteger( -1 ); entity1.setTheDouble( 5.0 ); entity1.setTheDate( now ); entity1.setTheBoolean( true ); em.persist( entity1 ); EntityOfBasics entity2 = new EntityOfBasics(); entity2.setId( 2 ); entity2.setTheString( "6" ); entity2.setTheInt( 6 ); entity2.setTheInteger( -2 ); entity2.setTheDouble( 6.0 ); entity2.setTheBoolean( true ); em.persist( entity2 ); EntityOfBasics entity3 = new EntityOfBasics(); entity3.setId( 3 ); entity3.setTheString( "7" ); entity3.setTheInt( 7 ); entity3.setTheInteger( 3 ); entity3.setTheDouble( 7.0 ); entity3.setTheBoolean( false ); entity3.setTheDate( new Date( now.getTime() + 200000L ) ); em.persist( entity3 ); EntityOfBasics entity4 = new EntityOfBasics(); entity4.setId( 4 ); entity4.setTheString( "13" ); entity4.setTheInt( 13 ); entity4.setTheInteger( 4 ); entity4.setTheDouble( 13.0 ); entity4.setTheBoolean( false ); entity4.setTheDate( new Date( now.getTime() + 300000L ) ); em.persist( entity4 ); EntityOfBasics entity5 = new EntityOfBasics(); entity5.setId( 5 ); entity5.setTheString( "5" ); entity5.setTheInt( 5 ); entity5.setTheInteger( 5 ); entity5.setTheDouble( 9.0 ); entity5.setTheBoolean( false ); em.persist( entity5 ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testRowNumberWithoutOrder(SessionFactoryScope scope) { scope.inTransaction( session -> { HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Long> cr = cb.createQuery( Long.class ); cr.from( EntityOfBasics.class ); JpaWindow window = cb.createWindow(); JpaExpression<Long> rowNumber = cb.rowNumber( window ); cr.select( rowNumber ).orderBy( cb.asc( cb.literal( 1 ) ) ); List<Long> resultList = session.createQuery( cr ).getResultList(); assertEquals( 5, resultList.size() ); assertEquals( 1L, resultList.get( 0 ) ); assertEquals( 2L, resultList.get( 1 ) ); assertEquals( 3L, resultList.get( 2 ) ); assertEquals( 4L, resultList.get( 3 ) ); assertEquals( 5L, resultList.get( 4 ) ); } ); } @Test @Jira( "https://hibernate.atlassian.net/browse/HHH-17391" ) public void testRowNumberMultiSelectGroupBy(final SessionFactoryScope scope) { scope.inTransaction( session -> { final HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); final CriteriaQuery<Tuple> cr = cb.createQuery( Tuple.class ); final Root<EntityOfBasics> root = cr.from( EntityOfBasics.class ); final JpaWindow window = cb.createWindow(); window.partitionBy( root.get( "id" ) ).orderBy( cb.asc( root.get( "id" ) ) ); final JpaExpression<Long> rowNumber = cb.rowNumber( window ); cr.multiselect( root.get( "id" ), rowNumber ).groupBy( root.get( "id" ) ); final List<Tuple> resultList = session.createQuery( cr ).getResultList(); assertEquals( 5, resultList.size() ); resultList.forEach( tuple -> assertEquals( 1L, tuple.get( 1, Long.class ) ) ); } ); } @Test @Jira( "https://hibernate.atlassian.net/browse/HHH-17392" ) public void testRowNumberMultiSelect(final SessionFactoryScope scope) { scope.inTransaction( session -> { final HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); final CriteriaQuery<Tuple> cr = cb.createQuery( Tuple.class ); final Root<EntityOfBasics> root = cr.from( EntityOfBasics.class ); final JpaWindow window = cb.createWindow(); window.partitionBy( root.get( "id" ) ).orderBy( cb.asc( root.get( "id" ) ) ); final JpaExpression<Long> rowNumber = cb.rowNumber( window ); cr.multiselect( root.get( "id" ), rowNumber ); final List<Tuple> resultList = session.createQuery( cr ).getResultList(); assertEquals( 5, resultList.size() ); resultList.forEach( tuple -> assertEquals( 1L, tuple.get( 1, Long.class ) ) ); } ); } @Test public void testFirstValue(SessionFactoryScope scope) { scope.inTransaction( session -> { HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Integer> cr = cb.createQuery( Integer.class ); Root<EntityOfBasics> root = cr.from( EntityOfBasics.class ); JpaWindow window = cb.createWindow().orderBy( cb.desc( root.get( "theInt" ) ) ); JpaExpression<Integer> firstValue = cb.firstValue( root.get( "theInt" ), window ); cr.select( firstValue ).orderBy( cb.asc( cb.literal( 1 ) ) ); List<Integer> resultList = session.createQuery( cr ).getResultList(); assertEquals( 5, resultList.size() ); assertEquals( 13, resultList.get( 0 ) ); assertEquals( 13, resultList.get( 1 ) ); assertEquals( 13, resultList.get( 2 ) ); assertEquals( 13, resultList.get( 3 ) ); assertEquals( 13, resultList.get( 4 ) ); } ); } @Test @SkipForDialect(dialectClass = SQLServerDialect.class, reason = "No support for nth_value function") @SkipForDialect(dialectClass = DB2Dialect.class, majorVersion = 10, reason = "No support for nth_value function") @SkipForDialect(dialectClass = InformixDialect.class, reason = "No support for nth_value function") public void testNthValue(SessionFactoryScope scope) { scope.inTransaction( session -> { HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Integer> cr = cb.createQuery( Integer.class ); Root<EntityOfBasics> root = cr.from( EntityOfBasics.class ); JpaWindow window = cb.createWindow() .orderBy( cb.desc( root.get( "theInt" ) ) ) .frameRows( cb.frameUnboundedPreceding(), cb.frameUnboundedFollowing() ); JpaExpression<Integer> nthValue = cb.nthValue( root.get( "theInt" ), 2, window ); cr.select( nthValue ); List<Integer> resultList = session.createQuery( cr ).getResultList(); assertEquals( 5, resultList.size() ); assertEquals( 7, resultList.get( 0 ) ); assertEquals( 7, resultList.get( 1 ) ); assertEquals( 7, resultList.get( 2 ) ); assertEquals( 7, resultList.get( 3 ) ); assertEquals( 7, resultList.get( 4 ) ); } ); } @Test public void testRank(SessionFactoryScope scope) { scope.inTransaction( session -> { HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Long> cr = cb.createQuery( Long.class ); Root<EntityOfBasics> root = cr.from( EntityOfBasics.class ); JpaWindow window = cb.createWindow() .partitionBy( root.get( "theInt" ) ) .orderBy( cb.asc( root.get( "id" ) ) ); JpaExpression<Long> rank = cb.rank( window ); cr.select( rank ).orderBy( cb.asc( cb.literal( 1 ) ) ); List<Long> resultList = session.createQuery( cr ).getResultList(); assertEquals( 5, resultList.size() ); assertEquals( 1L, resultList.get( 0 ) ); assertEquals( 1L, resultList.get( 1 ) ); assertEquals( 1L, resultList.get( 2 ) ); assertEquals( 1L, resultList.get( 3 ) ); assertEquals( 2L, resultList.get( 4 ) ); } ); } @Test @SkipForDialect(dialectClass = DB2Dialect.class, majorVersion = 10, reason = "No support for percent_rank and cume_dist functions before DB2 11") @SkipForDialect(dialectClass = AltibaseDialect.class, reason = "No support for percent_rank and cume_dist functions with over clause") public void testReusableWindow(SessionFactoryScope scope) { scope.inTransaction( session -> { HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Tuple> cr = cb.createTupleQuery(); Root<EntityOfBasics> root = cr.from( EntityOfBasics.class ); JpaWindow window = cb.createWindow() .partitionBy( root.get( "theInt" ) ) .orderBy( cb.asc( root.get( "id" ) ) ); JpaExpression<Long> rowNumber = cb.rowNumber( window ); JpaExpression<Double> percentRank = cb.percentRank( window ); JpaExpression<Double> cumeDist = cb.cumeDist( window ); cr.multiselect( rowNumber, percentRank, cumeDist ).orderBy( cb.asc( cb.literal( 1 ) ) ); List<Tuple> resultList = session.createQuery( cr ).getResultList(); assertEquals( 5, resultList.size() ); assertEquals( 0D, resultList.get( 0 ).get( 1 ) ); assertEquals( 0D, resultList.get( 1 ).get( 1 ) ); assertEquals( 0D, resultList.get( 2 ).get( 1 ) ); assertEquals( 0D, resultList.get( 3 ).get( 1 ) ); assertEquals( 1D, resultList.get( 4 ).get( 1 ) ); assertEquals( 1D, resultList.get( 4 ).get( 2 ) ); } ); } @Test public void testSumWithFilterAndWindow(SessionFactoryScope scope) { scope.inTransaction( session -> { HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Long> cr = cb.createQuery( Long.class ); Root<EntityOfBasics> root = cr.from( EntityOfBasics.class ); Path<Integer> theInt = root.get( "theInt" ); JpaWindow window = cb.createWindow().orderBy( cb.asc( theInt ) ); JpaExpression<Long> sum = cb.sum( theInt, cb.gt( theInt, 5 ), window ).asLong(); cr.select( sum ).orderBy( cb.asc( theInt, true ) ); List<Long> resultList = session.createQuery( cr ).getResultList(); assertEquals( 5L, resultList.size() ); assertNull( resultList.get( 0 ) ); assertNull( resultList.get( 1 ) ); assertEquals( 6L, resultList.get( 2 ) ); assertEquals( 13L, resultList.get( 3 ) ); assertEquals( 26L, resultList.get( 4 ) ); } ); } @Test public void testAvgAsWindowFunctionWithoutFilter(SessionFactoryScope scope) { scope.inTransaction( session -> { HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Double> cr = cb.createQuery( Double.class ); Root<EntityOfBasics> root = cr.from( EntityOfBasics.class ); Path<Integer> id = root.get( "id" ); JpaWindow window = cb.createWindow().orderBy( cb.asc( id ) ); JpaExpression<Double> avg = cb.avg( id, window ); cr.select( avg ).orderBy( cb.asc( cb.literal( 1 ) ) ); List<Double> resultList = session.createQuery( cr ).getResultList(); assertEquals( 5L, resultList.size() ); assertEquals( 1.0, resultList.get( 0 ) ); assertEquals( 1.5, resultList.get( 1 ) ); assertEquals( 2.0, resultList.get( 2 ) ); assertEquals( 2.5, resultList.get( 3 ) ); assertEquals( 3.0, resultList.get( 4 ) ); } ); } @Test public void testCountAsWindowFunctionWithFilter(SessionFactoryScope scope) { scope.inTransaction( session -> { HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Long> cr = cb.createQuery( Long.class ); Root<EntityOfBasics> root = cr.from( EntityOfBasics.class ); JpaWindow window = cb.createWindow(); JpaExpression<Long> count = cb.count( root, cb.gt( root.get( "id" ), 2 ), window ); cr.select( count ); List<Long> resultList = session.createQuery( cr ).getResultList(); assertEquals( 5L, resultList.size() ); assertEquals( 3L, resultList.get( 0 ) ); assertEquals( 3L, resultList.get( 1 ) ); assertEquals( 3L, resultList.get( 2 ) ); assertEquals( 3L, resultList.get( 3 ) ); assertEquals( 3L, resultList.get( 4 ) ); } ); } @Test public void testFrame(SessionFactoryScope scope) { scope.inTransaction( session -> { HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Integer> cr = cb.createQuery( Integer.class ); Root<EntityOfBasics> root = cr.from( EntityOfBasics.class ); JpaWindow window = cb.createWindow() .orderBy( cb.asc( root.get( "id" ) ) ) .frameRows( cb.frameBetweenPreceding( 2 ), cb.frameCurrentRow() ); JpaExpression<Integer> firstValue = cb.firstValue( root.get( "theInt" ), window ); cr.select( firstValue ).orderBy( cb.asc( root.get( "id" ) ) ); List<Integer> resultList = session.createQuery( cr ).getResultList(); assertEquals( 5, resultList.size() ); assertEquals( 5, resultList.get( 0 ) ); assertEquals( 5, resultList.get( 1 ) ); assertEquals( 5, resultList.get( 2 ) ); assertEquals( 6, resultList.get( 3 ) ); assertEquals( 7, resultList.get( 4 ) ); } ); } }
CriteriaWindowFunctionTest
java
alibaba__nacos
plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/TokenManagerDelegateTest.java
{ "start": 1659, "end": 3618 }
class ____ { private TokenManagerDelegate tokenManagerDelegate; @Mock private CachedJwtTokenManager cachedJwtTokenManager; @Mock private Authentication authentication; @Mock private NacosUser user; @BeforeEach void setUp() throws Exception { tokenManagerDelegate = new TokenManagerDelegate(cachedJwtTokenManager); when(cachedJwtTokenManager.getTokenValidityInSeconds()).thenReturn(100L); when(cachedJwtTokenManager.getTokenTtlInSeconds(anyString())).thenReturn(100L); when(cachedJwtTokenManager.getAuthentication(anyString())).thenReturn(authentication); when(cachedJwtTokenManager.parseToken(anyString())).thenReturn(user); when(cachedJwtTokenManager.createToken(anyString())).thenReturn("token"); when(cachedJwtTokenManager.createToken(authentication)).thenReturn("token"); } @Test void testCreateToken1() throws AccessException { assertEquals("token", tokenManagerDelegate.createToken(authentication)); } @Test void testCreateToken2() throws AccessException { assertEquals("token", tokenManagerDelegate.createToken("nacos")); } @Test void testGetAuthentication() throws AccessException { assertNotNull(tokenManagerDelegate.getAuthentication("token")); } @Test void testValidateToken() throws AccessException { tokenManagerDelegate.validateToken("token"); } @Test void testParseToken() throws AccessException { assertNotNull(tokenManagerDelegate.parseToken("token")); } @Test void testGetTokenTtlInSeconds() throws AccessException { assertTrue(tokenManagerDelegate.getTokenTtlInSeconds("token") > 0); } @Test void testGetTokenValidityInSeconds() throws AccessException { assertTrue(tokenManagerDelegate.getTokenValidityInSeconds() > 0); } }
TokenManagerDelegateTest
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableUnsubscribeOn.java
{ "start": 918, "end": 1336 }
class ____<T> extends AbstractFlowableWithUpstream<T, T> { final Scheduler scheduler; public FlowableUnsubscribeOn(Flowable<T> source, Scheduler scheduler) { super(source); this.scheduler = scheduler; } @Override protected void subscribeActual(Subscriber<? super T> s) { source.subscribe(new UnsubscribeSubscriber<>(s, scheduler)); } static final
FlowableUnsubscribeOn
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/NumberReplicas.java
{ "start": 2116, "end": 2205 }
class ____ extends EnumCounters<NumberReplicas.StoredReplicaState> { public
NumberReplicas
java
netty__netty
transport-classes-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueServerChannel.java
{ "start": 2242, "end": 4317 }
class ____ extends AbstractKQueueUnsafe { // Will hold the remote address after accept(...) was successful. // We need 24 bytes for the address as maximum + 1 byte for storing the capacity. // So use 26 bytes as it's a power of two. private final byte[] acceptedAddress = new byte[26]; @Override void readReady(KQueueRecvByteAllocatorHandle allocHandle) { assert eventLoop().inEventLoop(); final ChannelConfig config = config(); if (shouldBreakReadReady(config)) { clearReadFilter0(); return; } final ChannelPipeline pipeline = pipeline(); allocHandle.reset(config); allocHandle.attemptedBytesRead(1); Throwable exception = null; try { try { do { int acceptFd = socket.accept(acceptedAddress); if (acceptFd == -1) { // this means everything was handled for now allocHandle.lastBytesRead(-1); break; } allocHandle.lastBytesRead(1); allocHandle.incMessagesRead(1); readPending = false; pipeline.fireChannelRead(newChildChannel(acceptFd, acceptedAddress, 1, acceptedAddress[0])); } while (allocHandle.continueReading()); } catch (Throwable t) { exception = t; } allocHandle.readComplete(); pipeline.fireChannelReadComplete(); if (exception != null) { pipeline.fireExceptionCaught(exception); } } finally { if (shouldStopReading(config)) { clearReadFilter0(); } } } } }
KQueueServerSocketUnsafe
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/slot/TaskSlot.java
{ "start": 2694, "end": 13204 }
class ____<T extends TaskSlotPayload> implements AutoCloseableAsync { private static final Logger LOG = LoggerFactory.getLogger(TaskSlot.class); /** Index of the task slot. */ private final int index; /** Resource characteristics for this slot. */ private final ResourceProfile resourceProfile; /** Tasks running in this slot. */ private final Map<ExecutionAttemptID, T> tasks; private final MemoryManager memoryManager; /** State of this slot. */ private TaskSlotState state; /** Job id to which the slot has been allocated. */ private final JobID jobId; /** Allocation id of this slot. */ private final AllocationID allocationId; /** The closing future is completed when the slot is freed and closed. */ private final CompletableFuture<Void> closingFuture; /** {@link Executor} for background actions, e.g. verify all managed memory released. */ private final Executor asyncExecutor; public TaskSlot( final int index, final ResourceProfile resourceProfile, final int memoryPageSize, final JobID jobId, final AllocationID allocationId, final Executor asyncExecutor) { this.index = index; this.resourceProfile = Preconditions.checkNotNull(resourceProfile); this.asyncExecutor = Preconditions.checkNotNull(asyncExecutor); this.tasks = CollectionUtil.newHashMapWithExpectedSize(4); this.state = TaskSlotState.ALLOCATED; this.jobId = jobId; this.allocationId = allocationId; this.memoryManager = createMemoryManager(resourceProfile, memoryPageSize); this.closingFuture = new CompletableFuture<>(); } // ---------------------------------------------------------------------------------- // State accessors // ---------------------------------------------------------------------------------- public int getIndex() { return index; } public ResourceProfile getResourceProfile() { return resourceProfile; } public JobID getJobId() { return jobId; } public AllocationID getAllocationId() { return allocationId; } TaskSlotState getState() { return state; } public boolean isEmpty() { return tasks.isEmpty(); } public boolean isActive(JobID activeJobId, AllocationID activeAllocationId) { Preconditions.checkNotNull(activeJobId); Preconditions.checkNotNull(activeAllocationId); return TaskSlotState.ACTIVE == state && activeJobId.equals(jobId) && activeAllocationId.equals(allocationId); } public boolean isAllocated(JobID jobIdToCheck, AllocationID allocationIDToCheck) { Preconditions.checkNotNull(jobIdToCheck); Preconditions.checkNotNull(allocationIDToCheck); return jobIdToCheck.equals(jobId) && allocationIDToCheck.equals(allocationId) && (TaskSlotState.ACTIVE == state || TaskSlotState.ALLOCATED == state); } public boolean isReleasing() { return TaskSlotState.RELEASING == state; } /** * Get all tasks running in this task slot. * * @return Iterator to all currently contained tasks in this task slot. */ public Iterator<T> getTasks() { return tasks.values().iterator(); } public MemoryManager getMemoryManager() { return memoryManager; } // ---------------------------------------------------------------------------------- // State changing methods // ---------------------------------------------------------------------------------- /** * Add the given task to the task slot. This is only possible if there is not already another * task with the same execution attempt id added to the task slot. In this case, the method * returns true. Otherwise the task slot is left unchanged and false is returned. * * <p>In case that the task slot state is not active an {@link IllegalStateException} is thrown. * In case that the task's job id and allocation id don't match with the job id and allocation * id for which the task slot has been allocated, an {@link IllegalArgumentException} is thrown. * * @param task to be added to the task slot * @throws IllegalStateException if the task slot is not in state active * @return true if the task was added to the task slot; otherwise false */ public boolean add(T task) { // Check that this slot has been assigned to the job sending this task Preconditions.checkArgument( task.getJobID().equals(jobId), "The task's job id does not match the " + "job id for which the slot has been allocated."); Preconditions.checkArgument( task.getAllocationId().equals(allocationId), "The task's allocation " + "id does not match the allocation id for which the slot has been allocated."); Preconditions.checkState( TaskSlotState.ACTIVE == state, "The task slot is not in state active."); T oldTask = tasks.put(task.getExecutionId(), task); if (oldTask != null) { tasks.put(task.getExecutionId(), oldTask); return false; } else { return true; } } /** * Remove the task identified by the given execution attempt id. * * @param executionAttemptId identifying the task to be removed * @return The removed task if there was any; otherwise null. */ public T remove(ExecutionAttemptID executionAttemptId) { return tasks.remove(executionAttemptId); } /** Removes all tasks from this task slot. */ public void clear() { tasks.clear(); } /** * Mark this slot as active. A slot can only be marked active if it's in state allocated. * * <p>The method returns true if the slot was set to active. Otherwise it returns false. * * @return True if the new state of the slot is active; otherwise false */ public boolean markActive() { if (TaskSlotState.ALLOCATED == state || TaskSlotState.ACTIVE == state) { state = TaskSlotState.ACTIVE; return true; } else { return false; } } /** * Mark the slot as inactive/allocated. A slot can only be marked as inactive/allocated if it's * in state allocated or active. * * @return True if the new state of the slot is allocated; otherwise false */ public boolean markInactive() { if (TaskSlotState.ACTIVE == state || TaskSlotState.ALLOCATED == state) { state = TaskSlotState.ALLOCATED; return true; } else { return false; } } /** * Generate the slot offer from this TaskSlot. * * @return The sot offer which this task slot can provide */ public SlotOffer generateSlotOffer() { Preconditions.checkState( TaskSlotState.ACTIVE == state || TaskSlotState.ALLOCATED == state, "The task slot is not in state active or allocated."); Preconditions.checkState(allocationId != null, "The task slot are not allocated"); return new SlotOffer(allocationId, index, resourceProfile); } @Override public String toString() { return "TaskSlot(index:" + index + ", state:" + state + ", resource profile: " + resourceProfile + ", allocationId: " + (allocationId != null ? allocationId.toString() : "none") + ", jobId: " + (jobId != null ? jobId.toString() : "none") + ')'; } @Override public CompletableFuture<Void> closeAsync() { return closeAsync(new FlinkException("Closing the slot")); } /** * Close the task slot asynchronously. * * <p>Slot is moved to {@link TaskSlotState#RELEASING} state and only once. If there are active * tasks running in the slot then they are failed. The future of all tasks terminated and slot * cleaned up is initiated only once and always returned in case of multiple attempts to close * the slot. * * @param cause cause of closing * @return future of all running task if any being done and slot cleaned up. */ CompletableFuture<Void> closeAsync(Throwable cause) { if (!isReleasing()) { state = TaskSlotState.RELEASING; if (!isEmpty()) { // we couldn't free the task slot because it still contains task, fail the tasks // and set the slot state to releasing so that it gets eventually freed tasks.values().forEach(task -> task.failExternally(cause)); } final CompletableFuture<Void> shutdownFuture = FutureUtils.waitForAll( tasks.values().stream() .map(TaskSlotPayload::getTerminationFuture) .collect(Collectors.toList())) .thenRun(memoryManager::shutdown); verifyAllManagedMemoryIsReleasedAfter(shutdownFuture); FutureUtils.forward(shutdownFuture, closingFuture); } return closingFuture; } private void verifyAllManagedMemoryIsReleasedAfter(CompletableFuture<Void> after) { after.thenRunAsync( () -> { if (!memoryManager.verifyEmpty()) { LOG.warn( "Not all slot managed memory is freed at {}. This usually indicates memory leak. " + "However, when running an old JVM version it can also be caused by slow garbage collection. " + "Try to upgrade to Java 8u72 or higher if running on an old Java version.", this); } }, asyncExecutor); } private static MemoryManager createMemoryManager( ResourceProfile resourceProfile, int pageSize) { return MemoryManager.create(resourceProfile.getManagedMemory().getBytes(), pageSize); } }
TaskSlot
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/headers/OptionalHeaderTest.java
{ "start": 2213, "end": 3196 }
class ____ { @Path("test") @GET public String test(@RestQuery String query, @RestHeader String header1, @RestHeader String header2, @RestHeader Integer header3) { StringBuilder result = new StringBuilder("query="); result.append(query); result.append("/"); if (header1 != null) { result.append("Header1"); result.append("="); result.append(header1); result.append(","); } if (header2 != null) { result.append("Header2"); result.append("="); result.append(header2); result.append(","); } if (header3 != null) { result.append("Header3"); result.append("="); result.append(header3); } return result.toString(); } } }
Resource
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ShouldHaveEvenArgsTest.java
{ "start": 6051, "end": 8470 }
class ____ { private static final Multimap<String, String> multimap = ImmutableMultimap.of(); public void testWithOddArgs() { // BUG: Diagnostic contains: even number of arguments assertThat(multimap).containsExactly("hello", "there", "rest"); // BUG: Diagnostic contains: even number of arguments assertThat(multimap).containsExactly("hello", "there", "hello", "there", "rest"); // BUG: Diagnostic contains: even number of arguments assertThat(multimap).containsExactly(null, null, null, null, new Object[] {}); } public void testWithArrayArgs() { String key = "hello"; Object[] value = new Object[] {}; Object[][] args = new Object[][] {}; // BUG: Diagnostic contains: even number of arguments assertThat(multimap).containsExactly(key, value, (Object) args); } public void testWithOddArgsWithCorrespondence() { assertThat(multimap) .comparingValuesUsing(Correspondence.from((a, b) -> true, "dummy")) // BUG: Diagnostic contains: even number of arguments .containsExactly("hello", "there", "rest"); assertThat(multimap) .comparingValuesUsing(Correspondence.from((a, b) -> true, "dummy")) // BUG: Diagnostic contains: even number of arguments .containsExactly("hello", "there", "hello", "there", "rest"); } }\ """) .doTest(); } @org.junit.Ignore("Public truth doesn't contain this method") @Test public void negativeCase_multimap() { compilationHelper .addSourceLines( "ShouldHaveEvenArgsMultimapNegativeCases.java", """ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; /** * Negative test cases for {@link ShouldHaveEvenArgs} check. * * @author monnoroch@google.com (Max Strakhov) */ public
ShouldHaveEvenArgsMultimapPositiveCases
java
elastic__elasticsearch
plugins/discovery-ec2/src/javaRestTest/java/org/elasticsearch/discovery/ec2/DiscoveryEc2EnvironmentVariableCredentialsIT.java
{ "start": 976, "end": 2548 }
class ____ extends DiscoveryEc2ClusterFormationTestCase { private static final String PREFIX = getIdentifierPrefix("DiscoveryEc2EnvironmentVariableCredentialsIT"); private static final String ACCESS_KEY = PREFIX + "-access-key"; private static final Supplier<String> regionSupplier = new DynamicRegionSupplier(); private static final AwsEc2HttpFixture ec2ApiFixture = new AwsEc2HttpFixture( fixedAccessKey(ACCESS_KEY, regionSupplier, "ec2"), DiscoveryEc2EnvironmentVariableCredentialsIT::getAvailableTransportEndpoints ); private static final ElasticsearchCluster cluster = ElasticsearchCluster.local() .nodes(2) .plugin("discovery-ec2") .setting(DiscoveryModule.DISCOVERY_SEED_PROVIDERS_SETTING.getKey(), Ec2DiscoveryPlugin.EC2_SEED_HOSTS_PROVIDER_NAME) .setting("logger." + AwsEc2SeedHostsProvider.class.getCanonicalName(), "DEBUG") .setting(Ec2ClientSettings.ENDPOINT_SETTING.getKey(), ec2ApiFixture::getAddress) .environment("AWS_REGION", regionSupplier) .environment("AWS_ACCESS_KEY_ID", ACCESS_KEY) .environment("AWS_SECRET_ACCESS_KEY", ESTestCase::randomSecretKey) .build(); private static List<String> getAvailableTransportEndpoints() { return cluster.getAvailableTransportEndpoints(); } @ClassRule public static TestRule ruleChain = RuleChain.outerRule(ec2ApiFixture).around(cluster); @Override protected ElasticsearchCluster getCluster() { return cluster; } }
DiscoveryEc2EnvironmentVariableCredentialsIT
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/SqlReturnType.java
{ "start": 1556, "end": 2550 }
interface ____ { /** * Constant that indicates an unknown (or unspecified) SQL type. * Passed into setTypeValue if the original operation method does * not specify an SQL type. * @see java.sql.Types * @see JdbcOperations#update(String, Object[]) */ int TYPE_UNKNOWN = Integer.MIN_VALUE; /** * Get the type value from the specific object. * @param cs the CallableStatement to operate on * @param paramIndex the index of the parameter for which we need to set the value * @param sqlType the SQL type of the parameter we are setting * @param typeName the type name of the parameter (optional) * @return the target value * @throws SQLException if an SQLException is encountered setting parameter values * (that is, there's no need to catch SQLException) * @see java.sql.Types * @see java.sql.CallableStatement#getObject */ Object getTypeValue(CallableStatement cs, int paramIndex, int sqlType, @Nullable String typeName) throws SQLException; }
SqlReturnType
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/JodaTimeConverterManagerTest.java
{ "start": 886, "end": 1248 }
class ____ { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(JodaTimeConverterManager.class, getClass()); @Test public void converterManager() { helper .addSourceLines( "Test.java", """ import org.joda.time.convert.ConverterManager;
JodaTimeConverterManagerTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/date/DateAssert_hasSameTimeAsOtherDate_Test.java
{ "start": 1287, "end": 2139 }
class ____ extends DateAssertBaseTest { @Test void should_verify_that_actual_has_time_equals_to_expected() { Date date = new Date(); Timestamp timestamp = new java.sql.Timestamp(date.getTime()); assertThat(date).hasSameTimeAs(timestamp); assertThat(timestamp).hasSameTimeAs(date); } @Test void should_fail_when_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat((Date) null).hasSameTimeAs(new Date())) .withMessage(actualIsNull()); } @Test void should_throw_exception_when_date_is_null() { assertThatNullPointerException().isThrownBy(() -> assertThat(new Date()).hasSameTimeAs((Date) null)) .withMessage(dateToCompareActualWithIsNull()); } }
DateAssert_hasSameTimeAsOtherDate_Test
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/OverTest.java
{ "start": 260, "end": 1568 }
class ____ extends TestCase { public void test_over() throws Exception { String sql = "SELECT SalesOrderID, ProductID, OrderQty" + " ,SUM(OrderQty) OVER(PARTITION BY SalesOrderID) AS 'Total'" + " ,AVG(OrderQty) OVER(PARTITION BY SalesOrderID) AS 'Avg'" + " ,COUNT(OrderQty) OVER(PARTITION BY SalesOrderID) AS 'Count'" + " ,MIN(OrderQty) OVER(PARTITION BY SalesOrderID) AS 'Min'" + " ,MAX(OrderQty) OVER(PARTITION BY SalesOrderID) AS 'Max' " + "FROM Sales.SalesOrderDetail " + "WHERE SalesOrderID IN(43659,43664);"; SQLStatementParser parser = new SQLStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); assertEquals(1, statementList.size()); SchemaStatVisitor visitor = new SchemaStatVisitor(); statemen.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); assertEquals(3, visitor.getColumns().size()); assertEquals(1, visitor.getTables().size()); } }
OverTest
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/cluster/api/sync/NodeSelectionJsonCommands.java
{ "start": 852, "end": 30646 }
interface ____<K, V> { /** * Append the JSON values into the array at a given {@link JsonPath} after the last element in a said array. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @param values one or more {@link JsonValue} to be appended. * @return Long the resulting size of the arrays after the new data was appended, or null if the path does not exist. * @since 6.5 */ Executions<List<Long>> jsonArrappend(K key, JsonPath jsonPath, JsonValue... values); /** * Append the JSON values into the array at the {@link JsonPath#ROOT_PATH} after the last element in a said array. * * @param key the key holding the JSON document. * @param values one or more {@link JsonValue} to be appended. * @return Long the resulting size of the arrays after the new data was appended, or null if the path does not exist. * @since 6.5 */ Executions<List<Long>> jsonArrappend(K key, JsonValue... values); /** * Append the JSON string values into the array at the {@link JsonPath#ROOT_PATH} after the last element in a said array. * * @param key the key holding the JSON document. * @param jsonStrings one or more JSON strings to be appended. * @return Long the resulting size of the arrays after the new data was appended, or null if the path does not exist. * @since 6.8 */ Executions<List<Long>> jsonArrappend(K key, String... jsonStrings); /** * Append the JSON string values into the array at a given {@link JsonPath} after the last element in a said array. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @param jsonStrings one or more JSON strings to be appended. * @return Long the resulting size of the arrays after the new data was appended, or null if the path does not exist. * @since 6.8 */ Executions<List<Long>> jsonArrappend(K key, JsonPath jsonPath, String... jsonStrings); /** * Search for the first occurrence of a {@link JsonValue} in an array at a given {@link JsonPath} and return its index. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @param value the {@link JsonValue} to search for. * @param range the {@link JsonRangeArgs} to search within. * @return Long the index hosting the searched element, -1 if not found or null if the specified path is not an array. * @since 6.5 */ Executions<List<Long>> jsonArrindex(K key, JsonPath jsonPath, JsonValue value, JsonRangeArgs range); /** * Search for the first occurrence of a {@link JsonValue} in an array at a given {@link JsonPath} and return its index. This * method uses defaults for the start and end indexes, see {@link JsonRangeArgs#DEFAULT_START_INDEX} and * {@link JsonRangeArgs#DEFAULT_END_INDEX}. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @param value the {@link JsonValue} to search for. * @return Long the index hosting the searched element, -1 if not found or null if the specified path is not an array. * @since 6.5 */ Executions<List<Long>> jsonArrindex(K key, JsonPath jsonPath, JsonValue value); /** * Search for the first occurrence of a JSON string in an array at a given {@link JsonPath} and return its index. This * method uses defaults for the start and end indexes, see {@link JsonRangeArgs#DEFAULT_START_INDEX} and * {@link JsonRangeArgs#DEFAULT_END_INDEX}. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @param jsonString the JSON string to search for. * @return Long the index hosting the searched element, -1 if not found or null if the specified path is not an array. * @since 6.8 */ Executions<List<Long>> jsonArrindex(K key, JsonPath jsonPath, String jsonString); /** * Search for the first occurrence of a JSON string in an array at a given {@link JsonPath} and return its index. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @param jsonString the JSON string to search for. * @param range the {@link JsonRangeArgs} to search within. * @return Long the index hosting the searched element, -1 if not found or null if the specified path is not an array. * @since 6.8 */ Executions<List<Long>> jsonArrindex(K key, JsonPath jsonPath, String jsonString, JsonRangeArgs range); /** * Insert the {@link JsonValue}s into the array at a given {@link JsonPath} before the provided index, shifting the existing * elements to the right * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @param index the index before which the new elements will be inserted. * @param values one or more {@link JsonValue}s to be inserted. * @return Long the resulting size of the arrays after the new data was inserted, or null if the path does not exist. * @since 6.5 */ Executions<List<Long>> jsonArrinsert(K key, JsonPath jsonPath, int index, JsonValue... values); /** * Insert the JSON string values into the array at a given {@link JsonPath} before the provided index. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @param index the index before which the new elements will be inserted. * @param jsonStrings one or more JSON strings to be inserted. * @return Long the resulting size of the arrays after the new data was inserted, or null if the path does not exist. * @since 6.8 */ Executions<List<Long>> jsonArrinsert(K key, JsonPath jsonPath, int index, String... jsonStrings); /** * Report the length of the JSON array at a given {@link JsonPath} * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @return the size of the arrays, or null if the path does not exist. * @since 6.5 */ Executions<List<Long>> jsonArrlen(K key, JsonPath jsonPath); /** * Report the length of the JSON array at a the {@link JsonPath#ROOT_PATH} * * @param key the key holding the JSON document. * @return the size of the arrays, or null if the path does not exist. * @since 6.5 */ Executions<List<Long>> jsonArrlen(K key); /** * Remove and return {@link JsonValue} at a given index in the array at a given {@link JsonPath} * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @param index the index of the element to be removed. Default is -1, meaning the last element. Out-of-range indexes round * to their respective array ends. Popping an empty array returns null. * @return List<JsonValue> the removed element, or null if the specified path is not an array. * @since 6.5 */ Executions<List<JsonValue>> jsonArrpop(K key, JsonPath jsonPath, int index); /** * Remove and return the JSON value at a given index in the array at a given {@link JsonPath} as raw JSON strings. * <p> * Behaves like {@link #jsonArrpop(Object, JsonPath, int)} but returns {@code List<String>} with raw JSON instead of * {@link JsonValue} wrappers. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @param index the index of the element to be removed. Default is -1, meaning the last element. Out-of-range indexes round * to their respective array ends. Popping an empty array returns null. * @return List<String> the removed element, or null if the specified path is not an array. * @since 7.0 */ Executions<List<String>> jsonArrpopRaw(K key, JsonPath jsonPath, int index); /** * Remove and return {@link JsonValue} at index -1 (last element) in the array at a given {@link JsonPath} * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @return List<JsonValue> the removed element, or null if the specified path is not an array. * @since 6.5 */ Executions<List<JsonValue>> jsonArrpop(K key, JsonPath jsonPath); /** * Remove and return the JSON value at index -1 (last element) in the array at a given {@link JsonPath} as raw JSON strings. * <p> * Behaves like {@link #jsonArrpop(Object, JsonPath)} but returns {@code List<String>} with raw JSON instead of * {@link JsonValue} wrappers. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @return List<String> the removed element, or null if the specified path is not an array. * @since 7.0 */ Executions<List<String>> jsonArrpopRaw(K key, JsonPath jsonPath); /** * Remove and return {@link JsonValue} at index -1 (last element) in the array at the {@link JsonPath#ROOT_PATH} * * @param key the key holding the JSON document. * @return List<JsonValue> the removed element, or null if the specified path is not an array. * @since 6.5 */ Executions<List<JsonValue>> jsonArrpop(K key); /** * Remove and return the JSON value at index -1 (last element) in the array at the {@link JsonPath#ROOT_PATH} as raw JSON * strings. * <p> * Behaves like {@link #jsonArrpop(Object)} but returns {@code List<String>} with raw JSON instead of {@link JsonValue} * wrappers. * * @param key the key holding the JSON document. * @return List<String> the removed element, or null if the specified path is not an array. * @since 7.0 */ Executions<List<String>> jsonArrpopRaw(K key); /** * Trim an array at a given {@link JsonPath} so that it contains only the specified inclusive range of elements. All * elements with indexes smaller than the start range and all elements with indexes bigger than the end range are trimmed. * <p> * Behavior as of RedisJSON v2.0: * <ul> * <li>If start is larger than the array's size or start > stop, returns 0 and an empty array.</li> * <li>If start is < 0, then start from the end of the array.</li> * <li>If stop is larger than the end of the array, it is treated like the last element.</li> * </ul> * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the array inside the document. * @param range the {@link JsonRangeArgs} to trim by. * @return Long the resulting size of the arrays after the trimming, or null if the path does not exist. * @since 6.5 */ Executions<List<Long>> jsonArrtrim(K key, JsonPath jsonPath, JsonRangeArgs range); /** * Clear container values (arrays/objects) and set numeric values to 0 * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value to clear. * @return Long the number of values removed plus all the matching JSON numerical values that are zeroed. * @since 6.5 */ Executions<Long> jsonClear(K key, JsonPath jsonPath); /** * Clear container values (arrays/objects) and set numeric values to 0 at the {@link JsonPath#ROOT_PATH} * * @param key the key holding the JSON document. * @return Long the number of values removed plus all the matching JSON numerical values that are zeroed. * @since 6.5 */ Executions<Long> jsonClear(K key); /** * Deletes a value inside the JSON document at a given {@link JsonPath} * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value to clear. * @return Long the number of values removed (0 or more). * @since 6.5 */ Executions<Long> jsonDel(K key, JsonPath jsonPath); /** * Deletes a value inside the JSON document at the {@link JsonPath#ROOT_PATH} * * @param key the key holding the JSON document. * @return Long the number of values removed (0 or more). * @since 6.5 */ Executions<Long> jsonDel(K key); /** * Return the value at the specified path in JSON serialized form. * <p> * When using a single JSONPath, the root of the matching values is a JSON string with a top-level array of serialized JSON * value. In contrast, a legacy path returns a single value. * <p> * When using multiple JSONPath arguments, the root of the matching values is a JSON string with a top-level object, with * each object value being a top-level array of serialized JSON value. In contrast, if all paths are legacy paths, each * object value is a single serialized JSON value. If there are multiple paths that include both legacy path and JSONPath, * the returned value conforms to the JSONPath version (an array of values). * * @param key the key holding the JSON document. * @param options the {@link JsonGetArgs} to use. * @param jsonPaths the {@link JsonPath}s to use to identify the values to get. * @return JsonValue the value at path in JSON serialized form, or null if the path does not exist. * @since 6.5 */ Executions<List<JsonValue>> jsonGet(K key, JsonGetArgs options, JsonPath... jsonPaths); /** * Return the value at the specified path in JSON serialized form as raw strings. * <p> * Behaves like {@link #jsonGet(Object, JsonGetArgs, JsonPath...)} but returns {@code List<String>} with raw JSON instead of * {@link JsonValue} wrappers. * * @param key the key holding the JSON document. * @param options the {@link JsonGetArgs} to use. * @param jsonPaths the {@link JsonPath}s to use to identify the values to get. * @return List<String> the value at path in JSON serialized form, or null if the path does not exist. * @since 7.0 */ Executions<List<String>> jsonGetRaw(K key, JsonGetArgs options, JsonPath... jsonPaths); /** * Return the value at the specified path in JSON serialized form. Uses defaults for the {@link JsonGetArgs}. * <p> * When using a single JSONPath, the root of the matching values is a JSON string with a top-level array of serialized JSON * value. In contrast, a legacy path returns a single value. * <p> * When using multiple JSONPath arguments, the root of the matching values is a JSON string with a top-level object, with * each object value being a top-level array of serialized JSON value. In contrast, if all paths are legacy paths, each * object value is a single serialized JSON value. If there are multiple paths that include both legacy path and JSONPath, * the returned value conforms to the JSONPath version (an array of values). * * @param key the key holding the JSON document. * @param jsonPaths the {@link JsonPath}s to use to identify the values to get. * @return JsonValue the value at path in JSON serialized form, or null if the path does not exist. * @since 6.5 */ Executions<List<JsonValue>> jsonGet(K key, JsonPath... jsonPaths); /** * Return the value at the specified path in JSON serialized form as raw strings. Uses defaults for the {@link JsonGetArgs}. * <p> * Behaves like {@link #jsonGet(Object, JsonPath...)} but returns {@code List<String>} with raw JSON instead of * {@link JsonValue} wrappers. * * @param key the key holding the JSON document. * @param jsonPaths the {@link JsonPath}s to use to identify the values to get. * @return List<String> the value at path in JSON serialized form, or null if the path does not exist. * @since 7.0 */ Executions<List<String>> jsonGetRaw(K key, JsonPath... jsonPaths); /** * Merge a given {@link JsonValue} with the value matching {@link JsonPath}. Consequently, JSON values at matching paths are * updated, deleted, or expanded with new children. * <p> * Merging is done according to the following rules per JSON value in the value argument while considering the corresponding * original value if it exists: * <ul> * <li>merging an existing object key with a null value deletes the key</li> * <li>merging an existing object key with non-null value updates the value</li> * <li>merging a non-existing object key adds the key and value</li> * <li>merging an existing array with any merged value, replaces the entire array with the value</li> * </ul> * <p> * This command complies with RFC7396 "Json Merge Patch" * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value to merge. * @param value the {@link JsonValue} to merge. * @return String "OK" if the set was successful, error if the operation failed. * @since 6.5 * @see <A href="https://tools.ietf.org/html/rfc7396">RFC7396</a> */ Executions<String> jsonMerge(K key, JsonPath jsonPath, JsonValue value); /** * Merge a given JSON string with the value matching {@link JsonPath}. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value to merge. * @param jsonString the JSON string to merge. * @return String "OK" if the merge was successful, error if the operation failed. * @since 6.8 */ Executions<String> jsonMerge(K key, JsonPath jsonPath, String jsonString); /** * Return the values at the specified path from multiple key arguments. * * @param jsonPath the {@link JsonPath} pointing to the value to fetch. * @param keys the keys holding the {@link JsonValue}s to fetch. * @return List<JsonValue> the values at path, or null if the path does not exist. * @since 6.5 */ Executions<List<JsonValue>> jsonMGet(JsonPath jsonPath, K... keys); /** * Return the values at the specified path from multiple key arguments as raw JSON strings. * <p> * Behaves like {@link #jsonMGet(JsonPath, Object[])} but returns {@code List<String>} with raw JSON instead of * {@link JsonValue} wrappers. * * @param jsonPath the {@link JsonPath} pointing to the value to fetch. * @param keys the keys holding the values to fetch. * @return List<String> the values at path, or null if the path does not exist. * @since 7.0 */ Executions<List<String>> jsonMGetRaw(JsonPath jsonPath, K... keys); /** * Set or update one or more JSON values according to the specified {@link JsonMsetArgs} * <p> * JSON.MSET is atomic, hence, all given additions or updates are either applied or not. It is not possible for clients to * see that some keys were updated while others are unchanged. * <p> * A JSON value is a hierarchical structure. If you change a value in a specific path - nested values are affected. * * @param arguments the {@link JsonMsetArgs} specifying the values to change. * @return "OK" if the operation was successful, error otherwise * @since 6.5 */ Executions<String> jsonMSet(List<JsonMsetArgs<K, V>> arguments); /** * Increment the number value stored at the specified {@link JsonPath} in the JSON document by the provided increment. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value to increment. * @param number the increment value. * @return a {@link List} of the new values after the increment. * @since 6.5 */ Executions<List<Number>> jsonNumincrby(K key, JsonPath jsonPath, Number number); /** * Return the keys in the JSON document that are referenced by the given {@link JsonPath} * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value(s) whose key(s) we want. * @return List<V> the keys in the JSON document that are referenced by the given {@link JsonPath}. * @since 6.5 */ Executions<List<V>> jsonObjkeys(K key, JsonPath jsonPath); /** * Return the keys in the JSON document that are referenced by the {@link JsonPath#ROOT_PATH} * * @param key the key holding the JSON document. * @return List<V> the keys in the JSON document that are referenced by the given {@link JsonPath}. * @since 6.5 */ Executions<List<V>> jsonObjkeys(K key); /** * Report the number of keys in the JSON object at the specified {@link JsonPath} and for the provided key * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value(s) whose key(s) we want to count * @return Long the number of keys in the JSON object at the specified path, or null if the path does not exist. * @since 6.5 */ Executions<List<Long>> jsonObjlen(K key, JsonPath jsonPath); /** * Report the number of keys in the JSON object at the {@link JsonPath#ROOT_PATH} and for the provided key * * @param key the key holding the JSON document. * @return Long the number of keys in the JSON object at the specified path, or null if the path does not exist. * @since 6.5 */ Executions<List<Long>> jsonObjlen(K key); /** * Sets the JSON value at a given {@link JsonPath} in the JSON document. * <p> * For new Redis keys, the path must be the root. For existing keys, when the entire path exists, the value that it contains * is replaced with the JSON value. For existing keys, when the path exists, except for the last element, a new child is * added with the JSON value. * <p> * Adds a key (with its respective value) to a JSON Object (in a RedisJSON data type key) only if it is the last child in * the path, or it is the parent of a new child being added in the path. Optional arguments NX and XX modify this behavior * for both new RedisJSON data type keys and the JSON Object keys in them. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to set the value. * @param value the {@link JsonValue} to set. * @param options the {@link JsonSetArgs} the options for setting the value. * @return String "OK" if the set was successful, null if the {@link JsonSetArgs} conditions are not met. * @since 6.5 */ Executions<String> jsonSet(K key, JsonPath jsonPath, JsonValue value, JsonSetArgs options); /** * Sets the JSON value at a given {@link JsonPath} in the JSON document using defaults for the {@link JsonSetArgs}. * <p> * For new Redis keys the path must be the root. For existing keys, when the entire path exists, the value that it contains * is replaced with the JSON value. For existing keys, when the path exists, except for the last element, a new child is * added with the JSON value. * <p> * Adds a key (with its respective value) to a JSON Object (in a RedisJSON data type key) only if it is the last child in * the path, or it is the parent of a new child being added in the path. Optional arguments NX and XX modify this behavior * for both new RedisJSON data type keys and the JSON Object keys in them. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to set the value. * @param value the {@link JsonValue} to set. * @return String "OK" if the set was successful, null if the {@link JsonSetArgs} conditions are not met. * @since 6.5 */ Executions<String> jsonSet(K key, JsonPath jsonPath, JsonValue value); /** * Sets the JSON value at a given {@link JsonPath} in the JSON document using defaults for the {@link JsonSetArgs}. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to set the value. * @param jsonString the JSON string to set. * @return String "OK" if the set was successful, null if the {@link JsonSetArgs} conditions are not met. * @since 6.8 */ Executions<String> jsonSet(K key, JsonPath jsonPath, String jsonString); /** * Sets the JSON value at a given {@link JsonPath} in the JSON document. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to set the value. * @param jsonString the JSON string to set. * @param options the {@link JsonSetArgs} the options for setting the value. * @return String "OK" if the set was successful, null if the {@link JsonSetArgs} conditions are not met. * @since 6.8 */ Executions<String> jsonSet(K key, JsonPath jsonPath, String jsonString, JsonSetArgs options); /** * Append the json-string values to the string at the provided {@link JsonPath} in the JSON document. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to append the value. * @param value the {@link JsonValue} to append. * @return Long the new length of the string, or null if the matching JSON value is not a string. * @since 6.5 */ Executions<List<Long>> jsonStrappend(K key, JsonPath jsonPath, JsonValue value); /** * Append the json-string values to the string at the {@link JsonPath#ROOT_PATH} in the JSON document. * * @param key the key holding the JSON document. * @param value the {@link JsonValue} to append. * @return Long the new length of the string, or null if the matching JSON value is not a string. * @since 6.5 */ Executions<List<Long>> jsonStrappend(K key, JsonValue value); /** * Append the JSON string to the string at the {@link JsonPath#ROOT_PATH} in the JSON document. * * @param key the key holding the JSON document. * @param jsonString the JSON string to append. * @return Long the new length of the string, or null if the matching JSON value is not a string. * @since 6.8 */ Executions<List<Long>> jsonStrappend(K key, String jsonString); /** * Append the JSON string to the string at the provided {@link JsonPath} in the JSON document. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to append the value. * @param jsonString the JSON string to append. * @return Long the new length of the string, or null if the matching JSON value is not a string. * @since 6.8 */ Executions<List<Long>> jsonStrappend(K key, JsonPath jsonPath, String jsonString); /** * Report the length of the JSON String at the provided {@link JsonPath} in the JSON document. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value(s). * @return Long (in recursive descent) the length of the JSON String at the provided {@link JsonPath}, or null if the value * ath the desired path is not a string. * @since 6.5 */ Executions<List<Long>> jsonStrlen(K key, JsonPath jsonPath); /** * Report the length of the JSON String at the {@link JsonPath#ROOT_PATH} in the JSON document. * * @param key the key holding the JSON document. * @return Long (in recursive descent) the length of the JSON String at the provided {@link JsonPath}, or null if the value * ath the desired path is not a string. * @since 6.5 */ Executions<List<Long>> jsonStrlen(K key); /** * Toggle a Boolean value stored at the provided {@link JsonPath} in the JSON document. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value(s). * @return List<Long> the new value after the toggle, 0 for false, 1 for true or null if the path does not exist. * @since 6.5 */ Executions<List<Long>> jsonToggle(K key, JsonPath jsonPath); /** * Report the type of JSON value at the provided {@link JsonPath} in the JSON document. * * @param key the key holding the JSON document. * @param jsonPath the {@link JsonPath} pointing to the value(s). * @return List<JsonType> the type of JSON value at the provided {@link JsonPath} * @since 6.5 */ Executions<List<JsonType>> jsonType(K key, JsonPath jsonPath); /** * Report the type of JSON value at the {@link JsonPath#ROOT_PATH} in the JSON document. * * @param key the key holding the JSON document. * @return List<JsonType> the type of JSON value at the provided {@link JsonPath} * @since 6.5 */ Executions<List<JsonType>> jsonType(K key); }
NodeSelectionJsonCommands
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/FSOperations.java
{ "start": 50454, "end": 51038 }
class ____ implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; private String policyName; public FSSetStoragePolicy(String path, String policyName) { this.path = new Path(path); this.policyName = policyName; } @Override public Void execute(FileSystem fs) throws IOException { fs.setStoragePolicy(path, policyName); return null; } } /** * Executor that performs a unsetStoragePolicy FileSystemAccess files system * operation. */ @InterfaceAudience.Private public static
FSSetStoragePolicy
java
resilience4j__resilience4j
resilience4j-hedge/src/test/java/io/github/resilience4j/hedge/HedgeTest.java
{ "start": 803, "end": 1821 }
class ____ { private static final String TEST_HEDGE = "TEST_HEDGE"; @Test public void shouldInitializeOfDefaults() { Hedge hedge = Hedge.ofDefaults(); then(hedge.getHedgeConfig().toString()).isEqualTo(HedgeConfig.ofDefaults().toString()); then(hedge.getName()).isEqualTo(HedgeImpl.DEFAULT_NAME); } @Test public void shouldInitializeOfName() { Hedge hedge = Hedge.ofDefaults(TEST_HEDGE); then(hedge.getHedgeConfig().toString()).isEqualTo(HedgeConfig.ofDefaults().toString()); then(hedge.getName()).isEqualTo(TEST_HEDGE); } @Test public void shouldInitializeOfNameAndDefaults() { Hedge hedge = Hedge.of(TEST_HEDGE, HedgeConfig.ofDefaults()); then(hedge.getName()).isEqualTo(TEST_HEDGE); } @Test public void shouldInitializeConfig() { HedgeConfig config = HedgeConfig.ofDefaults(); Hedge hedge = Hedge.of(config); then(hedge.getHedgeConfig()).isEqualTo(config); } }
HedgeTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/id/uuid/annotation/TheOtherEntity.java
{ "start": 468, "end": 858 }
class ____ { @Id @GeneratedValue public Long pk; @UuidGenerator public UUID id; @Basic public String name; private TheOtherEntity() { // for Hibernate use } public TheOtherEntity(String name) { this.name = name; } public UUID getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
TheOtherEntity
java
elastic__elasticsearch
x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/transforms/scheduling/TransformScheduler.java
{ "start": 1908, "end": 2003 }
interface ____ receiving events about the scheduled task being triggered. */ public
allows
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java
{ "start": 14148, "end": 14297 }
class ____ { } @SpringBootTest(properties = { "key=myValue", "variables=foo=FOO\n bar=BAR" }, classes = Config.class) static
AnotherSeparatorInValue
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/assumptions/BDDAssumptionsTest.java
{ "start": 24248, "end": 24661 }
class ____ { private final OptionalLong actual = OptionalLong.empty(); @Test void should_run_test_when_assumption_passes() { thenCode(() -> given(actual).isEmpty()).doesNotThrowAnyException(); } @Test void should_ignore_test_when_assumption_fails() { expectAssumptionNotMetException(() -> given(actual).isNotEmpty()); } } @Nested
BDDAssumptions_given_OptionalLong_Test
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DeprecatedVariableTest.java
{ "start": 1975, "end": 2140 }
class ____ { void f() { if (toString() instanceof String s) {} } } """) .doTest(); } }
Test
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/NestedTestConfiguration.java
{ "start": 2584, "end": 5557 }
class ____. Thus, * there is no need to redeclare the annotation unless you wish to switch the * mode. * * <p>This annotation may be used as a <em>meta-annotation</em> to create custom * <em>composed annotations</em>. * * <p>The use of this annotation typically only makes sense in conjunction with * {@link org.junit.jupiter.api.Nested @Nested} test classes in JUnit Jupiter; * however, there may be other testing frameworks with support for nested test * classes that could also make use of this annotation. * * <p>If you are developing a component that integrates with the Spring TestContext * Framework and needs to support annotation inheritance within enclosing class * hierarchies, you must use the annotation search utilities provided in * {@link TestContextAnnotationUtils} in order to honor * {@code @NestedTestConfiguration} semantics. * * <h3>Supported Annotations</h3> * <p>The <em>Spring TestContext Framework</em> honors {@code @NestedTestConfiguration} * semantics for the following annotations. * <ul> * <li>{@link BootstrapWith @BootstrapWith}</li> * <li>{@link TestExecutionListeners @TestExecutionListeners}</li> * <li>{@link ContextCustomizerFactories @ContextCustomizerFactories}</li> * <li>{@link ContextConfiguration @ContextConfiguration}</li> * <li>{@link ContextHierarchy @ContextHierarchy}</li> * <li>{@link org.springframework.test.context.web.WebAppConfiguration @WebAppConfiguration}</li> * <li>{@link ActiveProfiles @ActiveProfiles}</li> * <li>{@link TestPropertySource @TestPropertySource}</li> * <li>{@link DynamicPropertySource @DynamicPropertySource}</li> * <li>{@link org.springframework.test.context.bean.override.convention.TestBean @TestBean}</li> * <li>{@link org.springframework.test.context.bean.override.mockito.MockitoBean @MockitoBean}</li> * <li>{@link org.springframework.test.context.bean.override.mockito.MockitoSpyBean @MockitoSpyBean}</li> * <li>{@link org.springframework.test.annotation.DirtiesContext @DirtiesContext}</li> * <li>{@link org.springframework.transaction.annotation.Transactional @Transactional}</li> * <li>{@link org.springframework.test.annotation.Rollback @Rollback}</li> * <li>{@link org.springframework.test.annotation.Commit @Commit}</li> * <li>{@link org.springframework.test.context.jdbc.Sql @Sql}</li> * <li>{@link org.springframework.test.context.jdbc.SqlConfig @SqlConfig}</li> * <li>{@link org.springframework.test.context.jdbc.SqlMergeMode @SqlMergeMode}</li> * <li>{@link TestConstructor @TestConstructor}</li> * </ul> * * <p>Note that {@code @NestedTestConfiguration} does not apply to * {@link org.springframework.test.context.junit.jupiter.SpringExtensionConfig @SpringExtensionConfig}. * * @author Sam Brannen * @since 5.3 * @see EnclosingConfiguration#INHERIT * @see EnclosingConfiguration#OVERRIDE * @see TestContextAnnotationUtils */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @
hierarchy
java
quarkusio__quarkus
integration-tests/jackson/src/test/java/io/quarkus/it/jackson/RegisteredPojoModelResourceIT.java
{ "start": 117, "end": 248 }
class ____ extends RegisteredPojoModelResourceTest { // Execute the same tests but in native mode. }
RegisteredPojoModelResourceIT
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/script/ScriptTermStatsTests.java
{ "start": 1539, "end": 14482 }
class ____ extends ESTestCase { public void testMatchedTermsCount() throws IOException { // Returns number of matched terms for each doc. assertAllDocs( Set.of(new Term("field", "foo"), new Term("field", "bar")), ScriptTermStats::matchedTermsCount, Map.of("doc-1", equalTo(2), "doc-2", equalTo(2), "doc-3", equalTo(1)) ); // Partial match assertAllDocs( Set.of(new Term("field", "foo"), new Term("field", "qux"), new Term("field", "baz")), ScriptTermStats::matchedTermsCount, Map.of("doc-1", equalTo(2), "doc-2", equalTo(1), "doc-3", equalTo(0)) ); // Always returns 0 when no term is provided. assertAllDocs( Set.of(), ScriptTermStats::matchedTermsCount, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(0))) ); // Always Returns 0 when none of the provided term has a match. assertAllDocs( randomTerms(), ScriptTermStats::matchedTermsCount, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(0))) ); // Always returns 0 when using a non-existing field assertAllDocs( Set.of(new Term("field-that-does-not-exists", "foo"), new Term("field-that-does-not-exists", "bar")), ScriptTermStats::matchedTermsCount, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(0))) ); } public void testDocFreq() throws IOException { // Single term { StatsSummary expected = new StatsSummary(1, 2, 2, 2); assertAllDocs( Set.of(new Term("field", "foo")), ScriptTermStats::docFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } // Multiple terms { StatsSummary expected = new StatsSummary(2, 5, 2, 3); assertAllDocs( Set.of(new Term("field", "foo"), new Term("field", "bar")), ScriptTermStats::docFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } // With missing terms { StatsSummary expected = new StatsSummary(2, 2, 0, 2); assertAllDocs( Set.of(new Term("field", "foo"), new Term("field", "baz")), ScriptTermStats::docFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } // When no term is provided. { StatsSummary expected = new StatsSummary(); assertAllDocs( Set.of(), ScriptTermStats::docFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } // When using a non-existing field { StatsSummary expected = new StatsSummary(2, 0, 0, 0); assertAllDocs( Set.of(new Term("non-existing-field", "foo"), new Term("non-existing-field", "baz")), ScriptTermStats::docFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } } public void testTotalTermFreq() throws IOException { // Single term { StatsSummary expected = new StatsSummary(1, 3, 3, 3); assertAllDocs( Set.of(new Term("field", "foo")), ScriptTermStats::totalTermFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } // Multiple terms { StatsSummary expected = new StatsSummary(2, 6, 3, 3); assertAllDocs( Set.of(new Term("field", "foo"), new Term("field", "bar")), ScriptTermStats::totalTermFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } // With missing terms { StatsSummary expected = new StatsSummary(2, 3, 0, 3); assertAllDocs( Set.of(new Term("field", "foo"), new Term("field", "baz")), ScriptTermStats::totalTermFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } // When no term is provided. { StatsSummary expected = new StatsSummary(); assertAllDocs( Set.of(), ScriptTermStats::totalTermFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } // When using a non-existing field { StatsSummary expected = new StatsSummary(2, 0, 0, 0); assertAllDocs( Set.of(new Term("non-existing-field", "foo"), new Term("non-existing-field", "baz")), ScriptTermStats::totalTermFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } } public void testTermFreq() throws IOException { // Single term { assertAllDocs( Set.of(new Term("field", "foo")), ScriptTermStats::termFreq, Map.ofEntries( Map.entry("doc-1", equalTo(new StatsSummary(1, 1, 1, 1))), Map.entry("doc-2", equalTo(new StatsSummary(1, 2, 2, 2))), Map.entry("doc-3", equalTo(new StatsSummary(1, 0, 0, 0))) ) ); } // Multiple terms { StatsSummary expected = new StatsSummary(2, 6, 3, 3); assertAllDocs( Set.of(new Term("field", "foo"), new Term("field", "bar")), ScriptTermStats::termFreq, Map.ofEntries( Map.entry("doc-1", equalTo(new StatsSummary(2, 2, 1, 1))), Map.entry("doc-2", equalTo(new StatsSummary(2, 3, 1, 2))), Map.entry("doc-3", equalTo(new StatsSummary(2, 1, 0, 1))) ) ); } // With missing terms { assertAllDocs( Set.of(new Term("field", "foo"), new Term("field", "qux"), new Term("field", "baz")), ScriptTermStats::termFreq, Map.ofEntries( Map.entry("doc-1", equalTo(new StatsSummary(3, 2, 0, 1))), Map.entry("doc-2", equalTo(new StatsSummary(3, 2, 0, 2))), Map.entry("doc-3", equalTo(new StatsSummary(3, 0, 0, 0))) ) ); } // When no term is provided. { StatsSummary expected = new StatsSummary(); assertAllDocs( Set.of(), ScriptTermStats::termFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } // When using a non-existing field { StatsSummary expected = new StatsSummary(2, 0, 0, 0); assertAllDocs( Set.of(new Term("non-existing-field", "foo"), new Term("non-existing-field", "baz")), ScriptTermStats::termFreq, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } } public void testTermPositions() throws IOException { // Single term { assertAllDocs( Set.of(new Term("field", "foo")), ScriptTermStats::termPositions, Map.ofEntries( Map.entry("doc-1", equalTo(new StatsSummary(1, 1, 1, 1))), Map.entry("doc-2", equalTo(new StatsSummary(2, 3, 1, 2))), Map.entry("doc-3", equalTo(new StatsSummary())) ) ); } // Multiple terms { StatsSummary expected = new StatsSummary(2, 6, 3, 3); assertAllDocs( Set.of(new Term("field", "foo"), new Term("field", "bar")), ScriptTermStats::termPositions, Map.ofEntries( Map.entry("doc-1", equalTo(new StatsSummary(2, 3, 1, 2))), Map.entry("doc-2", equalTo(new StatsSummary(3, 6, 1, 3))), Map.entry("doc-3", equalTo(new StatsSummary(1, 1, 1, 1))) ) ); } // With missing terms { assertAllDocs( Set.of(new Term("field", "foo"), new Term("field", "qux"), new Term("field", "baz")), ScriptTermStats::termPositions, Map.ofEntries( Map.entry("doc-1", equalTo(new StatsSummary(2, 4, 1, 3))), Map.entry("doc-2", equalTo(new StatsSummary(2, 3, 1, 2))), Map.entry("doc-3", equalTo(new StatsSummary())) ) ); } // When no term is provided. { StatsSummary expected = new StatsSummary(); assertAllDocs( Set.of(), ScriptTermStats::termPositions, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } // When using a non-existing field { StatsSummary expected = new StatsSummary(); assertAllDocs( Set.of(new Term("non-existing-field", "foo"), new Term("non-existing-field", "bar")), ScriptTermStats::termPositions, Stream.of("doc-1", "doc-2", "doc-3").collect(Collectors.toMap(Function.identity(), k -> equalTo(expected))) ); } } private void withIndexSearcher(CheckedConsumer<IndexSearcher, IOException> consummer) throws IOException { try (Directory dir = new ByteBuffersDirectory()) { IndexWriter w = new IndexWriter(dir, newIndexWriterConfig()); Document doc = new Document(); doc.add(new TextField("id", "doc-1", Field.Store.YES)); doc.add(new TextField("field", "foo bar qux", Field.Store.YES)); w.addDocument(doc); doc = new Document(); doc.add(new TextField("id", "doc-2", Field.Store.YES)); doc.add(new TextField("field", "foo foo bar", Field.Store.YES)); w.addDocument(doc); doc = new Document(); doc.add(new TextField("id", "doc-3", Field.Store.YES)); doc.add(new TextField("field", "bar", Field.Store.YES)); w.addDocument(doc); try (IndexReader r = DirectoryReader.open(w)) { w.close(); consummer.accept(newSearcher(r)); } } } private <T> void assertAllDocs(Set<Term> terms, Function<ScriptTermStats, T> function, Map<String, Matcher<T>> expectedValues) throws IOException { withIndexSearcher(searcher -> { for (LeafReaderContext leafReaderContext : searcher.getLeafContexts()) { IndexReader reader = leafReaderContext.reader(); StoredFields storedFields = reader.storedFields(); DocIdSetIterator docIdSetIterator = DocIdSetIterator.all(reader.maxDoc()); ScriptTermStats termStats = new ScriptTermStats(searcher, leafReaderContext, docIdSetIterator::docID, terms); while (docIdSetIterator.nextDoc() <= reader.maxDoc()) { String docId = storedFields.document(docIdSetIterator.docID()).get("id"); if (expectedValues.containsKey(docId)) { assertThat(function.apply(termStats), expectedValues.get(docId)); } } } }); } private Set<Term> randomTerms() { Predicate<Term> isReservedTerm = term -> List.of("foo", "bar").contains(term.text()); Supplier<Term> termSupplier = () -> randomValueOtherThanMany( isReservedTerm, () -> new Term("field", randomAlphaOfLengthBetween(1, 5)) ); return randomSet(1, randomIntBetween(1, 10), termSupplier); } }
ScriptTermStatsTests
java
apache__camel
components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/integration/MongoDbFindOneAndUpdateOperationIT.java
{ "start": 2380, "end": 10374 }
class ____ extends AbstractMongoDbITSupport implements ConfigurableRoute { @EndpointInject("mock:test") private MockEndpoint mock; @Test public void testNoMatch() throws InterruptedException { mock.expectedMessageCount(1); mock.expectedBodyReceived().constant(null); Bson filter = eq("extraField", true); Bson update = combine(set("scientist", "Darwin"), currentTimestamp("lastModified")); final Map<String, Object> headers = new HashMap<>(); headers.put(CRITERIA, filter); template.sendBodyAndHeaders("direct:findOneAndUpdate", update, headers); mock.assertIsSatisfied(); assertEquals(0, testCollection.countDocuments(), "Upsert was set to false, no new document should have been created."); } @Test public void testInsertOnUpdate() throws InterruptedException { mock.expectedMessageCount(1); mock.expectedBodyReceived().constant(null); Bson filter = eq("extraField", true); Bson update = combine(set("scientist", "Darwin"), currentTimestamp("lastModified")); final Map<String, Object> headers = new HashMap<>(); headers.put(CRITERIA, filter); // insert document if not found headers.put(UPSERT, true); template.sendBodyAndHeaders("direct:findOneAndUpdate", update, headers); mock.assertIsSatisfied(); assertEquals(1, testCollection.countDocuments(new Document("scientist", "Darwin")), "Upsert was set to true, a new document should have been created."); } @Test public void testInsertOnUpdateBodyParams() throws InterruptedException { mock.expectedMessageCount(1); mock.expectedBodyReceived().constant(null); Bson filter = eq("extraField", true); Bson update = combine(set("scientist", "Darwin"), currentTimestamp("lastModified")); // Sends the filter and update parameter in the body template.sendBodyAndHeader("direct:findOneAndUpdate", new Bson[] { filter, update }, UPSERT, true); mock.assertIsSatisfied(); assertEquals(1, testCollection.countDocuments(new Document("scientist", "Darwin")), "Upsert was set to true, a new document should have been created."); } @Test public void testInsertOnUpdateAndReturnUpdatedDocument() throws InterruptedException { mock.expectedMessageCount(1); mock.expectedBodyReceived().body(Document.class); Bson filter = eq("extraField", true); Bson update = combine(set("scientist", "Darwin"), currentTimestamp("lastModified")); final Map<String, Object> headers = new HashMap<>(); headers.put(CRITERIA, filter); // insert document if not found headers.put(UPSERT, true); // return document after update (in our case after insert) headers.put(RETURN_DOCUMENT, ReturnDocument.AFTER); template.sendBodyAndHeaders("direct:findOneAndUpdate", update, headers); mock.assertIsSatisfied(); assertEquals(1, testCollection.countDocuments(new Document("scientist", "Darwin")), "Upsert was set to true, a new document should have been created."); } @Test public void testInsertOnUpdateSortBy() throws InterruptedException { mock.expectedMessageCount(1); // insert some documents and use sort by to update only the first element String connes = "{\"_id\":\"1\", \"scientist\":\"Connes\", \"fixedField\": \"fixedValue\"}"; testCollection.insertOne(Document.parse(connes)); String serre = "{\"_id\":\"2\", \"scientist\":\"Serre\", \"fixedField\": \"fixedValue\"}"; testCollection.insertOne(Document.parse(serre)); Bson filter = eq("fixedField", "fixedValue"); Bson update = combine(set("scientist", "Dirac"), currentTimestamp("lastModified")); final Map<String, Object> headers = new HashMap<>(); headers.put(CRITERIA, filter); // sort by id headers.put(SORT_BY, Sorts.ascending("_id")); template.sendBodyAndHeaders("direct:findOneAndUpdate", update, headers); mock.assertIsSatisfied(); assertEquals(1, testCollection.countDocuments(new Document("scientist", "Dirac")), "Update should have happened, Dirac should be present."); assertEquals(1, testCollection.countDocuments(new Document("scientist", "Serre")), "Serre should still be present as his ID is higher."); assertEquals(0, testCollection.countDocuments(new Document("scientist", "Connes")), "Connes should have been updated to Dirac."); } @Test public void testInsertOnUpdateProjection() throws InterruptedException { mock.expectedMessageCount(1); mock.expectedBodyReceived().body(Document.class); Bson filter = eq("extraField", true); Bson update = combine(set("scientist", "Darwin"), currentTimestamp("lastModified")); final Map<String, Object> headers = new HashMap<>(); headers.put(CRITERIA, filter); // insert document if not found headers.put(UPSERT, true); // return only scientist field headers.put(FIELDS_PROJECTION, Projections.include("scientist")); // return document after update (in our case after insert) headers.put(RETURN_DOCUMENT, ReturnDocument.AFTER); Document doc = template.requestBodyAndHeaders("direct:findOneAndUpdate", update, headers, Document.class); mock.assertIsSatisfied(); assertTrue(doc.containsKey("scientist"), "Projection is set to include scientist field"); assertFalse(doc.containsKey("extraField"), "Projection is set to only include scientist field"); } @Test public void testFindOneAndUpdateOptions() throws InterruptedException { mock.expectedMessageCount(1); // insert some documents and use sort by to update only the first element String connes = "{\"_id\":\"1\", \"scientist\":\"Connes\", \"fixedField\": \"fixedValue\"}"; testCollection.insertOne(Document.parse(connes)); String serre = "{\"_id\":\"2\", \"scientist\":\"Serre\", \"fixedField\": \"fixedValue\"}"; testCollection.insertOne(Document.parse(serre)); Bson filter = eq("fixedField", "fixedValue"); Bson update = combine(set("scientist", "Dirac"), currentTimestamp("lastModified")); final Map<String, Object> headers = new HashMap<>(); headers.put(CRITERIA, filter); // Let's check that the correct option is taken into account headers.put(SORT_BY, Sorts.descending("_id")); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions(); options.sort(Sorts.ascending("_id")); headers.put(OPTIONS, options); template.sendBodyAndHeaders("direct:findOneAndUpdate", update, headers); mock.assertIsSatisfied(); assertEquals(1, testCollection.countDocuments(new Document("scientist", "Dirac")), "Update should have happened, Dirac should be present."); assertEquals(1, testCollection.countDocuments(new Document("scientist", "Serre")), "Serre should still be present as his ID is higher."); assertEquals(0, testCollection.countDocuments(new Document("scientist", "Connes")), "Connes should have been updated to Dirac."); } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:findOneAndUpdate") .to("mongodb:myDb?database={{mongodb.testDb}}&collection={{mongodb.testCollection}}&operation=findOneAndUpdate") .to(mock); } }; } @RouteFixture @Override public void createRouteBuilder(CamelContext context) throws Exception { context.addRoutes(createRouteBuilder()); } }
MongoDbFindOneAndUpdateOperationIT
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/tck/MergeWithSingleTckTest.java
{ "start": 765, "end": 1096 }
class ____ extends BaseTck<Long> { @Override public Publisher<Long> createPublisher(long elements) { if (elements == 0) { return Flowable.empty(); } return Flowable.rangeLong(1, elements - 1) .mergeWith(Single.just(elements)) ; } }
MergeWithSingleTckTest
java
netty__netty
microbench/src/main/java/io/netty/handler/codec/protobuf/VarintDecodingBenchmark.java
{ "start": 1959, "end": 6238 }
enum ____ { SMALL, LARGE, MEDIUM, ALL } @Param InputDistribution inputDistribution; ByteBuf[] data; int index; @Setup public void init() { ByteBuf[] dataSet; switch (inputDistribution) { case SMALL: dataSet = new ByteBuf[] { generateData(1, 1), generateData(2, 2), generateData(3, 3) }; break; case LARGE: dataSet = new ByteBuf[] { generateData(5, 5) }; if (inputs > 1) { System.exit(1); } break; case MEDIUM: dataSet = new ByteBuf[] { generateData(1, 5), generateData(2, 5), generateData(3, 5), generateData(4, 5) }; break; case ALL: dataSet = new ByteBuf[] { generateData(1, 1), generateData(2, 2), generateData(3, 3), generateData(1, 5), generateData(2, 5), generateData(3, 5), generateData(4, 5), generateData(5, 5) }; break; default: throw new RuntimeException("Unknown distribution"); } data = new ByteBuf[inputs]; Random rnd = new Random(SEED); for (int i = 0; i < inputs; i++) { data[i] = dataSet[rnd.nextInt(dataSet.length)]; } index = 0; } public static ByteBuf generateData(int varintLength, int capacity) { byte[] bytes = new byte[capacity]; for (int i = 0; i < (varintLength - 1); i++) { bytes[i] = (byte) 150; } // delimiter bytes[varintLength - 1] = (byte) 1; return Unpooled.wrappedBuffer(bytes); } public ByteBuf nextData() { index++; if (index == data.length) { index = 0; } return data[index].resetReaderIndex(); } @Benchmark public int oldReadRawVarint32() { return oldReadRawVarint32(nextData()); } @Benchmark public int readRawVarint32() { return ProtobufVarint32FrameDecoder.readRawVarint32(nextData()); } /** * Reads variable length 32bit int from buffer * * @return decoded int if buffers readerIndex has been forwarded else nonsense value */ private static int oldReadRawVarint32(ByteBuf buffer) { if (!buffer.isReadable()) { return 0; } buffer.markReaderIndex(); byte tmp = buffer.readByte(); if (tmp >= 0) { return tmp; } else { int result = tmp & 127; if (!buffer.isReadable()) { buffer.resetReaderIndex(); return 0; } if ((tmp = buffer.readByte()) >= 0) { result |= tmp << 7; } else { result |= (tmp & 127) << 7; if (!buffer.isReadable()) { buffer.resetReaderIndex(); return 0; } if ((tmp = buffer.readByte()) >= 0) { result |= tmp << 14; } else { result |= (tmp & 127) << 14; if (!buffer.isReadable()) { buffer.resetReaderIndex(); return 0; } if ((tmp = buffer.readByte()) >= 0) { result |= tmp << 21; } else { result |= (tmp & 127) << 21; if (!buffer.isReadable()) { buffer.resetReaderIndex(); return 0; } result |= (tmp = buffer.readByte()) << 28; if (tmp < 0) { throw new CorruptedFrameException("malformed varint."); } } } } return result; } } }
InputDistribution
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_843/TagInfo.java
{ "start": 257, "end": 426 }
class ____ { private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
TagInfo
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/builder/AdviceWithTasks.java
{ "start": 2331, "end": 2524 }
interface ____ { String getId(); boolean match(ProcessorDefinition<?> processor); } /** * Will match by id of the processor. */ private static final
MatchBy
java
apache__camel
components/camel-gson/src/test/java/org/apache/camel/component/gson/GsonMarshalExclusionTest.java
{ "start": 3304, "end": 3768 }
class ____ implements ExclusionStrategy { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getAnnotation(ExcludeWeight.class) != null; } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } } //START SNIPPET: strategy /** * Strategy to exclude {@link ExcludeAge} annotated fields */ protected static
WeightExclusionStrategy
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/KubernetesServiceAccountsComponentBuilderFactory.java
{ "start": 2005, "end": 4768 }
interface ____ extends ComponentBuilder<KubernetesServiceAccountsComponent> { /** * To use an existing kubernetes client. * * The option is a: * &lt;code&gt;io.fabric8.kubernetes.client.KubernetesClient&lt;/code&gt; type. * * Group: producer * * @param kubernetesClient the value to set * @return the dsl builder */ default KubernetesServiceAccountsComponentBuilder kubernetesClient(io.fabric8.kubernetes.client.KubernetesClient kubernetesClient) { doSetProperty("kubernetesClient", kubernetesClient); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default KubernetesServiceAccountsComponentBuilder 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 KubernetesServiceAccountsComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } }
KubernetesServiceAccountsComponentBuilder
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/impl/SpringSupervisingRouteControllerTest.java
{ "start": 3472, "end": 3743 }
class ____ extends SedaComponent { @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { return new MyJmsEndpoint(remaining); } } public static
MyJmsComponent
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintTest.java
{ "start": 8598, "end": 8779 }
class ____ extends Person { } @Entity(name = "Student") @PrimaryKeyJoinColumn( name = "PERSON_ID", foreignKey = @ForeignKey( name = "FK_STUDENT_PERSON" ) ) public static
Professor
java
netty__netty
common/src/main/java/io/netty/util/Recycler.java
{ "start": 16035, "end": 18221 }
class ____<T> extends EnhancedHandle<T> { private static final int STATE_CLAIMED = 0; private static final int STATE_AVAILABLE = 1; private static final AtomicIntegerFieldUpdater<DefaultHandle<?>> STATE_UPDATER; static { AtomicIntegerFieldUpdater<?> updater = AtomicIntegerFieldUpdater.newUpdater(DefaultHandle.class, "state"); //noinspection unchecked STATE_UPDATER = (AtomicIntegerFieldUpdater<DefaultHandle<?>>) updater; } private volatile int state; // State is initialised to STATE_CLAIMED (aka. 0) so they can be released. private final GuardedLocalPool<T> localPool; private T value; DefaultHandle(GuardedLocalPool<T> localPool) { this.localPool = localPool; } @Override public void recycle(Object object) { if (object != value) { throw new IllegalArgumentException("object does not belong to handle"); } toAvailable(); localPool.release(this); } @Override public void unguardedRecycle(Object object) { if (object != value) { throw new IllegalArgumentException("object does not belong to handle"); } unguardedToAvailable(); localPool.release(this); } T claim() { assert state == STATE_AVAILABLE; STATE_UPDATER.lazySet(this, STATE_CLAIMED); return value; } void set(T value) { this.value = value; } private void toAvailable() { int prev = STATE_UPDATER.getAndSet(this, STATE_AVAILABLE); if (prev == STATE_AVAILABLE) { throw new IllegalStateException("Object has been recycled already."); } } private void unguardedToAvailable() { int prev = state; if (prev == STATE_AVAILABLE) { throw new IllegalStateException("Object has been recycled already."); } STATE_UPDATER.lazySet(this, STATE_AVAILABLE); } } private static final
DefaultHandle
java
apache__camel
components/camel-flink/src/main/java/org/apache/camel/component/flink/Flinks.java
{ "start": 993, "end": 1339 }
class ____ { private Flinks() { } public static ExecutionEnvironment createExecutionEnvironment() { return ExecutionEnvironment.getExecutionEnvironment(); } public static StreamExecutionEnvironment createStreamExecutionEnvironment() { return StreamExecutionEnvironment.getExecutionEnvironment(); } }
Flinks
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/boot/model/Selection.java
{ "start": 303, "end": 557 }
enum ____ { COLUMN, FORMULA } private final SelectionType selectionType; public Selection(SelectionType selectionType) { this.selectionType = selectionType; } public SelectionType getSelectionType() { return selectionType; } }
SelectionType
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java
{ "start": 1317, "end": 6380 }
class ____ { private StaticApplicationContext registry; @BeforeEach void setup() { this.registry = new StaticApplicationContext(); } @AfterEach void cleanUp() { this.registry.close(); } @Test void loadClass() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class); assertThat(load(loader)).isOne(); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test void anonymousClassNotLoaded() { MyComponent myComponent = new MyComponent() { }; BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, myComponent.getClass()); assertThat(load(loader)).isZero(); } @Test void loadJsr330Class() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyNamedComponent.class); assertThat(load(loader)).isOne(); assertThat(this.registry.containsBean("myNamedComponent")).isTrue(); } @Test @WithSampleBeansXmlResource void loadXmlResource() { ClassPathResource resource = new ClassPathResource("org/springframework/boot/sample-beans.xml"); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(load(loader)).isOne(); assertThat(this.registry.containsBean("myXmlComponent")).isTrue(); } @Test @WithResource(name = "org/springframework/boot/sample-beans.groovy", content = """ import org.springframework.boot.sampleconfig.MyComponent; beans { myGroovyComponent(MyComponent) {} } """) void loadGroovyResource() { ClassPathResource resource = new ClassPathResource("org/springframework/boot/sample-beans.groovy"); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(load(loader)).isOne(); assertThat(this.registry.containsBean("myGroovyComponent")).isTrue(); } @Test @WithResource(name = "org/springframework/boot/sample-namespace.groovy", content = """ import org.springframework.boot.sampleconfig.MyComponent; beans { xmlns([ctx:'http://www.springframework.org/schema/context']) ctx.'component-scan'('base-package':'nonexistent') myGroovyComponent(MyComponent) {} } """) void loadGroovyResourceWithNamespace() { ClassPathResource resource = new ClassPathResource("org/springframework/boot/sample-namespace.groovy"); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(load(loader)).isOne(); assertThat(this.registry.containsBean("myGroovyComponent")).isTrue(); } @Test void loadPackage() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage()); assertThat(load(loader)).isEqualTo(2); assertThat(this.registry.containsBean("myComponent")).isTrue(); assertThat(this.registry.containsBean("myNamedComponent")).isTrue(); } @Test void loadClassName() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getName()); assertThat(load(loader)).isOne(); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test @WithSampleBeansXmlResource void loadXmlName() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, "classpath:org/springframework/boot/sample-beans.xml"); assertThat(load(loader)).isOne(); assertThat(this.registry.containsBean("myXmlComponent")).isTrue(); } @Test @WithResource(name = "org/springframework/boot/sample-beans.groovy", content = """ import org.springframework.boot.sampleconfig.MyComponent; beans { myGroovyComponent(MyComponent) {} } """) void loadGroovyName() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, "classpath:org/springframework/boot/sample-beans.groovy"); assertThat(load(loader)).isOne(); assertThat(this.registry.containsBean("myGroovyComponent")).isTrue(); } @Test void loadPackageName() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage().getName()); assertThat(load(loader)).isEqualTo(2); assertThat(this.registry.containsBean("myComponent")).isTrue(); assertThat(this.registry.containsBean("myNamedComponent")).isTrue(); } @Test void loadPackageNameWithoutDot() { // See gh-6126 BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponentInPackageWithoutDot.class.getPackage().getName()); int loaded = load(loader); assertThat(loaded).isOne(); assertThat(this.registry.containsBean("myComponentInPackageWithoutDot")).isTrue(); } @Test void loadPackageAndClassDoesNotDoubleAdd() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage(), MyComponent.class); assertThat(load(loader)).isEqualTo(2); assertThat(this.registry.containsBean("myComponent")).isTrue(); assertThat(this.registry.containsBean("myNamedComponent")).isTrue(); } private int load(BeanDefinitionLoader loader) { int beans = this.registry.getBeanDefinitionCount(); loader.load(); return this.registry.getBeanDefinitionCount() - beans; } }
BeanDefinitionLoaderTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhance/internal/bytebuddy/DirtyCheckingWithMappedsuperclassTest.java
{ "start": 5382, "end": 5981 }
class ____ extends TableTopGame { @Id private String id; private String name; public CardGame() { } private CardGame(String id, String name) { this.id = id; this.name = name; setCode( createCode( name ) ); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; setCode( createCode( name ) ); } private String createCode(String name) { return "X" + name.substring( 0, 3 ).toLowerCase() + "X"; } } }
CardGame
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/logging/logback/SystemStatusListener.java
{ "start": 1470, "end": 2798 }
class ____ extends OnConsoleStatusListener { private static final long RETROSPECTIVE_THRESHOLD = 300; private final boolean debug; private SystemStatusListener(boolean debug) { this.debug = debug; setResetResistant(false); setRetrospective(0); } @Override public void start() { super.start(); retrospectivePrint(); } private void retrospectivePrint() { if (this.context == null) { return; } long now = System.currentTimeMillis(); List<Status> statusList = this.context.getStatusManager().getCopyOfStatusList(); statusList.stream() .filter((status) -> getElapsedTime(status, now) < RETROSPECTIVE_THRESHOLD) .forEach(this::addStatusEvent); } @Override public void addStatusEvent(Status status) { if (this.debug || status.getLevel() >= Status.WARN) { super.addStatusEvent(status); } } @Override protected PrintStream getPrintStream() { return (!this.debug) ? System.err : System.out; } private static long getElapsedTime(Status status, long now) { return now - status.getTimestamp(); } static void addTo(LoggerContext loggerContext) { addTo(loggerContext, false); } static void addTo(LoggerContext loggerContext, boolean debug) { StatusListenerConfigHelper.addOnConsoleListenerInstance(loggerContext, new SystemStatusListener(debug)); } }
SystemStatusListener
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/PasswordManagementConfigurerTests.java
{ "start": 1961, "end": 3713 }
class ____ { public final SpringTestContext spring = new SpringTestContext(this); @Autowired MockMvc mvc; @Test public void whenChangePasswordPageNotSetThenDefaultChangePasswordPageUsed() throws Exception { this.spring.register(PasswordManagementWithDefaultChangePasswordPageConfig.class).autowire(); this.mvc.perform(get("/.well-known/change-password")) .andExpect(status().isFound()) .andExpect(redirectedUrl("/change-password")); } @Test public void whenChangePasswordPageSetThenSpecifiedChangePasswordPageUsed() throws Exception { this.spring.register(PasswordManagementWithCustomChangePasswordPageConfig.class).autowire(); this.mvc.perform(get("/.well-known/change-password")) .andExpect(status().isFound()) .andExpect(redirectedUrl("/custom-change-password-page")); } @Test public void whenSettingNullChangePasswordPage() { PasswordManagementConfigurer configurer = new PasswordManagementConfigurer(); assertThatIllegalArgumentException().isThrownBy(() -> configurer.changePasswordPage(null)) .withMessage("changePasswordPage cannot be empty"); } @Test public void whenSettingEmptyChangePasswordPage() { PasswordManagementConfigurer configurer = new PasswordManagementConfigurer(); assertThatIllegalArgumentException().isThrownBy(() -> configurer.changePasswordPage("")) .withMessage("changePasswordPage cannot be empty"); } @Test public void whenSettingBlankChangePasswordPage() { PasswordManagementConfigurer configurer = new PasswordManagementConfigurer(); assertThatIllegalArgumentException().isThrownBy(() -> configurer.changePasswordPage(" ")) .withMessage("changePasswordPage cannot be empty"); } @Configuration @EnableWebSecurity static
PasswordManagementConfigurerTests
java
apache__camel
components/camel-quartz/src/test/java/org/apache/camel/routepolicy/quartz/SimpleScheduledRoutePolicyTest.java
{ "start": 13554, "end": 15376 }
class ____ extends NoBuilderTest { @Test public void testNoAutoStartup() throws Exception { MockEndpoint success = context.getEndpoint("mock:success", MockEndpoint.class); success.expectedMessageCount(1); context.getComponent("direct", DirectComponent.class).setBlock(false); context.getComponent("quartz", QuartzComponent.class) .setPropertiesFile("org/apache/camel/routepolicy/quartz/myquartz.properties"); context.addRoutes(new RouteBuilder() { public void configure() { SimpleScheduledRoutePolicy policy = new SimpleScheduledRoutePolicy(); long startTime = System.currentTimeMillis() + 500; policy.setRouteStartDate(new Date(startTime)); policy.setRouteStartRepeatCount(1); policy.setRouteStartRepeatInterval(1000); from("direct:start") .routeId("test") .noAutoStartup() .routePolicy(policy) .to("mock:success"); } }); context.start(); // wait for route to start Awaitility.await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> { assertTrue(ServiceHelper.isStarted(context.getRoute("test").getConsumer())); }); template.sendBody("direct:start", "Ready or not, Here, I come"); context.getComponent("quartz", QuartzComponent.class).stop(); success.assertIsSatisfied(); } } @Nested
SimpleTest7
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/util/Collections.java
{ "start": 432, "end": 1968 }
class ____ { private Collections() { } @SafeVarargs public static <T> Set<T> asSet(T... elements) { Set<T> set = new HashSet<>( elements.length ); java.util.Collections.addAll( set, elements ); return set; } @SafeVarargs public static <T> Set<T> asSet(Collection<T> collection, T... elements) { Set<T> set = new HashSet<>( collection.size() + elements.length ); java.util.Collections.addAll( set, elements ); return set; } @SafeVarargs public static <T> Set<T> asSet(Collection<T> collection, Collection<T>... elements) { Set<T> set = new HashSet<>( collection ); for ( Collection<T> element : elements ) { set.addAll( element ); } return set; } public static <T> T first(Collection<T> collection) { return collection.iterator().next(); } public static <T> T last(List<T> list) { return list.get( list.size() - 1 ); } public static <T> List<T> join(List<T> a, List<T> b) { List<T> result = new ArrayList<>( a.size() + b.size() ); result.addAll( a ); result.addAll( b ); return result; } public static <K, V> Map.Entry<K, V> first(Map<K, V> map) { return map.entrySet().iterator().next(); } public static <K, V> V firstValue(Map<K, V> map) { return first( map ).getValue(); } public static <K, V> K firstKey(Map<K, V> map) { return first( map ).getKey(); } }
Collections
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/token/CreateTokenRequest.java
{ "start": 1257, "end": 9363 }
enum ____ { PASSWORD("password"), KERBEROS("_kerberos"), REFRESH_TOKEN("refresh_token"), AUTHORIZATION_CODE("authorization_code"), CLIENT_CREDENTIALS("client_credentials"); private final String value; GrantType(String value) { this.value = value; } public String getValue() { return value; } public static GrantType fromString(String grantType) { if (grantType != null) { for (GrantType type : values()) { if (type.getValue().equals(grantType)) { return type; } } } return null; } } private static final Set<GrantType> SUPPORTED_GRANT_TYPES = Collections.unmodifiableSet( EnumSet.of(GrantType.PASSWORD, GrantType.KERBEROS, GrantType.REFRESH_TOKEN, GrantType.CLIENT_CREDENTIALS) ); private String grantType; private String username; private SecureString password; private SecureString kerberosTicket; private String scope; private String refreshToken; public CreateTokenRequest(StreamInput in) throws IOException { super(in); grantType = in.readString(); username = in.readOptionalString(); password = in.readOptionalSecureString(); refreshToken = in.readOptionalString(); scope = in.readOptionalString(); kerberosTicket = in.readOptionalSecureString(); } public CreateTokenRequest() {} public CreateTokenRequest( String grantType, @Nullable String username, @Nullable SecureString password, @Nullable SecureString kerberosTicket, @Nullable String scope, @Nullable String refreshToken ) { this.grantType = grantType; this.username = username; this.password = password; this.kerberosTicket = kerberosTicket; this.scope = scope; this.refreshToken = refreshToken; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; GrantType type = GrantType.fromString(grantType); if (type != null) { switch (type) { case PASSWORD -> { validationException = validateUnsupportedField(type, "kerberos_ticket", kerberosTicket, validationException); validationException = validateUnsupportedField(type, "refresh_token", refreshToken, validationException); validationException = validateRequiredField("username", username, validationException); validationException = validateRequiredField("password", password, validationException); } case KERBEROS -> { validationException = validateUnsupportedField(type, "username", username, validationException); validationException = validateUnsupportedField(type, "password", password, validationException); validationException = validateUnsupportedField(type, "refresh_token", refreshToken, validationException); validationException = validateRequiredField("kerberos_ticket", kerberosTicket, validationException); } case REFRESH_TOKEN -> { validationException = validateUnsupportedField(type, "username", username, validationException); validationException = validateUnsupportedField(type, "password", password, validationException); validationException = validateUnsupportedField(type, "kerberos_ticket", kerberosTicket, validationException); validationException = validateRequiredField("refresh_token", refreshToken, validationException); } case CLIENT_CREDENTIALS -> { validationException = validateUnsupportedField(type, "username", username, validationException); validationException = validateUnsupportedField(type, "password", password, validationException); validationException = validateUnsupportedField(type, "kerberos_ticket", kerberosTicket, validationException); validationException = validateUnsupportedField(type, "refresh_token", refreshToken, validationException); } default -> validationException = addValidationError( "grant_type only supports the values: [" + SUPPORTED_GRANT_TYPES.stream().map(GrantType::getValue).collect(Collectors.joining(", ")) + "]", validationException ); } } else { validationException = addValidationError( "grant_type only supports the values: [" + SUPPORTED_GRANT_TYPES.stream().map(GrantType::getValue).collect(Collectors.joining(", ")) + "]", validationException ); } return validationException; } private static ActionRequestValidationException validateRequiredField( String field, String fieldValue, ActionRequestValidationException validationException ) { if (Strings.isNullOrEmpty(fieldValue)) { validationException = addValidationError(String.format(Locale.ROOT, "%s is missing", field), validationException); } return validationException; } private static ActionRequestValidationException validateRequiredField( String field, SecureString fieldValue, ActionRequestValidationException validationException ) { if (fieldValue == null || fieldValue.getChars() == null || fieldValue.length() == 0) { validationException = addValidationError(String.format(Locale.ROOT, "%s is missing", field), validationException); } return validationException; } private static ActionRequestValidationException validateUnsupportedField( GrantType grantType, String field, Object fieldValue, ActionRequestValidationException validationException ) { if (fieldValue != null) { validationException = addValidationError( String.format(Locale.ROOT, "%s is not supported with the %s grant_type", field, grantType.getValue()), validationException ); } return validationException; } public void setGrantType(String grantType) { this.grantType = grantType; } public void setUsername(@Nullable String username) { this.username = username; } public void setPassword(@Nullable SecureString password) { this.password = password; } public void setKerberosTicket(@Nullable SecureString kerberosTicket) { this.kerberosTicket = kerberosTicket; } public void setScope(@Nullable String scope) { this.scope = scope; } public void setRefreshToken(@Nullable String refreshToken) { this.refreshToken = refreshToken; } public String getGrantType() { return grantType; } @Nullable public String getUsername() { return username; } @Nullable public SecureString getPassword() { return password; } @Nullable public SecureString getKerberosTicket() { return kerberosTicket; } @Nullable public String getScope() { return scope; } @Nullable public String getRefreshToken() { return refreshToken; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(grantType); out.writeOptionalString(username); out.writeOptionalSecureString(password); out.writeOptionalString(refreshToken); out.writeOptionalString(scope); out.writeOptionalSecureString(kerberosTicket); } }
GrantType
java
apache__flink
flink-core-api/src/main/java/org/apache/flink/api/common/state/State.java
{ "start": 1313, "end": 1411 }
interface ____ { /** Removes the value mapped under the current key. */ void clear(); }
State
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/ConnectionReleaseMode.java
{ "start": 1847, "end": 2457 }
enum ____. */ public static ConnectionReleaseMode parse(final String name) { return ConnectionReleaseMode.valueOf( name.toUpperCase(Locale.ROOT) ); } public static ConnectionReleaseMode interpret(Object setting) { if ( setting == null ) { return null; } else if ( setting instanceof ConnectionReleaseMode mode ) { return mode; } else { final String value = setting.toString(); if ( isEmpty( value ) ) { return null; } // here we disregard "auto" else if ( value.equalsIgnoreCase( "auto" ) ) { return null; } else { return parse( value ); } } } }
value
java
micronaut-projects__micronaut-core
http-client-tck/src/main/java/io/micronaut/http/client/tck/tests/filter/ClientRequestFilterTest.java
{ "start": 20391, "end": 23255 }
class ____ { @Get("/request-filter/immediate-request-parameter") public String requestFilterImmediateRequestParameter() { return "foo"; } @Get("/request-filter/immediate-mutable-request-parameter") public String requestFilterImmediateMutableRequestParameter(HttpRequest<?> request) { return request.getHeaders().get("foo"); } @Get("/request-filter/replace-request-2") public String requestFilterReplaceRequest(HttpRequest<?> request) { return request.getPath(); } @Get("/request-filter/replace-mutable-request-2") public String requestFilterReplaceMutableRequest(HttpRequest<?> request) { return request.getPath(); } @Get("/request-filter/replace-request-null") public String requestFilterReplaceRequestNull(HttpRequest<?> request) { return request.getPath(); } @Get("/request-filter/replace-request-empty") public String requestFilterReplaceRequestEmpty(HttpRequest<?> request) { return request.getPath(); } @Get("/request-filter/replace-request-publisher-2") public String requestFilterReplaceRequestPublisher(HttpRequest<?> request) { return request.getPath(); } @Get("/request-filter/replace-request-mono-2") public String requestFilterReplaceRequestMono(HttpRequest<?> request) { return request.getPath(); } @Get("/request-filter/replace-request-completable-2") public String requestFilterReplaceRequestCompletable(HttpRequest<?> request) { return request.getPath(); } @Get("/request-filter/replace-request-completion-2") public String requestFilterReplaceRequestCompletion(HttpRequest<?> request) { return request.getPath(); } @Get("/request-filter/continuation-blocking") public String requestFilterContinuationBlocking(HttpRequest<?> request) { return request.getHeaders().get("foo"); } @Get("/request-filter/continuation-reactive-publisher") public String requestFilterContinuationReactivePublisher(HttpRequest<?> request) { return request.getHeaders().get("foo"); } @Get("/request-filter/continuation-update-request") public String requestFilterContinuationUpdateRequest(HttpRequest<?> request) { return request.getPath(); } @Get("/request-filter/null-response") public String requestFilterNullResponse(HttpRequest<?> request) { return "foo"; } @Get("/request-filter/empty-optional-response") public String requestFilterEmptyOptionalResponse(HttpRequest<?> request) { return "foo"; } } }
MyController
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ProcessTableFunctionTestUtils.java
{ "start": 34687, "end": 35814 }
class ____ extends AppendProcessTableFunctionBase { public void eval( Context ctx, @StateHint MapView<String, Integer> s, @ArgumentHint({SET_SEMANTIC_TABLE, OPTIONAL_PARTITION_BY}) Row r) throws Exception { final String viewToString = s.getMap().entrySet().stream() .map(Objects::toString) .sorted() .collect(Collectors.joining(", ", "{", "}")); collectObjects(viewToString, s.getClass().getSimpleName(), r); // get final String name = r.getFieldAs("name"); int count = 1; if (s.contains(name)) { count = s.get(name); } // create s.put("old" + name, count); s.put(name, count + 1); // clear if (count == 2) { ctx.clearState("s"); } } } @DataTypeHint("ROW<name STRING, count BIGINT, mode STRING>") public abstract static
NonNullMapStateFunction
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/debugging/LocationFactory.java
{ "start": 308, "end": 620 }
class ____ { private static final Factory factory = createLocationFactory(); private LocationFactory() {} public static Location create() { return create(false); } public static Location create(boolean inline) { return factory.create(inline); } private
LocationFactory
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/engine/support/hierarchical/ParallelExecutionIntegrationTests.java
{ "start": 18585, "end": 18786 }
class ____ { @Test @ResourceLock(value = "b", mode = READ_WRITE) void test1() throws InterruptedException { incrementBlockAndCheck(sharedResource, countDownLatch); } } @Nested
Test1
java
google__error-prone
check_api/src/main/java/com/google/errorprone/matchers/ChildMultiMatcher.java
{ "start": 4995, "end": 6764 }
class ____<N extends Tree> extends ListMatcher<N> { @Override public MatchResult<N> matches(List<Matchable<N>> matchables, Matcher<N> nodeMatcher) { if (matchables.isEmpty()) { return MatchResult.none(); } Matchable<N> last = Iterables.getLast(matchables); return nodeMatcher.matches(last.tree(), last.state()) ? MatchResult.match(last.tree()) : MatchResult.<N>none(); } } /** The matcher to apply to the subnodes in question. */ protected final Matcher<N> nodeMatcher; private final ListMatcher<N> listMatcher; public ChildMultiMatcher(MatchType matchType, Matcher<N> nodeMatcher) { this.nodeMatcher = nodeMatcher; this.listMatcher = ListMatcher.create(matchType); } @Override public boolean matches(T tree, VisitorState state) { return multiMatchResult(tree, state).matches(); } @Override public MultiMatchResult<N> multiMatchResult(T tree, VisitorState state) { ImmutableList.Builder<Matchable<N>> result = ImmutableList.builder(); for (N subnode : getChildNodes(tree, state)) { TreePath newPath = new TreePath(state.getPath(), subnode); result.add(Matchable.create(subnode, state.withPath(newPath))); } MatchResult<N> matchResult = listMatcher.matches(result.build(), nodeMatcher); return MultiMatchResult.create(matchResult.matches(), matchResult.matchingNodes()); } /** * Returns the set of child nodes to match. The nodes must be immediate children of the current * node to ensure the TreePath calculation is correct. MultiMatchers with other requirements * should not subclass ChildMultiMatcher. */ @ForOverride protected abstract Iterable<? extends N> getChildNodes(T tree, VisitorState state); }
LastMatcher
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/legacy/api/TableSchema.java
{ "start": 3493, "end": 27514 }
class ____ { private static final String ATOMIC_TYPE_FIELD_NAME = "f0"; private final List<TableColumn> columns; private final List<WatermarkSpec> watermarkSpecs; private final @Nullable UniqueConstraint primaryKey; private TableSchema( List<TableColumn> columns, List<WatermarkSpec> watermarkSpecs, @Nullable UniqueConstraint primaryKey) { this.columns = Preconditions.checkNotNull(columns); this.watermarkSpecs = Preconditions.checkNotNull(watermarkSpecs); this.primaryKey = primaryKey; } /** * @deprecated Use the {@link Builder} instead. */ @Deprecated public TableSchema(String[] fieldNames, TypeInformation<?>[] fieldTypes) { DataType[] fieldDataTypes = fromLegacyInfoToDataType(fieldTypes); validateNameTypeNumberEqual(fieldNames, fieldDataTypes); List<TableColumn> columns = new ArrayList<>(); for (int i = 0; i < fieldNames.length; i++) { columns.add(TableColumn.physical(fieldNames[i], fieldDataTypes[i])); } validateColumnsAndWatermarkSpecs(columns, Collections.emptyList()); this.columns = columns; this.watermarkSpecs = Collections.emptyList(); this.primaryKey = null; } /** Returns a deep copy of the table schema. */ public TableSchema copy() { return new TableSchema( new ArrayList<>(columns), new ArrayList<>(watermarkSpecs), primaryKey); } /** Returns all field data types as an array. */ public DataType[] getFieldDataTypes() { return columns.stream().map(TableColumn::getType).toArray(DataType[]::new); } /** * @deprecated This method will be removed in future versions as it uses the old type system. It * is recommended to use {@link #getFieldDataTypes()} instead which uses the new type system * based on {@link DataTypes}. Please make sure to use either the old or the new type system * consistently to avoid unintended behavior. See the website documentation for more * information. */ @Deprecated public TypeInformation<?>[] getFieldTypes() { return fromDataTypeToLegacyInfo(getFieldDataTypes()); } /** * Returns the specified data type for the given field index. * * @param fieldIndex the index of the field */ public Optional<DataType> getFieldDataType(int fieldIndex) { if (fieldIndex < 0 || fieldIndex >= columns.size()) { return Optional.empty(); } return Optional.of(columns.get(fieldIndex).getType()); } /** * @deprecated This method will be removed in future versions as it uses the old type system. It * is recommended to use {@link #getFieldDataType(int)} instead which uses the new type * system based on {@link DataTypes}. Please make sure to use either the old or the new type * system consistently to avoid unintended behavior. See the website documentation for more * information. */ @Deprecated public Optional<TypeInformation<?>> getFieldType(int fieldIndex) { return getFieldDataType(fieldIndex).map(TypeConversions::fromDataTypeToLegacyInfo); } /** * Returns the specified data type for the given field name. * * @param fieldName the name of the field */ public Optional<DataType> getFieldDataType(String fieldName) { return this.columns.stream() .filter(column -> column.getName().equals(fieldName)) .findFirst() .map(TableColumn::getType); } /** * @deprecated This method will be removed in future versions as it uses the old type system. It * is recommended to use {@link #getFieldDataType(String)} instead which uses the new type * system based on {@link DataTypes}. Please make sure to use either the old or the new type * system consistently to avoid unintended behavior. See the website documentation for more * information. */ @Deprecated public Optional<TypeInformation<?>> getFieldType(String fieldName) { return getFieldDataType(fieldName).map(TypeConversions::fromDataTypeToLegacyInfo); } /** Returns the number of fields. */ public int getFieldCount() { return columns.size(); } /** Returns all field names as an array. */ public String[] getFieldNames() { return this.columns.stream().map(TableColumn::getName).toArray(String[]::new); } /** * Returns the specified name for the given field index. * * @param fieldIndex the index of the field */ public Optional<String> getFieldName(int fieldIndex) { if (fieldIndex < 0 || fieldIndex >= columns.size()) { return Optional.empty(); } return Optional.of(this.columns.get(fieldIndex).getName()); } /** * Returns the {@link TableColumn} instance for the given field index. * * @param fieldIndex the index of the field */ public Optional<TableColumn> getTableColumn(int fieldIndex) { if (fieldIndex < 0 || fieldIndex >= columns.size()) { return Optional.empty(); } return Optional.of(this.columns.get(fieldIndex)); } /** * Returns the {@link TableColumn} instance for the given field name. * * @param fieldName the name of the field */ public Optional<TableColumn> getTableColumn(String fieldName) { return this.columns.stream() .filter(column -> column.getName().equals(fieldName)) .findFirst(); } /** Returns all the {@link TableColumn}s for this table schema. */ public List<TableColumn> getTableColumns() { return new ArrayList<>(this.columns); } /** * Converts all columns of this schema into a (possibly nested) row data type. * * <p>This method returns the <b>source-to-query schema</b>. * * <p>Note: The returned row data type contains physical, computed, and metadata columns. Be * careful when using this method in a table source or table sink. In many cases, {@link * #toPhysicalRowDataType()} might be more appropriate. * * @see DataTypes#ROW(Field...) * @see #toPhysicalRowDataType() * @see #toPersistedRowDataType() */ public DataType toRowDataType() { final Field[] fields = columns.stream() .map(column -> FIELD(column.getName(), column.getType())) .toArray(Field[]::new); // The row should be never null. return ROW(fields).notNull(); } /** * Converts all physical columns of this schema into a (possibly nested) row data type. * * <p>Note: The returned row data type contains only physical columns. It does not include * computed or metadata columns. * * @see DataTypes#ROW(Field...) * @see #toRowDataType() * @see #toPersistedRowDataType() */ public DataType toPhysicalRowDataType() { final Field[] fields = columns.stream() .filter(TableColumn::isPhysical) .map(column -> FIELD(column.getName(), column.getType())) .toArray(Field[]::new); // The row should be never null. return ROW(fields).notNull(); } /** * Converts all persisted columns of this schema into a (possibly nested) row data type. * * <p>This method returns the <b>query-to-sink schema</b>. * * <p>Note: Computed columns and virtual columns are excluded in the returned row data type. The * data type contains the columns of {@link #toPhysicalRowDataType()} plus persisted metadata * columns. * * @see DataTypes#ROW(Field...) * @see #toRowDataType() * @see #toPhysicalRowDataType() */ public DataType toPersistedRowDataType() { final Field[] fields = columns.stream() .filter(TableColumn::isPersisted) .map(column -> FIELD(column.getName(), column.getType())) .toArray(Field[]::new); // The row should be never null. return ROW(fields).notNull(); } /** * @deprecated Use {@link #toRowDataType()} instead. */ @Deprecated @SuppressWarnings("unchecked") public TypeInformation<Row> toRowType() { return (TypeInformation<Row>) fromDataTypeToLegacyInfo(toRowDataType()); } /** * Returns a list of the watermark specification which contains rowtime attribute and watermark * strategy expression. * * <p>NOTE: Currently, there is at most one {@link WatermarkSpec} in the list, because we don't * support multiple watermarks definition yet. But in the future, we may support multiple * watermarks. */ public List<WatermarkSpec> getWatermarkSpecs() { return watermarkSpecs; } public Optional<UniqueConstraint> getPrimaryKey() { return Optional.ofNullable(primaryKey); } /** Helps to migrate to the new {@link Schema} class. */ public Schema toSchema() { return toSchema(Collections.emptyMap()); } /** Helps to migrate to the new {@link Schema} class, retain comments when needed. */ public Schema toSchema(Map<String, String> comments) { final Schema.Builder builder = Schema.newBuilder(); columns.forEach( column -> { if (column instanceof PhysicalColumn) { final PhysicalColumn c = (PhysicalColumn) column; builder.column(c.getName(), c.getType()); } else if (column instanceof MetadataColumn) { final MetadataColumn c = (MetadataColumn) column; builder.columnByMetadata( c.getName(), c.getType(), c.getMetadataAlias().orElse(null), c.isVirtual()); } else if (column instanceof ComputedColumn) { final ComputedColumn c = (ComputedColumn) column; builder.columnByExpression(c.getName(), c.getExpression()); } else { throw new IllegalArgumentException("Unsupported column type: " + column); } String colName = column.getName(); if (comments.containsKey(colName)) { builder.withComment(comments.get(colName)); } }); watermarkSpecs.forEach( spec -> builder.watermark(spec.getRowtimeAttribute(), spec.getWatermarkExpr())); if (primaryKey != null) { builder.primaryKeyNamed(primaryKey.getName(), primaryKey.getColumns()); } return builder.build(); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("root\n"); for (TableColumn column : columns) { sb.append(" |-- "); sb.append(column.asSummaryString()); sb.append('\n'); } if (!watermarkSpecs.isEmpty()) { for (WatermarkSpec watermarkSpec : watermarkSpecs) { sb.append(" |-- "); sb.append(watermarkSpec.asSummaryString()); sb.append('\n'); } } if (primaryKey != null) { sb.append(" |-- ").append(primaryKey.asSummaryString()); sb.append('\n'); } return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TableSchema that = (TableSchema) o; return Objects.equals(columns, that.columns) && Objects.equals(watermarkSpecs, that.watermarkSpecs) && Objects.equals(primaryKey, that.primaryKey); } @Override public int hashCode() { return Objects.hash(columns, watermarkSpecs, primaryKey); } /** * Creates a table schema from a {@link TypeInformation} instance. If the type information is a * {@link CompositeType}, the field names and types for the composite type are used to construct * the {@link TableSchema} instance. Otherwise, a table schema with a single field is created. * The field name is "f0" and the field type the provided type. * * @param typeInfo The {@link TypeInformation} from which the table schema is generated. * @return The table schema that was generated from the given {@link TypeInformation}. * @deprecated This method will be removed soon. Use {@link DataTypes} to declare types. */ @Deprecated public static TableSchema fromTypeInfo(TypeInformation<?> typeInfo) { if (typeInfo instanceof CompositeType<?>) { final CompositeType<?> compositeType = (CompositeType<?>) typeInfo; // get field names and types from composite type final String[] fieldNames = compositeType.getFieldNames(); final TypeInformation<?>[] fieldTypes = new TypeInformation[fieldNames.length]; for (int i = 0; i < fieldTypes.length; i++) { fieldTypes[i] = compositeType.getTypeAt(i); } return new TableSchema(fieldNames, fieldTypes); } else { // create table schema with a single field named "f0" of the given type. return new TableSchema( new String[] {ATOMIC_TYPE_FIELD_NAME}, new TypeInformation<?>[] {typeInfo}); } } /** Helps to migrate to the new {@link ResolvedSchema} to old API methods. */ public static TableSchema fromResolvedSchema(ResolvedSchema resolvedSchema) { return fromResolvedSchema(resolvedSchema, DefaultSqlFactory.INSTANCE); } public static TableSchema fromResolvedSchema( ResolvedSchema resolvedSchema, SqlFactory sqlFactory) { final TableSchema.Builder builder = TableSchema.builder(); resolvedSchema.getColumns().stream() .map( column -> { if (column instanceof Column.PhysicalColumn) { final Column.PhysicalColumn c = (Column.PhysicalColumn) column; return TableColumn.physical(c.getName(), c.getDataType()); } else if (column instanceof Column.MetadataColumn) { final Column.MetadataColumn c = (Column.MetadataColumn) column; return TableColumn.metadata( c.getName(), c.getDataType(), c.getMetadataKey().orElse(null), c.isVirtual()); } else if (column instanceof Column.ComputedColumn) { final Column.ComputedColumn c = (Column.ComputedColumn) column; return TableColumn.computed( c.getName(), c.getDataType(), c.getExpression().asSerializableString(sqlFactory)); } throw new IllegalArgumentException( "Unsupported column type: " + column); }) .forEach(builder::add); resolvedSchema .getWatermarkSpecs() .forEach( spec -> builder.watermark( spec.getRowtimeAttribute(), spec.getWatermarkExpression() .asSerializableString(sqlFactory), spec.getWatermarkExpression().getOutputDataType())); resolvedSchema .getPrimaryKey() .ifPresent( pk -> builder.primaryKey( pk.getName(), pk.getColumns().toArray(new String[0]))); return builder.build(); } public static Builder builder() { return new Builder(); } // ~ Tools ------------------------------------------------------------------ /** * Validate the field names {@code fieldNames} and field types {@code fieldTypes} have equal * number. * * @param fieldNames Field names * @param fieldTypes Field data types */ private static void validateNameTypeNumberEqual(String[] fieldNames, DataType[] fieldTypes) { if (fieldNames.length != fieldTypes.length) { throw new ValidationException( "Number of field names and field data types must be equal.\n" + "Number of names is " + fieldNames.length + ", number of data types is " + fieldTypes.length + ".\n" + "List of field names: " + Arrays.toString(fieldNames) + "\n" + "List of field data types: " + Arrays.toString(fieldTypes)); } } /** Table column and watermark specification sanity check. */ private static void validateColumnsAndWatermarkSpecs( List<TableColumn> columns, List<WatermarkSpec> watermarkSpecs) { // Validate and create name to type mapping. // Field name to data type mapping, we need this because the row time attribute // field can be nested. // This also check duplicate fields. final Map<String, LogicalType> fieldNameToType = new HashMap<>(); for (TableColumn column : columns) { validateAndCreateNameToTypeMapping( fieldNameToType, column.getName(), column.getType().getLogicalType(), ""); } // Validate watermark and rowtime attribute. for (WatermarkSpec watermark : watermarkSpecs) { String rowtimeAttribute = watermark.getRowtimeAttribute(); LogicalType rowtimeType = Optional.ofNullable(fieldNameToType.get(rowtimeAttribute)) .orElseThrow( () -> new ValidationException( String.format( "Rowtime attribute '%s' is not defined in schema.", rowtimeAttribute))); if (!(rowtimeType.getTypeRoot() == LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE || rowtimeType.getTypeRoot() == LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)) { throw new ValidationException( String.format( "Rowtime attribute '%s' must be of type TIMESTAMP or TIMESTAMP_LTZ but is of type '%s'.", rowtimeAttribute, rowtimeType)); } LogicalType watermarkOutputType = watermark.getWatermarkExprOutputType().getLogicalType(); if (!canBeTimeAttributeType(watermarkOutputType)) { throw new ValidationException( String.format( "Watermark strategy %s must be of type TIMESTAMP or TIMESTAMP_LTZ but is of type '%s'.", watermark.getWatermarkExpr(), watermarkOutputType.asSummaryString())); } } } private static void validatePrimaryKey(List<TableColumn> columns, UniqueConstraint primaryKey) { Map<String, TableColumn> columnsByNameLookup = columns.stream() .collect(Collectors.toMap(TableColumn::getName, Function.identity())); for (String columnName : primaryKey.getColumns()) { TableColumn column = columnsByNameLookup.get(columnName); if (column == null) { throw new ValidationException( String.format( "Could not create a PRIMARY KEY '%s'. Column '%s' does not exist.", primaryKey.getName(), columnName)); } if (!column.isPhysical()) { throw new ValidationException( String.format( "Could not create a PRIMARY KEY '%s'. Column '%s' is not a physical column.", primaryKey.getName(), columnName)); } if (column.getType().getLogicalType().isNullable()) { throw new ValidationException( String.format( "Could not create a PRIMARY KEY '%s'. Column '%s' is nullable.", primaryKey.getName(), columnName)); } } } /** * Creates a mapping from field name to data type, the field name can be a nested field. This is * mainly used for validating whether the rowtime attribute (might be nested) exists in the * schema. During creating, it also validates whether there is duplicate field names. * * <p>For example, a "f0" field of ROW type has two nested fields "q1" and "q2". Then the * mapping will be ["f0" -> ROW, "f0.q1" -> INT, "f0.q2" -> STRING]. * * <pre>{@code * f0 ROW<q1 INT, q2 STRING> * }</pre> * * @param fieldNameToType Field name to type mapping that to update * @param fieldName Name of this field, e.g. "q1" or "q2" in the above example * @param fieldType Data type of this field * @param parentFieldName Field name of parent type, e.g. "f0" in the above example */ private static void validateAndCreateNameToTypeMapping( Map<String, LogicalType> fieldNameToType, String fieldName, LogicalType fieldType, String parentFieldName) { String fullFieldName = parentFieldName.isEmpty() ? fieldName : parentFieldName + "." + fieldName; LogicalType oldType = fieldNameToType.put(fullFieldName, fieldType); if (oldType != null) { throw new ValidationException( "Field names must be unique. Duplicate field: '" + fullFieldName + "'"); } if (isCompositeType(fieldType) && !(fieldType instanceof LegacyTypeInformationType)) { final List<String> fieldNames = LogicalTypeChecks.getFieldNames(fieldType); final List<LogicalType> fieldTypes = fieldType.getChildren(); IntStream.range(0, fieldNames.size()) .forEach( i -> validateAndCreateNameToTypeMapping( fieldNameToType, fieldNames.get(i), fieldTypes.get(i), fullFieldName)); } } // -------------------------------------------------------------------------------------------- /** Builder for creating a {@link TableSchema}. */ @Internal public static
TableSchema
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/exception/spi/ViolatedConstraintNameExtractor.java
{ "start": 437, "end": 768 }
interface ____ { /** * Extract the name of the violated constraint from the given * {@link SQLException}. * * @param sqle The exception that was the result of the constraint violation. * @return The extracted constraint name. */ @Nullable String extractConstraintName(SQLException sqle); }
ViolatedConstraintNameExtractor
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/model/ConfigOperateResult.java
{ "start": 758, "end": 1653 }
class ____ implements Serializable { boolean success = true; private long id; private long lastModified; public ConfigOperateResult(long id, long lastModified) { this.id = id; this.lastModified = lastModified; } public ConfigOperateResult(boolean success) { this.success = success; } public ConfigOperateResult() { } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getLastModified() { return lastModified; } public void setLastModified(long lastModified) { this.lastModified = lastModified; } }
ConfigOperateResult
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest84.java
{ "start": 893, "end": 1220 }
class ____ extends TestCase { public void test_false() throws Exception { WallProvider provider = new MySqlWallProvider(); assertTrue(provider.checkValid(// "CREATE INDEX part_of_name ON customer (name(10));")); assertEquals(1, provider.getTableStats().size()); } }
MySqlWallTest84
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/cluster/stats/VersionStats.java
{ "start": 1767, "end": 6260 }
class ____ implements ToXContentFragment, Writeable { private final Set<SingleVersionStats> versionStats; public static VersionStats of(Metadata metadata, List<ClusterStatsNodeResponse> nodeResponses) { final Map<IndexVersion, Integer> indexCounts = new HashMap<>(); final Map<IndexVersion, Integer> primaryShardCounts = new HashMap<>(); final Map<IndexVersion, Long> primaryByteCounts = new HashMap<>(); final Map<String, List<ShardStats>> indexPrimaryShardStats = new HashMap<>(); // Build a map from index name to primary shard stats for (ClusterStatsNodeResponse r : nodeResponses) { for (ShardStats shardStats : r.shardsStats()) { if (shardStats.getShardRouting().primary()) { indexPrimaryShardStats.compute(shardStats.getShardRouting().getIndexName(), (name, stats) -> { if (stats == null) { List<ShardStats> newStats = new ArrayList<>(); newStats.add(shardStats); return newStats; } else { stats.add(shardStats); return stats; } }); } } } // Loop through all indices in the metadata, building the counts as needed for (ProjectMetadata project : metadata.projects().values()) { for (Map.Entry<String, IndexMetadata> cursor : project.indices().entrySet()) { IndexMetadata indexMetadata = cursor.getValue(); // Increment version-specific index counts indexCounts.merge(indexMetadata.getCreationVersion(), 1, Integer::sum); // Increment version-specific primary shard counts primaryShardCounts.merge(indexMetadata.getCreationVersion(), indexMetadata.getNumberOfShards(), Integer::sum); // Increment version-specific primary shard sizes String indexName = indexMetadata.getIndex().getName(); long indexPrimarySize = indexPrimaryShardStats.getOrDefault(indexName, Collections.emptyList()) .stream() .mapToLong(stats -> stats.getStats().getStore().sizeInBytes()) .sum(); primaryByteCounts.merge(indexMetadata.getCreationVersion(), indexPrimarySize, Long::sum); } } List<SingleVersionStats> calculatedStats = new ArrayList<>(indexCounts.size()); for (Map.Entry<IndexVersion, Integer> indexVersionCount : indexCounts.entrySet()) { IndexVersion v = indexVersionCount.getKey(); SingleVersionStats singleStats = new SingleVersionStats( v, indexVersionCount.getValue(), primaryShardCounts.getOrDefault(v, 0), primaryByteCounts.getOrDefault(v, 0L) ); calculatedStats.add(singleStats); } return new VersionStats(calculatedStats); } VersionStats(Collection<SingleVersionStats> versionStats) { this.versionStats = Collections.unmodifiableSet(new TreeSet<>(versionStats)); } VersionStats(StreamInput in) throws IOException { this.versionStats = Collections.unmodifiableSet(new TreeSet<>(in.readCollectionAsList(SingleVersionStats::new))); } public Set<SingleVersionStats> versionStats() { return this.versionStats; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startArray("versions"); for (SingleVersionStats stat : versionStats) { stat.toXContent(builder, params); } builder.endArray(); return builder; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeCollection(versionStats); } @Override public int hashCode() { return versionStats.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } VersionStats other = (VersionStats) obj; return versionStats.equals(other.versionStats); } @Override public String toString() { return Strings.toString(this); } static
VersionStats
java
apache__camel
components/camel-syslog/src/test/java/org/apache/camel/component/syslog/SyslogEnumsTest.java
{ "start": 952, "end": 2902 }
class ____ { @Test public void testFacilityConstants() { assertEquals("KERN", SyslogFacility.values()[0 >> 3].name()); assertEquals("USER", SyslogFacility.values()[1 >> 3 / 8].name()); assertEquals("MAIL", SyslogFacility.values()[2 >> 3 / 8].name()); assertEquals("DAEMON", SyslogFacility.values()[3 >> 3 / 8].name()); assertEquals("AUTH", SyslogFacility.values()[4 >> 3 / 8].name()); assertEquals("SYSLOG", SyslogFacility.values()[5 >> 3 / 8].name()); assertEquals("LPR", SyslogFacility.values()[6 >> 3 / 8].name()); assertEquals("NEWS", SyslogFacility.values()[7 >> 3 / 8].name()); assertEquals("UUCP", SyslogFacility.values()[8 >> 3 / 8].name()); assertEquals("CRON", SyslogFacility.values()[9 >> 3 / 8].name()); assertEquals("AUTHPRIV", SyslogFacility.values()[10 >> 3 / 8].name()); assertEquals("FTP", SyslogFacility.values()[11 >> 3 / 8].name()); /** * RESERVED_12, RESERVED_13, RESERVED_14, RESERVED_15, */ assertEquals("LOCAL0", SyslogFacility.values()[16 >> 3 / 8].name()); assertEquals("LOCAL1", SyslogFacility.values()[17 >> 3 / 8].name()); assertEquals("LOCAL2", SyslogFacility.values()[18 >> 3 / 8].name()); assertEquals("LOCAL3", SyslogFacility.values()[19 >> 3 / 8].name()); assertEquals("LOCAL4", SyslogFacility.values()[20 >> 3 / 8].name()); assertEquals("LOCAL5", SyslogFacility.values()[21 >> 3 / 8].name()); assertEquals("LOCAL6", SyslogFacility.values()[22 >> 3 / 8].name()); assertEquals("LOCAL7", SyslogFacility.values()[23 >> 3 / 8].name()); } @Test public void testSeverity() { assertEquals("EMERG", SyslogSeverity.values()[0 & 0x07].name()); assertEquals("ALERT", SyslogSeverity.values()[1 & 0x07].name()); assertEquals("DEBUG", SyslogSeverity.values()[7 & 0x07].name()); } }
SyslogEnumsTest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/lucene/read/ValuesSourceReaderOperator.java
{ "start": 1632, "end": 7962 }
class ____ extends AbstractPageMappingToIteratorOperator { /** * Creates a factory for {@link ValuesSourceReaderOperator}. * @param fields fields to load * @param shardContexts per-shard loading information * @param docChannel the channel containing the shard, leaf/segment and doc id */ public record Factory(ByteSizeValue jumboSize, List<FieldInfo> fields, IndexedByShardId<ShardContext> shardContexts, int docChannel) implements OperatorFactory { public Factory { if (fields.isEmpty()) { throw new IllegalStateException("ValuesSourceReaderOperator doesn't support empty fields"); } } @Override public Operator get(DriverContext driverContext) { return new ValuesSourceReaderOperator(driverContext.blockFactory(), jumboSize.getBytes(), fields, shardContexts, docChannel); } @Override public String describe() { StringBuilder sb = new StringBuilder(); sb.append("ValuesSourceReaderOperator[fields = ["); if (fields.size() < 10) { boolean first = true; for (FieldInfo f : fields) { if (first) { first = false; } else { sb.append(", "); } sb.append(f.name); } } else { sb.append(fields.size()).append(" fields"); } return sb.append("]]").toString(); } } /** * Configuration for a field to load. * * @param nullsFiltered if {@code true}, then target docs passed from the source operator are guaranteed to have a value * for the field; otherwise, the guarantee is unknown. This enables optimizations for block loaders, * treating the field as dense (every document has value) even if it is sparse in the index. * For example, "FROM index | WHERE x != null | STATS sum(x)", after filtering out documents * without value for field x, all target documents returned from the source operator * will have a value for field x whether x is dense or sparse in the index. * @param blockLoader maps shard index to the {@link BlockLoader}s which load the actual blocks. */ public record FieldInfo(String name, ElementType type, boolean nullsFiltered, IntFunction<BlockLoader> blockLoader) {} public record ShardContext( IndexReader reader, Function<Set<String>, SourceLoader> newSourceLoader, double storedFieldsSequentialProportion ) {} final BlockFactory blockFactory; /** * When the loaded fields {@link Block}s' estimated size grows larger than this, * we finish loading the {@linkplain Page} and return it, even if * the {@linkplain Page} is shorter than the incoming {@linkplain Page}. * <p> * NOTE: This only applies when loading single segment non-descending * row stride bytes. This is the most common way to get giant fields, * but it isn't all the ways. * </p> */ final long jumboBytes; final FieldWork[] fields; final IndexedByShardId<? extends ShardContext> shardContexts; private final int docChannel; private final Map<String, Integer> readersBuilt = new TreeMap<>(); long valuesLoaded; private int lastShard = -1; private int lastSegment = -1; /** * Creates a new extractor * @param fields fields to load * @param docChannel the channel containing the shard, leaf/segment and doc id */ public ValuesSourceReaderOperator( BlockFactory blockFactory, long jumboBytes, List<FieldInfo> fields, IndexedByShardId<? extends ShardContext> shardContexts, int docChannel ) { if (fields.isEmpty()) { throw new IllegalStateException("ValuesSourceReaderOperator doesn't support empty fields"); } this.blockFactory = blockFactory; this.jumboBytes = jumboBytes; this.fields = fields.stream().map(FieldWork::new).toArray(FieldWork[]::new); this.shardContexts = shardContexts; this.docChannel = docChannel; } @Override protected ReleasableIterator<Page> receive(Page page) { DocVector docVector = page.<DocBlock>getBlock(docChannel).asVector(); return appendBlockArrays( page, docVector.singleSegment() ? new ValuesFromSingleReader(this, docVector) : new ValuesFromManyReader(this, docVector) ); } void positionFieldWork(int shard, int segment, int firstDoc) { if (lastShard == shard) { if (lastSegment == segment) { for (FieldWork w : fields) { w.sameSegment(firstDoc); } return; } lastSegment = segment; for (FieldWork w : fields) { w.sameShardNewSegment(); } return; } lastShard = shard; lastSegment = segment; for (FieldWork w : fields) { w.newShard(shard); } } boolean positionFieldWorkDocGuaranteedAscending(int shard, int segment) { if (lastShard == shard) { if (lastSegment == segment) { return false; } lastSegment = segment; for (FieldWork w : fields) { w.sameShardNewSegment(); } return true; } lastShard = shard; lastSegment = segment; for (FieldWork w : fields) { w.newShard(shard); } return true; } void trackStoredFields(StoredFieldsSpec spec, boolean sequential) { readersBuilt.merge( "stored_fields[" + "requires_source:" + spec.requiresSource() + ", fields:" + spec.requiredStoredFields().size() + ", sequential: " + sequential + "]", 1, (prev, one) -> prev + one ); } protected
ValuesSourceReaderOperator
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/resume/ResumeAdapter.java
{ "start": 1022, "end": 1478 }
class ____ is to bind the component-specific part of the logic to the more generic handling of * the resume strategy. The adapter is always component specific and some components may have more than one. * * It is the responsibility of the supported components to implement the custom implementation for this part of the * resume API, as well as to offer component-specific interfaces that can be specialized by other integrations. */ public
responsibility
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/FieldNameTranslators.java
{ "start": 21823, "end": 23679 }
class ____ implements FieldNameTranslator { private final String indexFieldName; private final String queryFieldName; FlattenedFieldNameTranslator(String indexFieldName, String queryFieldName) { this.indexFieldName = indexFieldName; this.queryFieldName = queryFieldName; } @Override public boolean isQueryFieldSupported(String fieldNameOrPattern) { if (Regex.isSimpleMatchPattern(fieldNameOrPattern)) { // It is not possible to translate a pattern for subfields of a flattened field // (because there's no list of subfields of the flattened field). // But the pattern can still match the flattened field itself. return Regex.simpleMatch(fieldNameOrPattern, queryFieldName); } else { return fieldNameOrPattern.equals(queryFieldName) || fieldNameOrPattern.startsWith(queryFieldName + "."); } } @Override public boolean isIndexFieldSupported(String fieldName) { return fieldName.equals(indexFieldName) || fieldName.startsWith(indexFieldName + "."); } @Override public String translate(String fieldNameOrPattern) { if (Regex.isSimpleMatchPattern(fieldNameOrPattern) || fieldNameOrPattern.equals(queryFieldName)) { // the pattern can only refer to the flattened field itself, not to its subfields return indexFieldName; } else { assert fieldNameOrPattern.startsWith(queryFieldName + "."); return indexFieldName + fieldNameOrPattern.substring(queryFieldName.length()); } } @Override public boolean isSortSupported() { return true; } } }
FlattenedFieldNameTranslator
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java
{ "start": 41224, "end": 41847 }
class ____ extends CommonSecurityFilterChainConfig { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .oauth2Login(withDefaults()); // @formatter:on return super.configureFilterChain(http); } @Bean ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(GOOGLE_CLIENT_REGISTRATION); } @Bean GrantedAuthoritiesMapper grantedAuthoritiesMapper() { return createGrantedAuthoritiesMapper(); } } @Configuration @EnableWebSecurity static
OAuth2LoginConfigCustomWithBeanRegistration
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/runtime/AbstractGenericTypeSerializerTest.java
{ "start": 13070, "end": 13894 }
class ____ { private long authorId; private List<String> bookTitles; private String authorName; public BookAuthor() {} public BookAuthor(long authorId, List<String> bookTitles, String authorName) { this.authorId = authorId; this.bookTitles = bookTitles; this.authorName = authorName; } @Override public boolean equals(Object obj) { if (obj.getClass() == BookAuthor.class) { BookAuthor other = (BookAuthor) obj; return other.authorName.equals(this.authorName) && other.authorId == this.authorId && other.bookTitles.equals(this.bookTitles); } else { return false; } } } }
BookAuthor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/idclass/IdClassTest.java
{ "start": 899, "end": 3639 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { PK pk = new PK( "Linux", "admin", 1 ); SystemUser systemUser = new SystemUser(); systemUser.setId( pk ); systemUser.setName( "Andrea" ); session.persist( systemUser ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testGet(SessionFactoryScope scope) { SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); statementInspector.clear(); scope.inTransaction( session -> { PK pk = new PK( "Linux", "admin", 1 ); SystemUser systemUser = session.get( SystemUser.class, pk ); assertThat( systemUser.getName(), is( "Andrea" ) ); assertThat( systemUser.getSubsystem(), is( "Linux" ) ); assertThat( systemUser.getUsername(), is( "admin" ) ); assertThat( systemUser.getRegistrationId(), is( 1 ) ); statementInspector.assertExecutedCount( 1 ); statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 0 ); } ); } @Test public void testHql(SessionFactoryScope scope) { SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); statementInspector.clear(); scope.inTransaction( session -> { PK pk = new PK( "Linux", "admin", 1 ); SystemUser systemUser = session.createQuery( "from SystemUser s where s.id = :id", SystemUser.class ).setParameter( "id", pk ).getSingleResult(); assertThat( systemUser.getName(), is( "Andrea" ) ); assertThat( systemUser.getSubsystem(), is( "Linux" ) ); assertThat( systemUser.getUsername(), is( "admin" ) ); assertThat( systemUser.getRegistrationId(), is( 1 ) ); statementInspector.assertExecutedCount( 1 ); statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 0 ); } ); statementInspector.clear(); scope.inTransaction( session -> { SystemUser systemUser = session.createQuery( "from SystemUser s where s.username = :username", SystemUser.class ).setParameter( "username", "admin" ).getSingleResult(); assertThat( systemUser.getName(), is( "Andrea" ) ); assertThat( systemUser.getSubsystem(), is( "Linux" ) ); assertThat( systemUser.getUsername(), is( "admin" ) ); assertThat( systemUser.getRegistrationId(), is( 1 ) ); statementInspector.assertExecutedCount( 1 ); statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 0 ); } ); } @Entity(name = "SystemUser") @IdClass(PK.class) public static
IdClassTest
java
greenrobot__EventBus
EventBusTestJava/src/main/java/org/greenrobot/eventbus/EventBusBuilderTest.java
{ "start": 2746, "end": 2926 }
class ____ { @Subscribe public void onEvent(SubscriberExceptionEvent event) { trackEvent(event); } } public
SubscriberExceptionEventTracker
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/vld/ValidatePolymSubTypeTest.java
{ "start": 1708, "end": 1919 }
class ____ { public BaseValue value; protected DefTypeWrapper() { } public DefTypeWrapper(BaseValue v) { value = v; } } // // // Validator implementations static
DefTypeWrapper
java
netty__netty
testsuite-http2/src/main/java/io/netty/testsuite/http2/HelloWorldHttp1Handler.java
{ "start": 1695, "end": 3305 }
class ____ extends SimpleChannelInboundHandler<FullHttpRequest> { private final String establishApproach; HelloWorldHttp1Handler(String establishApproach) { this.establishApproach = checkNotNull(establishApproach, "establishApproach"); } @Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, ctx.alloc().buffer(0))); } boolean keepAlive = HttpUtil.isKeepAlive(req); ByteBuf content = ctx.alloc().buffer(); content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate()); ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")"); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
HelloWorldHttp1Handler
java
netty__netty
handler/src/test/java/io/netty/handler/logging/LoggingHandlerTest.java
{ "start": 12437, "end": 12740 }
class ____ extends EmbeddedChannel { private DisconnectingEmbeddedChannel(ChannelHandler... handlers) { super(handlers); } @Override public ChannelMetadata metadata() { return new ChannelMetadata(true); } } }
DisconnectingEmbeddedChannel
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/codec/FastjsonManualCodec.java
{ "start": 5299, "end": 6857 }
class ____ implements ObjectSerializer { MediaSerializer mediaSer = new MediaSerializer(); ImageSerializer imageSer = new ImageSerializer(); @Override public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { MediaContent mediaContent = (MediaContent) object; SerializeWriter out = serializer.out; out.write('{'); out.writeFieldName("image", false); List<Image> images = mediaContent.images; out.write('['); for (int i = 0, size = images.size(); i < size; ++i) { if (i != 0) { out.write(','); } Image image = images.get(i); imageSer.write(serializer, image, Integer.valueOf(i), Image.class, features); } out.write(']'); out.write(','); out.writeFieldName("media", false); mediaSer.write(serializer, mediaContent.media, "media", Media.class, features); out.write('}'); } } @Override public byte[] encodeToBytes(Object object) throws Exception { // TODO Auto-generated method stub return null; } @Override public void encode(OutputStream out, Object object) throws Exception { out.write(encodeToBytes(object)); } }
MediaContentSerializer
java
qos-ch__slf4j
slf4j-api/src/main/java/org/slf4j/helpers/Slf4jEnvUtil.java
{ "start": 1308, "end": 2495 }
class ____ { /** * Returns the current version of slf4j, or null if data is not available. * * @return current version or null if missing version data * @since 2.0.14 */ static public String slf4jVersion() { // String moduleVersion = slf4jVersionByModule(); // if(moduleVersion != null) // return moduleVersion; Package pkg = Slf4jEnvUtil.class.getPackage(); if(pkg == null) { return null; } final String pkgVersion = pkg.getImplementationVersion(); return pkgVersion; } /** * Returns the current version of slf4j via class.getModule() * or null if data is not available. * * @return current version or null if missing version data * @since 2.0.14 */ // static private String slf4jVersionByModule() { // Module module = Slf4jEnvUtil.class.getModule(); // if (module == null) // return null; // // ModuleDescriptor md = module.getDescriptor(); // if (md == null) // return null; // Optional<String> opt = md.rawVersion(); // return opt.orElse(null); // } }
Slf4jEnvUtil
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/proxy/LazyLoader.java
{ "start": 718, "end": 1142 }
interface ____ extends Callback { /** * Return the object which the original method invocation should be * dispatched. Called as soon as the first lazily-loaded method in * the enhanced instance is invoked. The same object is then used * for every future method call to the proxy instance. * @return an object that can invoke the method */ Object loadObject() throws Exception; }
LazyLoader