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
micronaut-projects__micronaut-core
http-client-core/src/main/java/io/micronaut/http/client/HttpClientRegistry.java
{ "start": 1095, "end": 3295 }
interface ____<T extends HttpClient> { /** * Return the client for the given annotation metadata. * * @param annotationMetadata The annotation metadata. * @return The client */ @NonNull T getClient(@NonNull AnnotationMetadata annotationMetadata); /** * Return the client for the client ID and path. * * @param httpVersion The HTTP version * @param clientId The client ID * @param path The path (Optional) * @return The client * @deprecated Use {@link #getClient(HttpVersionSelection, String, String)} instead */ @Deprecated @NonNull default T getClient(HttpVersion httpVersion, @NonNull String clientId, @Nullable String path) { return getClient(HttpVersionSelection.forLegacyVersion(httpVersion), clientId, path); } /** * Return the client for the client ID and path. * * @param httpVersion The HTTP version * @param clientId The client ID * @param path The path (Optional) * @return The client * @since 4.0.0 */ @NonNull T getClient(@NonNull HttpVersionSelection httpVersion, @NonNull String clientId, @Nullable String path); /** * Resolves a {@link HttpClient} for the given injection point. * * @param injectionPoint The injection point * @param loadBalancer The load balancer to use (Optional) * @param configuration The configuration (Optional) * @param beanContext The bean context to use * @return The HTTP Client */ @NonNull T resolveClient(@Nullable InjectionPoint<?> injectionPoint, @Nullable LoadBalancer loadBalancer, @Nullable HttpClientConfiguration configuration, @NonNull BeanContext beanContext); /** * Dispose of the client defined by the given metadata. * * @param annotationMetadata The annotation metadata */ void disposeClient(AnnotationMetadata annotationMetadata); /** * @return Return the default HTTP client. */ default T getDefaultClient() { return getClient(AnnotationMetadata.EMPTY_METADATA); } }
HttpClientRegistry
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/vectors/DenseVectorFieldMapper.java
{ "start": 104649, "end": 109570 }
class ____ extends QuantizedIndexOptions { final int clusterSize; final double defaultVisitPercentage; final boolean onDiskRescore; BBQIVFIndexOptions(int clusterSize, double defaultVisitPercentage, boolean onDiskRescore, RescoreVector rescoreVector) { super(VectorIndexType.BBQ_DISK, rescoreVector); this.clusterSize = clusterSize; this.defaultVisitPercentage = defaultVisitPercentage; this.onDiskRescore = onDiskRescore; } @Override KnnVectorsFormat getVectorsFormat(ElementType elementType) { assert elementType == ElementType.FLOAT || elementType == ElementType.BFLOAT16; if (Build.current().isSnapshot()) { return new ESNextDiskBBQVectorsFormat( ESNextDiskBBQVectorsFormat.QuantEncoding.ONE_BIT_4BIT_QUERY, clusterSize, ES920DiskBBQVectorsFormat.DEFAULT_CENTROIDS_PER_PARENT_CLUSTER, elementType, onDiskRescore ); } return new ES920DiskBBQVectorsFormat( clusterSize, ES920DiskBBQVectorsFormat.DEFAULT_CENTROIDS_PER_PARENT_CLUSTER, elementType, onDiskRescore ); } @Override public boolean updatableTo(DenseVectorIndexOptions update) { return update.type.equals(this.type); } @Override boolean doEquals(DenseVectorIndexOptions other) { BBQIVFIndexOptions that = (BBQIVFIndexOptions) other; return clusterSize == that.clusterSize && defaultVisitPercentage == that.defaultVisitPercentage && onDiskRescore == that.onDiskRescore && Objects.equals(rescoreVector, that.rescoreVector); } @Override int doHashCode() { return Objects.hash(clusterSize, defaultVisitPercentage, onDiskRescore, rescoreVector); } @Override public boolean isFlat() { return false; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field("type", type); builder.field("cluster_size", clusterSize); builder.field("default_visit_percentage", defaultVisitPercentage); if (onDiskRescore) { builder.field("on_disk_rescore", true); } if (rescoreVector != null) { rescoreVector.toXContent(builder, params); } builder.endObject(); return builder; } } public record RescoreVector(float oversample) implements ToXContentObject { static final String NAME = "rescore_vector"; static final String OVERSAMPLE = "oversample"; static RescoreVector fromIndexOptions(Map<String, ?> indexOptionsMap, IndexVersion indexVersion) { Object rescoreVectorNode = indexOptionsMap.remove(NAME); if (rescoreVectorNode == null) { return null; } Map<String, Object> mappedNode = XContentMapValues.nodeMapValue(rescoreVectorNode, NAME); Object oversampleNode = mappedNode.get(OVERSAMPLE); if (oversampleNode == null) { throw new IllegalArgumentException("Invalid rescore_vector value. Missing required field " + OVERSAMPLE); } float oversampleValue = (float) XContentMapValues.nodeDoubleValue(oversampleNode); if (oversampleValue == 0 && allowsZeroRescore(indexVersion) == false) { throw new IllegalArgumentException("oversample must be greater than 1"); } if (oversampleValue < 1 && oversampleValue != 0) { throw new IllegalArgumentException("oversample must be greater than 1 or exactly 0"); } else if (oversampleValue > 10) { throw new IllegalArgumentException("oversample must be less than or equal to 10"); } return new RescoreVector(oversampleValue); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(NAME); builder.field(OVERSAMPLE, oversample); builder.endObject(); return builder; } } public static final TypeParser PARSER = new TypeParser( (n, c) -> new Builder( n, c.getIndexSettings().getIndexVersionCreated(), INDEX_MAPPING_EXCLUDE_SOURCE_VECTORS_SETTING.get(c.getIndexSettings().getSettings()), c.getVectorsFormatProviders() ), notInMultiFields(CONTENT_TYPE) ); public static final
BBQIVFIndexOptions
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/JobConfigInfo.java
{ "start": 5377, "end": 6626 }
class ____ extends StdDeserializer<JobConfigInfo> { private static final long serialVersionUID = -3580088509877177213L; public Deserializer() { super(JobConfigInfo.class); } @Override public JobConfigInfo deserialize( JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { JsonNode rootNode = jsonParser.readValueAsTree(); final JobID jobId = JobID.fromHexString(rootNode.get(FIELD_NAME_JOB_ID).asText()); final String jobName = rootNode.get(FIELD_NAME_JOB_NAME).asText(); final ExecutionConfigInfo executionConfigInfo; if (rootNode.has(FIELD_NAME_EXECUTION_CONFIG)) { executionConfigInfo = RestMapperUtils.getStrictObjectMapper() .treeToValue( rootNode.get(FIELD_NAME_EXECUTION_CONFIG), ExecutionConfigInfo.class); } else { executionConfigInfo = null; } return new JobConfigInfo(jobId, jobName, executionConfigInfo); } } /** Nested
Deserializer
java
quarkusio__quarkus
extensions/smallrye-graphql-client/deployment/src/test/java/io/quarkus/smallrye/graphql/client/deployment/TypesafeGraphQLClientProgrammaticUsageTest.java
{ "start": 784, "end": 1593 }
class ____ { @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(TestingGraphQLApi.class, TestingGraphQLClientApi.class, Person.class, PersonDto.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")); @TestHTTPResource URL url; @Test public void performQuery() { TestingGraphQLClientApi client = TypesafeGraphQLClientBuilder.newBuilder().endpoint(url.toString() + "/graphql") .build(TestingGraphQLClientApi.class); List<Person> people = client.people(); assertEquals("John", people.get(0).getFirstName()); assertEquals("Arthur", people.get(1).getFirstName()); } }
TypesafeGraphQLClientProgrammaticUsageTest
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/Verticle.java
{ "start": 1322, "end": 2741 }
interface ____ extends Deployable { /** * Get a reference to the Vert.x instance that deployed this verticle * * @return A reference to the Vert.x instance */ Vertx getVertx(); /** * Initialise the verticle with the Vert.x instance and the context. * <p> * This method is called by Vert.x when the instance is deployed. You do not call it yourself. * * @param vertx the Vert.x instance * @param context the context */ void init(Vertx vertx, Context context); /** * Start the verticle instance. * <p> * Vert.x calls this method when deploying the instance. You do not call it yourself. * <p> * A promise is passed into the method, and when deployment is complete the verticle should either call * {@link io.vertx.core.Promise#complete} or {@link io.vertx.core.Promise#fail} the future. * * @param startPromise the future */ void start(Promise<Void> startPromise) throws Exception; /** * Stop the verticle instance. * <p> * Vert.x calls this method when un-deploying the instance. You do not call it yourself. * <p> * A promise is passed into the method, and when un-deployment is complete the verticle should either call * {@link io.vertx.core.Promise#complete} or {@link io.vertx.core.Promise#fail} the future. * * @param stopPromise the future */ void stop(Promise<Void> stopPromise) throws Exception; }
Verticle
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmManager.java
{ "start": 1840, "end": 1965 }
class ____ exposing the Maven 4 API. This is basically a restricted view on the Maven core realm. * * @return The
realm
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/FenceProducersOptions.java
{ "start": 965, "end": 1202 }
class ____ extends AbstractOptions<FenceProducersOptions> { @Override public String toString() { return "FenceProducersOptions{" + "timeoutMs=" + timeoutMs + '}'; } }
FenceProducersOptions
java
spring-projects__spring-framework
spring-core/src/testFixtures/java/org/springframework/core/testfixture/aot/generator/visibility/PublicFactoryBean.java
{ "start": 754, "end": 1127 }
class ____<T> { PublicFactoryBean(Class<T> type) { } public static PublicFactoryBean<ProtectedType> protectedTypeFactoryBean() { return new PublicFactoryBean<>(ProtectedType.class); } public static ResolvableType resolveToProtectedGenericParameter() { return ResolvableType.forClassWithGenerics(PublicFactoryBean.class, ProtectedType.class); } }
PublicFactoryBean
java
elastic__elasticsearch
x-pack/plugin/analytics/src/main/java/org/elasticsearch/xpack/analytics/mapper/TDigestBlockLoader.java
{ "start": 2290, "end": 5414 }
class ____ implements AllReader { private final AllReader encodedDigestReader; private final AllReader minimaReader; private final AllReader maximaReader; private final AllReader sumsReader; private final AllReader valueCountsReader; TDigestReader( AllReader encodedDigestReader, AllReader minimaReader, AllReader maximaReader, AllReader sumsReader, AllReader valueCountsReader ) { this.encodedDigestReader = encodedDigestReader; this.minimaReader = minimaReader; this.maximaReader = maximaReader; this.sumsReader = sumsReader; this.valueCountsReader = valueCountsReader; } @Override public boolean canReuse(int startingDocID) { return minimaReader.canReuse(startingDocID) && maximaReader.canReuse(startingDocID) && sumsReader.canReuse(startingDocID) && valueCountsReader.canReuse(startingDocID) && encodedDigestReader.canReuse(startingDocID); } @Override // Column oriented reader public Block read(BlockFactory factory, Docs docs, int offset, boolean nullsFiltered) throws IOException { Block minima = null; Block maxima = null; Block sums = null; Block valueCounts = null; Block encodedBytes = null; Block result; boolean success = false; try { minima = minimaReader.read(factory, docs, offset, nullsFiltered); maxima = maximaReader.read(factory, docs, offset, nullsFiltered); sums = sumsReader.read(factory, docs, offset, nullsFiltered); valueCounts = valueCountsReader.read(factory, docs, offset, nullsFiltered); encodedBytes = encodedDigestReader.read(factory, docs, offset, nullsFiltered); result = factory.buildTDigestBlockDirect(encodedBytes, minima, maxima, sums, valueCounts); success = true; } finally { if (success == false) { Releasables.close(minima, maxima, sums, valueCounts, encodedBytes); } } return result; } @Override public void read(int docId, StoredFields storedFields, Builder builder) throws IOException { ExponentialHistogramBuilder histogramBuilder = (ExponentialHistogramBuilder) builder; minimaReader.read(docId, storedFields, histogramBuilder.minima()); maximaReader.read(docId, storedFields, histogramBuilder.maxima()); sumsReader.read(docId, storedFields, histogramBuilder.sums()); valueCountsReader.read(docId, storedFields, histogramBuilder.valueCounts()); encodedDigestReader.read(docId, storedFields, histogramBuilder.encodedHistograms()); } @Override public String toString() { return "BlockDocValuesReader.TDigest"; } } }
TDigestReader
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/GoogleBigqueryComponentBuilderFactory.java
{ "start": 1390, "end": 1914 }
interface ____ { /** * Google BigQuery (camel-google-bigquery) * Google BigQuery data warehouse for analytics. * * Category: cloud,bigdata * Since: 2.20 * Maven coordinates: org.apache.camel:camel-google-bigquery * * @return the dsl builder */ static GoogleBigqueryComponentBuilder googleBigquery() { return new GoogleBigqueryComponentBuilderImpl(); } /** * Builder for the Google BigQuery component. */
GoogleBigqueryComponentBuilderFactory
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/TimeoutOptions.java
{ "start": 810, "end": 3010 }
class ____ implements Serializable { public static final Duration DISABLED_TIMEOUT = Duration.ZERO.minusSeconds(1); public static final boolean DEFAULT_TIMEOUT_COMMANDS = false; public static final Duration DEFAULT_RELAXED_TIMEOUT = Duration.ofSeconds(10); private final boolean timeoutCommands; private final boolean applyConnectionTimeout; private final Duration relaxedTimeout; private final TimeoutSource source; private TimeoutOptions(boolean timeoutCommands, boolean applyConnectionTimeout, TimeoutSource source, Duration relaxedTimeout) { this.timeoutCommands = timeoutCommands; this.applyConnectionTimeout = applyConnectionTimeout; this.relaxedTimeout = relaxedTimeout; this.source = source; } /** * Returns a new {@link TimeoutOptions.Builder} to construct {@link TimeoutOptions}. * * @return a new {@link TimeoutOptions.Builder} to construct {@link TimeoutOptions}. */ public static Builder builder() { return new Builder(); } /** * Create a new instance of {@link TimeoutOptions} with default settings. * * @return a new instance of {@link TimeoutOptions} with default settings. */ public static TimeoutOptions create() { return builder().build(); } /** * Create a new instance of {@link TimeoutOptions} with enabled timeout applying default connection timeouts. * * @return a new instance of {@link TimeoutOptions} with enabled timeout applying default connection timeouts. */ public static TimeoutOptions enabled() { return builder().timeoutCommands().connectionTimeout().build(); } /** * Create a new instance of {@link TimeoutOptions} with enabled timeout applying a fixed {@link Duration timeout}. * * @return a new instance of {@link TimeoutOptions} with enabled timeout applying a fixed {@link Duration timeout}. */ public static TimeoutOptions enabled(Duration timeout) { return builder().timeoutCommands().fixedTimeout(timeout).build(); } /** * Builder for {@link TimeoutOptions}. */ public static
TimeoutOptions
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/client/samples/matchers/JsonPathRequestMatchersIntegrationTests.java
{ "start": 2185, "end": 6644 }
class ____ { private static final MultiValueMap<String, Person> people = new LinkedMultiValueMap<>(); static { people.add("composers", new Person("Johann Sebastian Bach")); people.add("composers", new Person("Johannes Brahms")); people.add("composers", new Person("Edvard Grieg")); people.add("composers", new Person("Robert Schumann")); people.add("performers", new Person("Vladimir Ashkenazy")); people.add("performers", new Person("Yehudi Menuhin")); } private final RestTemplate restTemplate = new RestTemplate(Collections.singletonList(new JacksonJsonHttpMessageConverter())); private final MockRestServiceServer mockServer = MockRestServiceServer.createServer(this.restTemplate); @Test void exists() { this.mockServer.expect(requestTo("/composers")) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.composers[0]").exists()) .andExpect(jsonPath("$.composers[1]").exists()) .andExpect(jsonPath("$.composers[2]").exists()) .andExpect(jsonPath("$.composers[3]").exists()) .andRespond(withSuccess()); executeAndVerify(); } @Test void doesNotExist() { this.mockServer.expect(requestTo("/composers")) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.composers[?(@.name == 'Edvard Grieeeeeeg')]").doesNotExist()) .andExpect(jsonPath("$.composers[?(@.name == 'Robert Schuuuuuuman')]").doesNotExist()) .andExpect(jsonPath("$.composers[4]").doesNotExist()) .andRespond(withSuccess()); executeAndVerify(); } @Test void value() { this.mockServer.expect(requestTo("/composers")) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.composers[0].name").value("Johann Sebastian Bach")) .andExpect(jsonPath("$.performers[1].name").value("Yehudi Menuhin")) .andRespond(withSuccess()); executeAndVerify(); } @Test void hamcrestMatchers() { this.mockServer.expect(requestTo("/composers")) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.composers[0].name").value(equalTo("Johann Sebastian Bach"))) .andExpect(jsonPath("$.performers[1].name").value(equalTo("Yehudi Menuhin"))) .andExpect(jsonPath("$.composers[0].name", startsWith("Johann"))) .andExpect(jsonPath("$.performers[0].name", endsWith("Ashkenazy"))) .andExpect(jsonPath("$.performers[1].name", containsString("di Me"))) .andExpect(jsonPath("$.composers[1].name", is(in(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))))) .andExpect(jsonPath("$.composers[:3].name", hasItem("Johannes Brahms"))) .andRespond(withSuccess()); executeAndVerify(); } @Test void hamcrestMatchersWithParameterizedJsonPaths() { String composerName = "$.composers[%s].name"; String performerName = "$.performers[%s].name"; this.mockServer.expect(requestTo("/composers")) .andExpect(content().contentType("application/json")) .andExpect(jsonPath(composerName, 0).value(startsWith("Johann"))) .andExpect(jsonPath(performerName, 0).value(endsWith("Ashkenazy"))) .andExpect(jsonPath(performerName, 1).value(containsString("di Me"))) .andExpect(jsonPath(composerName, 1).value(is(in(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))))) .andRespond(withSuccess()); executeAndVerify(); } @Test void isArray() { this.mockServer.expect(requestTo("/composers")) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.composers").isArray()) .andRespond(withSuccess()); executeAndVerify(); } @Test void isString() { this.mockServer.expect(requestTo("/composers")) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.composers[0].name").isString()) .andRespond(withSuccess()); executeAndVerify(); } @Test void isNumber() { this.mockServer.expect(requestTo("/composers")) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.composers[0].someDouble").isNumber()) .andRespond(withSuccess()); executeAndVerify(); } @Test void isBoolean() { this.mockServer.expect(requestTo("/composers")) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.composers[0].someBoolean").isBoolean()) .andRespond(withSuccess()); executeAndVerify(); } private void executeAndVerify() { this.restTemplate.put(URI.create("/composers"), people); this.mockServer.verify(); } }
JsonPathRequestMatchersIntegrationTests
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/convention/TestBeanByNameLookupTestClassScopedExtensionContextIntegrationTests.java
{ "start": 1680, "end": 3055 }
class ____ { @TestBean(name = "field") String field; @TestBean(name = "methodRenamed1", methodName = "field") String methodRenamed1; @TestBean("prototypeScoped") String prototypeScoped; static String field() { return "fieldOverride"; } static String nestedField() { return "nestedFieldOverride"; } static String prototypeScoped() { return "prototypeScopedOverride"; } @Test void fieldHasOverride(ApplicationContext ctx) { assertThat(ctx.getBean("field")).as("applicationContext").isEqualTo("fieldOverride"); assertThat(field).as("injection point").isEqualTo("fieldOverride"); } @Test void fieldWithMethodNameHasOverride(ApplicationContext ctx) { assertThat(ctx.getBean("methodRenamed1")).as("applicationContext").isEqualTo("fieldOverride"); assertThat(methodRenamed1).as("injection point").isEqualTo("fieldOverride"); } @Test void fieldForPrototypeHasOverride(ConfigurableApplicationContext ctx) { assertThat(ctx.getBeanFactory().getBeanDefinition("prototypeScoped").isSingleton()).as("isSingleton").isTrue(); assertThat(ctx.getBean("prototypeScoped")).as("applicationContext").isEqualTo("prototypeScopedOverride"); assertThat(prototypeScoped).as("injection point").isEqualTo("prototypeScopedOverride"); } @Nested @DisplayName("With @TestBean in enclosing
TestBeanByNameLookupTestClassScopedExtensionContextIntegrationTests
java
apache__flink
flink-clients/src/main/java/org/apache/flink/client/deployment/application/WebSubmissionJobClient.java
{ "start": 1656, "end": 3446 }
class ____ implements JobClient { private final JobID jobId; public WebSubmissionJobClient(final JobID jobId) { this.jobId = checkNotNull(jobId); } @Override public JobID getJobID() { return jobId; } @Override public CompletableFuture<JobStatus> getJobStatus() { throw new FlinkRuntimeException( "The Job Status cannot be requested when in Web Submission."); } @Override public CompletableFuture<Void> cancel() { throw new FlinkRuntimeException( "Cancelling the job is not supported by the Job Client when in Web Submission."); } @Override public CompletableFuture<String> stopWithSavepoint( boolean advanceToEndOfEventTime, @Nullable String savepointDirectory, SavepointFormatType formatType) { throw new FlinkRuntimeException( "Stop with Savepoint is not supported by the Job Client when in Web Submission."); } @Override public CompletableFuture<String> triggerSavepoint( @Nullable String savepointDirectory, SavepointFormatType formatType) { throw new FlinkRuntimeException( "A savepoint cannot be taken through the Job Client when in Web Submission."); } @Override public CompletableFuture<Map<String, Object>> getAccumulators() { throw new FlinkRuntimeException( "The Accumulators cannot be fetched through the Job Client when in Web Submission."); } @Override public CompletableFuture<JobExecutionResult> getJobExecutionResult() { throw new FlinkRuntimeException( "The Job Result cannot be fetched through the Job Client when in Web Submission."); } }
WebSubmissionJobClient
java
apache__camel
components/camel-wordpress/src/test/java/org/apache/camel/component/wordpress/api/test/WordpressMockServerTestSupport.java
{ "start": 1317, "end": 4668 }
class ____ { protected static HttpServer localServer; protected static WordpressServiceProvider serviceProvider; private static final Logger LOGGER = LoggerFactory.getLogger(WordpressMockServerTestSupport.class); private static final int PORT = 9009; public WordpressMockServerTestSupport() { } @BeforeAll public static void setUpMockServer() throws IOException { // @formatter:off int i = 0; while (true) { try { localServer = createServer(PORT + i); localServer.start(); break; } catch (BindException ex) { LOGGER.warn("Port {} already in use, trying next one", PORT + i); i++; } } serviceProvider = WordpressServiceProvider.getInstance(); serviceProvider.init(getServerBaseUrl()); // @formatter:on LOGGER.info("Local server up and running on address {} and port {}", localServer.getInetAddress(), localServer.getLocalPort()); } private static HttpServer createServer(int port) { final Map<String, String> postsListCreateRequestHandlers = new HashMap<>(); postsListCreateRequestHandlers.put("GET", "/data/posts/list.json"); postsListCreateRequestHandlers.put("POST", "/data/posts/create.json"); final Map<String, String> postsSingleUpdateRequestHandlers = new HashMap<>(); postsSingleUpdateRequestHandlers.put("GET", "/data/posts/single.json"); postsSingleUpdateRequestHandlers.put("POST", "/data/posts/update.json"); postsSingleUpdateRequestHandlers.put("DELETE", "/data/posts/delete.json"); final Map<String, String> usersListCreateRequestHandlers = new HashMap<>(); usersListCreateRequestHandlers.put("GET", "/data/users/list.json"); usersListCreateRequestHandlers.put("POST", "/data/users/create.json"); final Map<String, String> usersSingleUpdateRequestHandlers = new HashMap<>(); usersSingleUpdateRequestHandlers.put("GET", "/data/users/single.json"); usersSingleUpdateRequestHandlers.put("POST", "/data/users/update.json"); usersSingleUpdateRequestHandlers.put("DELETE", "/data/users/delete.json"); // @formatter:off return ServerBootstrap.bootstrap().setCanonicalHostName("localhost").setListenerPort(port) .register("/wp/v2/posts", new WordpressServerHttpRequestHandler(postsListCreateRequestHandlers)) .register("/wp/v2/posts/*", new WordpressServerHttpRequestHandler(postsSingleUpdateRequestHandlers)) .register("/wp/v2/users", new WordpressServerHttpRequestHandler(usersListCreateRequestHandlers)) .register("/wp/v2/users/*", new WordpressServerHttpRequestHandler(usersSingleUpdateRequestHandlers)) .create(); // @formatter:on } @AfterAll public static void tearDownMockServer() { LOGGER.info("Stopping local server"); if (localServer != null) { localServer.stop(); } } public static WordpressServiceProvider getServiceProvider() { return serviceProvider; } public static String getServerBaseUrl() { return "http://localhost:" + localServer.getLocalPort(); } }
WordpressMockServerTestSupport
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/vectors/es816/ES816BinaryQuantizedVectorsReader.java
{ "start": 2881, "end": 15334 }
class ____ extends FlatVectorsReader { private static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(ES816BinaryQuantizedVectorsReader.class); private final Map<String, FieldEntry> fields = new HashMap<>(); private final IndexInput quantizedVectorData; private final FlatVectorsReader rawVectorsReader; private final ES816BinaryFlatVectorsScorer vectorScorer; @SuppressWarnings("this-escape") ES816BinaryQuantizedVectorsReader( SegmentReadState state, FlatVectorsReader rawVectorsReader, ES816BinaryFlatVectorsScorer vectorsScorer ) throws IOException { super(vectorsScorer); this.vectorScorer = vectorsScorer; this.rawVectorsReader = rawVectorsReader; int versionMeta = -1; String metaFileName = IndexFileNames.segmentFileName( state.segmentInfo.name, state.segmentSuffix, ES816BinaryQuantizedVectorsFormat.META_EXTENSION ); boolean success = false; try (ChecksumIndexInput meta = state.directory.openChecksumInput(metaFileName)) { Throwable priorE = null; try { versionMeta = CodecUtil.checkIndexHeader( meta, ES816BinaryQuantizedVectorsFormat.META_CODEC_NAME, ES816BinaryQuantizedVectorsFormat.VERSION_START, ES816BinaryQuantizedVectorsFormat.VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix ); readFields(meta, state.fieldInfos); } catch (Throwable exception) { priorE = exception; } finally { CodecUtil.checkFooter(meta, priorE); } quantizedVectorData = openDataInput( state, versionMeta, ES816BinaryQuantizedVectorsFormat.VECTOR_DATA_EXTENSION, ES816BinaryQuantizedVectorsFormat.VECTOR_DATA_CODEC_NAME, // Quantized vectors are accessed randomly from their node ID stored in the HNSW // graph. state.context.withHints(FileTypeHint.DATA, FileDataHint.KNN_VECTORS, DataAccessHint.RANDOM) ); success = true; } finally { if (success == false) { IOUtils.closeWhileHandlingException(this); } } } private void readFields(ChecksumIndexInput meta, FieldInfos infos) throws IOException { for (int fieldNumber = meta.readInt(); fieldNumber != -1; fieldNumber = meta.readInt()) { FieldInfo info = infos.fieldInfo(fieldNumber); if (info == null) { throw new CorruptIndexException("Invalid field number: " + fieldNumber, meta); } FieldEntry fieldEntry = readField(meta, info); validateFieldEntry(info, fieldEntry); fields.put(info.name, fieldEntry); } } static void validateFieldEntry(FieldInfo info, FieldEntry fieldEntry) { int dimension = info.getVectorDimension(); if (dimension != fieldEntry.dimension) { throw new IllegalStateException( "Inconsistent vector dimension for field=\"" + info.name + "\"; " + dimension + " != " + fieldEntry.dimension ); } int binaryDims = BQVectorUtils.discretize(dimension, 64) / 8; int correctionsCount = fieldEntry.similarityFunction != VectorSimilarityFunction.EUCLIDEAN ? 3 : 2; long numQuantizedVectorBytes = Math.multiplyExact((binaryDims + (Float.BYTES * correctionsCount)), (long) fieldEntry.size); if (numQuantizedVectorBytes != fieldEntry.vectorDataLength) { throw new IllegalStateException( "Binarized vector data length " + fieldEntry.vectorDataLength + " not matching size = " + fieldEntry.size + " * (binaryBytes=" + binaryDims + " + 8" + ") = " + numQuantizedVectorBytes ); } } @Override public RandomVectorScorer getRandomVectorScorer(String field, float[] target) throws IOException { FieldEntry fi = fields.get(field); if (fi == null || fi.size() == 0) { return null; } return vectorScorer.getRandomVectorScorer( fi.similarityFunction, OffHeapBinarizedVectorValues.load( fi.ordToDocDISIReaderConfiguration, fi.dimension, fi.size, new BinaryQuantizer(fi.dimension, fi.descritizedDimension, fi.similarityFunction), fi.similarityFunction, vectorScorer, fi.centroid, fi.centroidDP, fi.vectorDataOffset, fi.vectorDataLength, quantizedVectorData ), target ); } @Override public RandomVectorScorer getRandomVectorScorer(String field, byte[] target) throws IOException { return rawVectorsReader.getRandomVectorScorer(field, target); } @Override public void checkIntegrity() throws IOException { rawVectorsReader.checkIntegrity(); CodecUtil.checksumEntireFile(quantizedVectorData); } @Override public FloatVectorValues getFloatVectorValues(String field) throws IOException { FieldEntry fi = fields.get(field); if (fi == null) { return null; } if (fi.vectorEncoding != VectorEncoding.FLOAT32) { throw new IllegalArgumentException( "field=\"" + field + "\" is encoded as: " + fi.vectorEncoding + " expected: " + VectorEncoding.FLOAT32 ); } OffHeapBinarizedVectorValues bvv = OffHeapBinarizedVectorValues.load( fi.ordToDocDISIReaderConfiguration, fi.dimension, fi.size, new BinaryQuantizer(fi.dimension, fi.descritizedDimension, fi.similarityFunction), fi.similarityFunction, vectorScorer, fi.centroid, fi.centroidDP, fi.vectorDataOffset, fi.vectorDataLength, quantizedVectorData ); return new BinarizedVectorValues(rawVectorsReader.getFloatVectorValues(field), bvv); } @Override public ByteVectorValues getByteVectorValues(String field) throws IOException { return rawVectorsReader.getByteVectorValues(field); } @Override public void search(String field, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) throws IOException { rawVectorsReader.search(field, target, knnCollector, acceptDocs); } @Override public void search(String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) throws IOException { if (knnCollector.k() == 0) return; final RandomVectorScorer scorer = getRandomVectorScorer(field, target); if (scorer == null) return; OrdinalTranslatedKnnCollector collector = new OrdinalTranslatedKnnCollector(knnCollector, scorer::ordToDoc); Bits acceptedOrds = scorer.getAcceptOrds(acceptDocs.bits()); for (int i = 0; i < scorer.maxOrd(); i++) { if (acceptedOrds == null || acceptedOrds.get(i)) { collector.collect(i, scorer.score(i)); collector.incVisitedCount(1); } } } @Override public void close() throws IOException { IOUtils.close(quantizedVectorData, rawVectorsReader); } @Override public long ramBytesUsed() { long size = SHALLOW_SIZE; size += RamUsageEstimator.sizeOfMap(fields, RamUsageEstimator.shallowSizeOfInstance(FieldEntry.class)); size += rawVectorsReader.ramBytesUsed(); return size; } @Override public Map<String, Long> getOffHeapByteSize(FieldInfo fieldInfo) { var raw = rawVectorsReader.getOffHeapByteSize(fieldInfo); FieldEntry fe = fields.get(fieldInfo.name); if (fe == null) { assert fieldInfo.getVectorEncoding() == VectorEncoding.BYTE; return raw; } var quant = Map.of(VECTOR_DATA_EXTENSION, fe.vectorDataLength()); return KnnVectorsReader.mergeOffHeapByteSizeMaps(raw, quant); } public float[] getCentroid(String field) { FieldEntry fieldEntry = fields.get(field); if (fieldEntry != null) { return fieldEntry.centroid; } return null; } private static IndexInput openDataInput( SegmentReadState state, int versionMeta, String fileExtension, String codecName, IOContext context ) throws IOException { String fileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, fileExtension); IndexInput in = state.directory.openInput(fileName, context); boolean success = false; try { int versionVectorData = CodecUtil.checkIndexHeader( in, codecName, ES816BinaryQuantizedVectorsFormat.VERSION_START, ES816BinaryQuantizedVectorsFormat.VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix ); if (versionMeta != versionVectorData) { throw new CorruptIndexException( "Format versions mismatch: meta=" + versionMeta + ", " + codecName + "=" + versionVectorData, in ); } CodecUtil.retrieveChecksum(in); success = true; return in; } finally { if (success == false) { IOUtils.closeWhileHandlingException(in); } } } private FieldEntry readField(IndexInput input, FieldInfo info) throws IOException { VectorEncoding vectorEncoding = readVectorEncoding(input); VectorSimilarityFunction similarityFunction = readSimilarityFunction(input); if (similarityFunction != info.getVectorSimilarityFunction()) { throw new IllegalStateException( "Inconsistent vector similarity function for field=\"" + info.name + "\"; " + similarityFunction + " != " + info.getVectorSimilarityFunction() ); } return FieldEntry.create(input, vectorEncoding, info.getVectorSimilarityFunction()); } private record FieldEntry( VectorSimilarityFunction similarityFunction, VectorEncoding vectorEncoding, int dimension, int descritizedDimension, long vectorDataOffset, long vectorDataLength, int size, float[] centroid, float centroidDP, OrdToDocDISIReaderConfiguration ordToDocDISIReaderConfiguration ) { static FieldEntry create(IndexInput input, VectorEncoding vectorEncoding, VectorSimilarityFunction similarityFunction) throws IOException { int dimension = input.readVInt(); long vectorDataOffset = input.readVLong(); long vectorDataLength = input.readVLong(); int size = input.readVInt(); final float[] centroid; float centroidDP = 0; if (size > 0) { centroid = new float[dimension]; input.readFloats(centroid, 0, dimension); centroidDP = Float.intBitsToFloat(input.readInt()); } else { centroid = null; } OrdToDocDISIReaderConfiguration conf = OrdToDocDISIReaderConfiguration.fromStoredMeta(input, size); return new FieldEntry( similarityFunction, vectorEncoding, dimension, BQVectorUtils.discretize(dimension, 64), vectorDataOffset, vectorDataLength, size, centroid, centroidDP, conf ); } } /** Binarized vector values holding row and quantized vector values */ protected static final
ES816BinaryQuantizedVectorsReader
java
alibaba__druid
core/src/main/java/com/alibaba/druid/support/monitor/dao/MonitorDaoJdbcImpl.java
{ "start": 26164, "end": 35383 }
class ____ { private final Field field; private final String columnName; private final Field hashFor; private final String hashForType; public FieldInfo(Field field, String columnName, Field hashFor, String hashForType) { this.field = field; this.columnName = columnName; this.hashFor = hashFor; this.hashForType = hashForType; field.setAccessible(true); if (hashFor != null) { hashFor.setAccessible(true); } } public String getHashForType() { return hashForType; } public Field getField() { return field; } public Field getHashFor() { return hashFor; } public String getColumnName() { return columnName; } public Class<?> getFieldType() { return field.getType(); } } public void insertAppIfNotExits(String domain, String app) throws SQLException { MonitorApp monitorApp = findApp(domain, app); if (monitorApp != null) { return; } String sql = "insert druid_app (domain, app) values (?, ?)"; JdbcUtils.execute(dataSource, sql, domain, app); } public List<MonitorApp> listApp(String domain) throws SQLException { List<MonitorApp> list = new ArrayList<MonitorApp>(); String sql = "select id, domain, app from druid_app " + " where domain = ?"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement(sql); stmt.setString(1, domain); rs = stmt.executeQuery(); if (rs.next()) { list.add(readApp(rs)); } return list; } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(conn); } } public MonitorApp findApp(String domain, String app) throws SQLException { String sql = "select id, domain, app from druid_app " + " where domain = ? and app = ?"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement(sql); stmt.setString(1, domain); stmt.setString(2, app); rs = stmt.executeQuery(); if (rs.next()) { return readApp(rs); } return null; } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(conn); } } private MonitorApp readApp(ResultSet rs) throws SQLException { MonitorApp app = new MonitorApp(); app.setId(rs.getLong(1)); app.setDomain(rs.getString(2)); app.setApp(rs.getString(3)); return app; } public List<MonitorCluster> listCluster(String domain, String app) throws SQLException { List<MonitorCluster> list = new ArrayList<MonitorCluster>(); String sql = "select id, domain, app, cluster from druid_cluster " + " where domain = ?"; if (app != null) { sql += " and app = ?"; } Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement(sql); stmt.setString(1, domain); if (app != null) { stmt.setString(2, app); } rs = stmt.executeQuery(); if (rs.next()) { list.add(readCluster(rs)); } return list; } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(conn); } } public void insertClusterIfNotExits(String domain, String app, String cluster) throws SQLException { MonitorCluster monitorApp = findCluster(domain, app, cluster); if (monitorApp != null) { return; } String sql = "insert druid_cluster (domain, app, cluster) values (?, ?, ?)"; JdbcUtils.execute(dataSource, sql, domain, app, cluster); } public MonitorCluster findCluster(String domain, String app, String cluster) throws SQLException { String sql = "select id, domain, app, cluster from druid_cluster " + " where domain = ? and app = ? and cluster = ?"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement(sql); stmt.setString(1, domain); stmt.setString(2, app); stmt.setString(3, cluster); rs = stmt.executeQuery(); if (rs.next()) { return readCluster(rs); } return null; } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(conn); } } private MonitorCluster readCluster(ResultSet rs) throws SQLException { MonitorCluster app = new MonitorCluster(); app.setId(rs.getLong(1)); app.setDomain(rs.getString(2)); app.setApp(rs.getString(3)); app.setCluster(rs.getString(4)); return app; } public void insertOrUpdateInstance(String domain, String app, String cluster, String host, String ip, Date startTime, long pid) throws SQLException { MonitorInstance monitorInst = findInst(domain, app, cluster, host); if (monitorInst == null) { String sql = "insert into druid_inst (domain, app, cluster, host, ip, lastActiveTime, lastPID) " + " values (?, ?, ?, ?, ?, ?, ?)"; JdbcUtils.execute(dataSource, sql, domain, app, cluster, host, ip, startTime, pid); } else { String sql = "update druid_inst set ip = ?, lastActiveTime = ?, lastPID = ? " + " where domain = ? and app = ? and cluster = ? and host = ? "; JdbcUtils.execute(dataSource, sql, ip, startTime, pid, domain, app, cluster, host); } } public MonitorInstance findInst(String domain, String app, String cluster, String host) throws SQLException { String sql = "select id, domain, app, cluster, host, ip, lastActiveTime, lastPID from druid_inst " + " where domain = ? and app = ? and cluster = ? and host = ? " + " limit 1"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement(sql); stmt.setString(1, domain); stmt.setString(2, app); stmt.setString(3, cluster); stmt.setString(4, host); rs = stmt.executeQuery(); if (rs.next()) { return readInst(rs); } return null; } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(conn); } } public List<MonitorInstance> listInst(String domain, String app, String cluster) throws SQLException { List<MonitorInstance> list = new ArrayList<MonitorInstance>(); String sql = "select id, domain, app, cluster, host, ip, lastActiveTime, lastPID from druid_inst " + "where domain = ?"; if (app != null) { sql += " and app = ?"; } if (cluster != null) { sql += " and cluster = ?"; } Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement(sql); int paramIndex = 1; stmt.setString(paramIndex++, domain); if (app != null) { stmt.setString(paramIndex++, app); } if (cluster != null) { stmt.setString(paramIndex++, cluster); } rs = stmt.executeQuery(); if (rs.next()) { list.add(readInst(rs)); } return list; } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(conn); } } private MonitorInstance readInst(ResultSet rs) throws SQLException { MonitorInstance inst = new MonitorInstance(); inst.setId(rs.getLong(1)); inst.setDomain(rs.getString(2)); inst.setApp(rs.getString(3)); inst.setCluster(rs.getString(4)); inst.setHost(rs.getString(5)); inst.setIp(rs.getString(6)); inst.setLastActiveTime(rs.getTimestamp(7)); inst.setLastPID(rs.getLong(8)); return inst; } }
FieldInfo
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/metadata/MetadataV4Serializer.java
{ "start": 1266, "end": 2701 }
class ____ extends MetadataV3Serializer { public static final MetadataSerializer INSTANCE = new MetadataV4Serializer(); public static final int VERSION = 4; @Override public int getVersion() { return VERSION; } @Override public CheckpointMetadata deserialize( DataInputStream dis, ClassLoader userCodeClassLoader, String externalPointer) throws IOException { return super.deserialize(dis, userCodeClassLoader, externalPointer) .withProperties(deserializeProperties(dis)); } @Override public void serialize(CheckpointMetadata checkpointMetadata, DataOutputStream dos) throws IOException { super.serialize(checkpointMetadata, dos); serializeProperties(checkpointMetadata.getCheckpointProperties(), dos); } private CheckpointProperties deserializeProperties(DataInputStream dis) throws IOException { try { // closed outside return (CheckpointProperties) new ObjectInputStream(dis).readObject(); } catch (ClassNotFoundException e) { throw new IOException("Couldn't deserialize checkpoint properties", e); } } private void serializeProperties(CheckpointProperties properties, DataOutputStream dos) throws IOException { new ObjectOutputStream(dos).writeObject(properties); // closed outside } }
MetadataV4Serializer
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/isolation/PluginScanner.java
{ "start": 10550, "end": 10923 }
class ____ constructor must be public"; } else if (t instanceof ExceptionInInitializerError) { return ": Failed to statically initialize plugin class"; } else if (t instanceof InvocationTargetException) { return ": Failed to invoke plugin constructor"; } else if (t instanceof LinkageError) { return ": Plugin
default
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2500/Issue2579.java
{ "start": 453, "end": 2592 }
class ____ extends TestCase { // 场景:走ASM public void test_for_issue1() throws Exception { run_test("MyPoint1"); } // 场景:不走ASM,通过JSONType(asm=false),关闭了ASM public void test_for_issue2() throws Exception { run_test("MyPoint2"); } // 场景:随机顺序组合JSON字符串测试2000次 private void run_test(String className) { String begin = "{"; String end = "}"; String jsonString; for (int i = 1; i < 2000; i++) { jsonString = getString(i, className); jsonString = begin + jsonString + end; try { Object obj = JSON.parse(jsonString, Feature.SupportAutoType); if ("MyPoint1".equals(className)) { Assert.assertEquals(i, ((MyPoint1) obj).getBatchNumber()); } else { Assert.assertEquals(i, ((MyPoint2) obj).getBatchNumber()); } } catch (JSONException e) { System.out.println(jsonString); e.printStackTrace(); Assert.assertTrue(false); } } } private static String getString(int batchNumber, String className) { List<String> list = new ArrayList<String>(); list.add("\"@type\":\"com.alibaba.json.bvt.issue_2500.Issue2579$" + className + "\""); list.add("\"date\":1563867975335"); list.add("\"id\":\"0f075036-9e52-4821-800a-9c51761a7227b\""); list.add("\"location\":{\"@type\":\"java.awt.Point\",\"x\":11,\"y\":1}"); list.add("\"point\":{\"@type\":\"java.awt.Point\",\"x\":9,\"y\":1}"); list.add( "\"pointArr\":[{\"@type\":\"java.awt.Point\",\"x\":4,\"y\":6},{\"@type\":\"java.awt.Point\",\"x\":7,\"y\":8}]"); list.add("\"strArr\":[\"te-st\",\"tes-t2\"]"); list.add("\"x\":2.0D"); list.add("\"y\":3.0D"); list.add("\"batchNumber\":" + batchNumber); Iterator<String> it = list.iterator(); StringBuffer buffer = new StringBuffer(); int len; int index; while (it.hasNext()) { len = list.size(); index = getRandomIndex(len); buffer.append(list.get(index)); buffer.append(","); list.remove(index); } buffer.deleteCharAt(buffer.length() - 1); return buffer.toString(); } private static int getRandomIndex(int length) { Random random = new Random(); return random.nextInt(length); } @SuppressWarnings("serial") public static
Issue2579
java
netty__netty
handler/src/test/java/io/netty/handler/ssl/AmazonCorrettoSslEngineTest.java
{ "start": 1303, "end": 3904 }
class ____ extends SSLEngineTest { static boolean checkIfAccpIsDisabled() { return AmazonCorrettoCryptoProvider.INSTANCE.getLoadingError() != null || !AmazonCorrettoCryptoProvider.INSTANCE.runSelfTests().equals(SelfTestStatus.PASSED); } public AmazonCorrettoSslEngineTest() { super(SslProvider.isTlsv13Supported(SslProvider.JDK)); } @Override protected SslProvider sslClientProvider() { return SslProvider.JDK; } @Override protected SslProvider sslServerProvider() { return SslProvider.JDK; } @BeforeEach @Override public void setup() { // See https://github.com/corretto/amazon-corretto-crypto-provider/blob/develop/README.md#code Security.insertProviderAt(AmazonCorrettoCryptoProvider.INSTANCE, 1); // See https://github.com/corretto/amazon-corretto-crypto-provider/blob/develop/README.md#verification-optional try { AmazonCorrettoCryptoProvider.INSTANCE.assertHealthy(); String providerName = Cipher.getInstance("AES/GCM/NoPadding").getProvider().getName(); assertEquals(AmazonCorrettoCryptoProvider.PROVIDER_NAME, providerName); } catch (Throwable e) { Security.removeProvider(AmazonCorrettoCryptoProvider.PROVIDER_NAME); throw new AssertionError(e); } super.setup(); } @AfterEach @Override public void tearDown() throws InterruptedException { super.tearDown(); // Remove the provider again and verify that it was removed Security.removeProvider(AmazonCorrettoCryptoProvider.PROVIDER_NAME); assertNull(Security.getProvider(AmazonCorrettoCryptoProvider.PROVIDER_NAME)); } @MethodSource("newTestParams") @ParameterizedTest @Disabled /* Does the JDK support a "max certificate chain length"? */ @Override public void testMutualAuthValidClientCertChainTooLongFailOptionalClientAuth(SSLEngineTestParam param) { } @MethodSource("newTestParams") @ParameterizedTest @Disabled /* Does the JDK support a "max certificate chain length"? */ @Override public void testMutualAuthValidClientCertChainTooLongFailRequireClientAuth(SSLEngineTestParam param) { } @Override protected boolean mySetupMutualAuthServerIsValidException(Throwable cause) { // TODO(scott): work around for a JDK issue. The exception should be SSLHandshakeException. return super.mySetupMutualAuthServerIsValidException(cause) || causedBySSLException(cause); } }
AmazonCorrettoSslEngineTest
java
netty__netty
transport/src/main/java/io/netty/channel/DefaultMessageSizeEstimator.java
{ "start": 991, "end": 1085 }
class ____ implements MessageSizeEstimator { private static final
DefaultMessageSizeEstimator
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformationIntegrationTests.java
{ "start": 12826, "end": 13235 }
class ____ { private UUID clientId; public UUID getId() { return this.clientId; } public void setId(UUID clientId) { this.clientId = clientId; } public void setClientId(String clientId) { this.clientId = UUID.fromString(clientId); } @Id public String getClientId() { return clientId == null ? null : clientId.toString(); } } @Entity public static
ExampleEntityWithStringId
java
apache__spark
launcher/src/main/java/org/apache/spark/launcher/SparkSubmitCommandBuilder.java
{ "start": 1355, "end": 1463 }
class ____ also some special features to aid launching shells (pyspark and sparkR) and also * examples. */
has
java
google__dagger
javatests/dagger/internal/codegen/SubcomponentCreatorValidationTest.java
{ "start": 2698, "end": 3052 }
interface ____ {", " ChildComponent child();", " ChildComponent.Builder childComponentBuilder();", "}"); Source childComponentFile = preprocessedJavaSource("test.ChildComponent", "package test;", "", "import dagger.Subcomponent;", "", "@Subcomponent", "
ParentComponent
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/ByteBufferDecodingState.java
{ "start": 1138, "end": 4853 }
class ____ extends DecodingState { ByteBuffer[] inputs; ByteBuffer[] outputs; int[] erasedIndexes; boolean usingDirectBuffer; ByteBufferDecodingState(RawErasureDecoder decoder, ByteBuffer[] inputs, int[] erasedIndexes, ByteBuffer[] outputs) { this.decoder = decoder; this.inputs = inputs; this.outputs = outputs; this.erasedIndexes = erasedIndexes; ByteBuffer validInput = CoderUtil.findFirstValidInput(inputs); this.decodeLength = validInput.remaining(); this.usingDirectBuffer = validInput.isDirect(); checkParameters(inputs, erasedIndexes, outputs); checkInputBuffers(inputs); checkOutputBuffers(outputs); } ByteBufferDecodingState(RawErasureDecoder decoder, int decodeLength, int[] erasedIndexes, ByteBuffer[] inputs, ByteBuffer[] outputs) { this.decoder = decoder; this.decodeLength = decodeLength; this.erasedIndexes = erasedIndexes; this.inputs = inputs; this.outputs = outputs; } /** * Convert to a ByteArrayDecodingState when it's backed by on-heap arrays. */ ByteArrayDecodingState convertToByteArrayState() { int[] inputOffsets = new int[inputs.length]; int[] outputOffsets = new int[outputs.length]; byte[][] newInputs = new byte[inputs.length][]; byte[][] newOutputs = new byte[outputs.length][]; ByteBuffer buffer; for (int i = 0; i < inputs.length; ++i) { buffer = inputs[i]; if (buffer != null) { inputOffsets[i] = buffer.arrayOffset() + buffer.position(); newInputs[i] = buffer.array(); } } for (int i = 0; i < outputs.length; ++i) { buffer = outputs[i]; outputOffsets[i] = buffer.arrayOffset() + buffer.position(); newOutputs[i] = buffer.array(); } ByteArrayDecodingState baeState = new ByteArrayDecodingState(decoder, decodeLength, erasedIndexes, newInputs, inputOffsets, newOutputs, outputOffsets); return baeState; } /** * Check and ensure the buffers are of the desired length and type, direct * buffers or not. * @param buffers the buffers to check */ void checkInputBuffers(ByteBuffer[] buffers) { int validInputs = 0; for (ByteBuffer buffer : buffers) { if (buffer == null) { continue; } if (buffer.remaining() != decodeLength) { throw new HadoopIllegalArgumentException( "Invalid buffer, not of length " + decodeLength); } if (buffer.isDirect() != usingDirectBuffer) { throw new HadoopIllegalArgumentException( "Invalid buffer, isDirect should be " + usingDirectBuffer); } validInputs++; } if (validInputs < decoder.getNumDataUnits()) { throw new HadoopIllegalArgumentException( "No enough valid inputs are provided, not recoverable"); } } /** * Check and ensure the buffers are of the desired length and type, direct * buffers or not. * @param buffers the buffers to check */ void checkOutputBuffers(ByteBuffer[] buffers) { for (ByteBuffer buffer : buffers) { if (buffer == null) { throw new HadoopIllegalArgumentException( "Invalid buffer found, not allowing null"); } if (buffer.remaining() != decodeLength) { throw new HadoopIllegalArgumentException( "Invalid buffer, not of length " + decodeLength); } if (buffer.isDirect() != usingDirectBuffer) { throw new HadoopIllegalArgumentException( "Invalid buffer, isDirect should be " + usingDirectBuffer); } } } }
ByteBufferDecodingState
java
google__dagger
javatests/dagger/hilt/android/processor/internal/GeneratorsTest.java
{ "start": 17779, "end": 18407 }
class ____ extends Application implements" + " GeneratedComponentManagerHolder {")); }); } @Test public void copyTargetApiAnnotationFragment() { Source myApplication = HiltCompilerTests.javaSource( "test.MyFragment", "package test;", "", "import android.annotation.TargetApi;", "import androidx.fragment.app.Fragment;", "import dagger.hilt.android.AndroidEntryPoint;", "", "@TargetApi(24)", "@AndroidEntryPoint(Fragment.class)", "public
Hilt_MyApplication
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/JavaTimeDefaultTimeZoneTest.java
{ "start": 1416, "end": 2028 }
class ____ { // BUG: Diagnostic matches: REPLACEME Clock clock = Clock.systemDefaultZone(); Clock clockWithZone = Clock.system(systemDefault()); } """) .doTest(); } @Test public void staticImportOfStaticMethod() { BugCheckerRefactoringTestHelper.newInstance( JavaTimeDefaultTimeZone.class, JavaTimeDefaultTimeZoneTest.class) .addInputLines( "in/TestClass.java", """ import static java.time.LocalDate.now; import java.time.LocalDate; public
TestClass
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/Customer.java
{ "start": 263, "end": 629 }
class ____ { private Long id; private String name; public Customer() { } public Customer(Long id, String name) { this.id = id; this.name = name; } @Id public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Customer
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/highavailability/HighAvailabilityServicesUtilsTest.java
{ "start": 5113, "end": 5686 }
class ____ implements HighAvailabilityServicesFactory { static HighAvailabilityServices haServices; static ClientHighAvailabilityServices clientHAServices; @Override public HighAvailabilityServices createHAServices( Configuration configuration, Executor executor) { return haServices; } @Override public ClientHighAvailabilityServices createClientHAServices(Configuration configuration) throws Exception { return clientHAServices; } } }
TestHAFactory
java
apache__camel
components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyProxyTest.java
{ "start": 1169, "end": 2483 }
class ____ extends BaseNettyTest { @RegisterExtension protected AvailablePortFinder.Port port2 = AvailablePortFinder.find(); @Test public void testNettyProxy() throws Exception { getMockEndpoint("mock:before").expectedBodiesReceived("Camel"); getMockEndpoint("mock:proxy").expectedBodiesReceived("Camel"); getMockEndpoint("mock:after").expectedBodiesReceived("Bye Camel"); Object body = template.requestBody("netty:tcp://localhost:" + port.getPort() + "?sync=true&textline=true", "Camel\n"); assertEquals("Bye Camel", body); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { fromF("netty:tcp://localhost:%s?sync=true&textline=true", port.getPort()) .to("mock:before") .toF("netty:tcp://localhost:%s?sync=true&textline=true", port2.getPort()) .to("mock:after"); fromF("netty:tcp://localhost:%s?sync=true&textline=true", port2.getPort()) .to("mock:proxy") .transform().simple("Bye ${body}\n"); } }; } }
NettyProxyTest
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/MyFooList.java
{ "start": 126, "end": 249 }
class ____ extends ArrayList<Foo> { public MyFooList(Foo... foos) { super(Arrays.asList(foos)); } }
MyFooList
java
google__guava
android/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java
{ "start": 9234, "end": 9919 }
class ____ implements Sample { final long delayMillis; boolean finished; SampleImpl(long delayMillis) { this.delayMillis = delayMillis; } @CanIgnoreReturnValue @Override public String sleepThenReturnInput(String input) { try { MILLISECONDS.sleep(delayMillis); finished = true; return input; } catch (InterruptedException e) { throw new AssertionError(); } } @Override public void sleepThenThrowException() throws SampleException { try { MILLISECONDS.sleep(delayMillis); } catch (InterruptedException e) { } throw new SampleException(); } } }
SampleImpl
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToBooleanConverter.java
{ "start": 965, "end": 1046 }
class ____ convert {@link String} to {@link Boolean} * * @since 2.7.6 */ public
to
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/filter/factory/RewriteLocationResponseHeaderGatewayFilterFactoryTests.java
{ "start": 1255, "end": 1777 }
class ____ extends BaseWebClientTests { @Test public void rewriteLocationResponseHeaderFilterWorks() { testClient.post() .uri("/headers") .header("Host", "test1.rewritelocationresponseheader.org") .exchange() .expectStatus() .isOk() .expectHeader() .valueEquals("Location", "https://test1.rewritelocationresponseheader.org/some/object/id"); } @EnableAutoConfiguration @SpringBootConfiguration @Import(DefaultTestConfig.class) public static
RewriteLocationResponseHeaderGatewayFilterFactoryTests
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/module/SimpleAbstractTypeResolver.java
{ "start": 974, "end": 1136 }
class ____ when defining * concrete implementations; however, only works with abstract types (since * this is only called for abstract types) */ public
annotations
java
quarkusio__quarkus
independent-projects/qute/core/src/test/java/io/quarkus/qute/ReflectionResolverTest.java
{ "start": 444, "end": 3976 }
class ____ { @Test public void testReflectionResolver() { Map<Integer, String> treeMap = new TreeMap<>(Integer::compare); treeMap.put(2, "bar"); treeMap.put(1, "foo"); assertEquals("foo::o", Engine.builder().addDefaults().addValueResolver(new ReflectionValueResolver()).build() .parse("{map.entrySet.iterator.next.value}::{str.charAt(1)}").data("map", treeMap, "str", "foo").render()); } @Test public void testFieldAccessor() { assertEquals("box", Engine.builder().addDefaults().addValueResolver(new ReflectionValueResolver()).build() .parse("{foo.name}").data("foo", new Foo("box")).render()); } @Test public void testMethodWithParameter() { assertEquals("3", Engine.builder().addDefaults().addValueResolver(new ReflectionValueResolver()).build() .parse("{foo.computeLength(foo.name)}").data("foo", new Foo("box")).render()); } @Test public void testMethodWithParameterNotFound() { assertEquals("NOT_FOUND", Engine.builder().addDefaults().addValueResolver(new ReflectionValueResolver()).build() .parse("{foo.computeLength(true) ?: 'NOT_FOUND'}").data("foo", new Foo("box")).render()); } @Test public void testMethodWithVarargs() { assertEquals("box:box:", Engine.builder().addDefaults().addValueResolver(new ReflectionValueResolver()).build() .parse("{foo.compute(foo.name,1,2)}").data("foo", new Foo("box")).render()); } @Test public void testStaticMembersIgnored() { assertEquals("baz::baz", Engine.builder().addDefaults().addValueResolver(new ReflectionValueResolver()).build() .parse("{foo.bar ?: 'baz'}::{foo.BAR ?: 'baz'}").data("foo", new Foo("box")).render()); } @Test public void testCachedResolver() { Template template = Engine.builder().addDefaults().addValueResolver(new ReflectionValueResolver()).build() .parse("{foo.name}::{foo.name.repeat(5)}::{foo.name.repeat(n)}"); Expression fooName = template.findExpression(e -> e.toOriginalString().equals("foo.name")); Expression fooNameRepeat5 = template.findExpression(e -> e.toOriginalString().equals("foo.name.repeat(5)")); Expression fooNameRepeatN = template.findExpression(e -> e.toOriginalString().equals("foo.name.repeat(n)")); PartImpl fooNamePart = (PartImpl) fooName.getParts().get(1); PartImpl fooNameRepeat5Part = (PartImpl) fooNameRepeat5.getParts().get(2); PartImpl fooNameRepeatNPart = (PartImpl) fooNameRepeatN.getParts().get(2); assertNull(fooNamePart.cachedResolver); assertNull(fooNameRepeat5Part.cachedResolver); assertNull(fooNameRepeatNPart.cachedResolver); assertEquals("box::boxboxboxboxbox::box", template.data("foo", new Foo("box"), "n", 1).render()); assertEquals("box::boxboxboxboxbox::boxbox", template.data("foo", new Foo("box"), "n", 2).render()); assertNotNull(fooNamePart.cachedResolver); assertNotNull(fooNameRepeat5Part.cachedResolver); assertNotNull(fooNameRepeatNPart.cachedResolver); assertTrue(fooNamePart.cachedResolver instanceof ReflectionValueResolver.AccessorResolver); assertTrue(fooNameRepeat5Part.cachedResolver instanceof ReflectionValueResolver.AccessorResolver); assertTrue(fooNameRepeatNPart.cachedResolver instanceof ReflectionValueResolver.CandidateResolver); } public static
ReflectionResolverTest
java
alibaba__nacos
console/src/main/java/com/alibaba/nacos/console/handler/impl/ConditionFunctionEnabled.java
{ "start": 2181, "end": 2384 }
class ____ extends ConditionFunctionEnabled { public ConditionConfigEnabled() { super(EnvUtil.FUNCTION_MODE_CONFIG); } } public static
ConditionConfigEnabled
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ArraysTools.java
{ "start": 235, "end": 1435 }
class ____ { public static <T> boolean arrayIncludesInstanceOf(T[] array, Class<?> cls) { for ( T obj : array ) { if ( cls.isAssignableFrom( obj.getClass() ) ) { return true; } } return false; } public static boolean arraysEqual(Object[] array1, Object[] array2) { if ( array1 == null ) { return array2 == null; } if ( array2 == null || array1.length != array2.length ) { return false; } for ( int i = 0; i < array1.length; ++i ) { if ( array1[i] != null ? !array1[i].equals( array2[i] ) : array2[i] != null ) { return false; } } return true; } /** * Converts map's value set to an array. {@code keys} parameter specifies requested elements and their order. * * @param data Source map. * @param keys Array of keys that represent requested map values. * * @return Array of values stored in the map under specified keys. If map does not contain requested key, * {@code null} is inserted. */ public static Object[] mapToArray(Map<String, Object> data, String[] keys) { final Object[] ret = new Object[keys.length]; for ( int i = 0; i < keys.length; ++i ) { ret[i] = data.get( keys[i] ); } return ret; } }
ArraysTools
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/operators/util/CollectionDataStreams.java
{ "start": 1677, "end": 3578 }
class ____ { public static DataStreamSource<Tuple3<Integer, Long, String>> get3TupleDataSet( StreamExecutionEnvironment env) { List<Tuple3<Integer, Long, String>> data = new ArrayList<>(); data.add(new Tuple3<>(1, 1L, "Hi")); data.add(new Tuple3<>(2, 2L, "Hello")); data.add(new Tuple3<>(3, 2L, "Hello world")); data.add(new Tuple3<>(4, 3L, "Hello world, how are you?")); data.add(new Tuple3<>(5, 3L, "I am fine.")); data.add(new Tuple3<>(6, 3L, "Luke Skywalker")); data.add(new Tuple3<>(7, 4L, "Comment#1")); data.add(new Tuple3<>(8, 4L, "Comment#2")); data.add(new Tuple3<>(9, 4L, "Comment#3")); data.add(new Tuple3<>(10, 4L, "Comment#4")); data.add(new Tuple3<>(11, 5L, "Comment#5")); data.add(new Tuple3<>(12, 5L, "Comment#6")); data.add(new Tuple3<>(13, 5L, "Comment#7")); data.add(new Tuple3<>(14, 5L, "Comment#8")); data.add(new Tuple3<>(15, 5L, "Comment#9")); data.add(new Tuple3<>(16, 6L, "Comment#10")); data.add(new Tuple3<>(17, 6L, "Comment#11")); data.add(new Tuple3<>(18, 6L, "Comment#12")); data.add(new Tuple3<>(19, 6L, "Comment#13")); data.add(new Tuple3<>(20, 6L, "Comment#14")); data.add(new Tuple3<>(21, 6L, "Comment#15")); Collections.shuffle(data); return env.fromData(data); } public static DataStreamSource<Tuple3<Integer, Long, String>> getSmall3TupleDataSet( StreamExecutionEnvironment env) { List<Tuple3<Integer, Long, String>> data = new ArrayList<>(); data.add(new Tuple3<>(1, 1L, "Hi")); data.add(new Tuple3<>(2, 2L, "Hello")); data.add(new Tuple3<>(3, 2L, "Hello world")); Collections.shuffle(data); return env.fromData(data); } /** POJO. */ public static
CollectionDataStreams
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/frommap/StringMapToBeanWithCustomPresenceCheckMapper.java
{ "start": 412, "end": 779 }
interface ____ { StringMapToBeanWithCustomPresenceCheckMapper INSTANCE = Mappers.getMapper( StringMapToBeanWithCustomPresenceCheckMapper.class ); Order fromMap(Map<String, String> map); @Condition default boolean isNotEmpty(String value) { return value != null && !value.isEmpty(); }
StringMapToBeanWithCustomPresenceCheckMapper
java
spring-projects__spring-security
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/InMemoryReactiveClientRegistrationRepositoryTests.java
{ "start": 1122, "end": 3391 }
class ____ { private ClientRegistration registration = TestClientRegistrations.clientRegistration().build(); private InMemoryReactiveClientRegistrationRepository repository; @BeforeEach public void setup() { this.repository = new InMemoryReactiveClientRegistrationRepository(this.registration); } @Test public void constructorWhenZeroVarArgsThenIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository()); } @Test public void constructorWhenClientRegistrationArrayThenIllegalArgumentException() { ClientRegistration[] registrations = null; assertThatIllegalArgumentException() .isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations)); } @Test public void constructorWhenClientRegistrationListThenIllegalArgumentException() { List<ClientRegistration> registrations = null; assertThatIllegalArgumentException() .isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations)); } @Test public void constructorListClientRegistrationWhenDuplicateIdThenIllegalArgumentException() { List<ClientRegistration> registrations = Arrays.asList(this.registration, this.registration); assertThatIllegalStateException() .isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations)); } @Test public void constructorWhenClientRegistrationIsNullThenIllegalArgumentException() { ClientRegistration registration = null; assertThatIllegalArgumentException() .isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registration)); } @Test public void findByRegistrationIdWhenValidIdThenFound() { // @formatter:off StepVerifier.create(this.repository.findByRegistrationId(this.registration.getRegistrationId())) .expectNext(this.registration) .verifyComplete(); // @formatter:on } @Test public void findByRegistrationIdWhenNotValidIdThenEmpty() { StepVerifier.create(this.repository.findByRegistrationId(this.registration.getRegistrationId() + "invalid")) .verifyComplete(); } @Test public void iteratorWhenContainsGithubThenContains() { assertThat(this.repository).containsOnly(this.registration); } }
InMemoryReactiveClientRegistrationRepositoryTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/OneToManyJoinedInheritanceAndDiscriminatorTest.java
{ "start": 1574, "end": 3944 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { final CustomerComputerSystem customerComputer = new CustomerComputerSystem(); customerComputer.setId( 1L ); session.persist( customerComputer ); final CustomerCompany customerCompany = new CustomerCompany( 2L ); customerCompany.addComputerSystem( customerComputer ); session.persist( customerCompany ); final DistributorComputerSystem distributorComputer = new DistributorComputerSystem(); distributorComputer.setId( 3L ); session.persist( distributorComputer ); final DistributorCompany distributorCompany = new DistributorCompany( 4L ); distributorCompany.addComputerSystem( distributorComputer ); session.persist( distributorCompany ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.dropData(); } @Test public void testQuery(SessionFactoryScope scope) { scope.inTransaction( session -> { //noinspection removal final CustomerCompany result = session.createQuery( "from CustomerCompany", CustomerCompany.class ).getSingleResult(); assertThat( result.getComputerSystems() ).hasSize( 1 ); } ); } @Test public void testFind(SessionFactoryScope scope) { scope.inTransaction( session -> { final DistributorCompany result = session.find( DistributorCompany.class, 4L ); assertThat( result.getComputerSystems() ).hasSize( 1 ); } ); } @Test public void testJoinSelectId(SessionFactoryScope scope) { scope.inTransaction( session -> { //noinspection removal final Long result = session.createQuery( "select s.id from CustomerCompany c join c.computerSystems s", Long.class ).getSingleResult(); assertThat( result ).isEqualTo( 1L ); } ); } @Test public void testJoinSelectEntity(SessionFactoryScope scope) { scope.inTransaction( session -> { //noinspection removal final DistributorComputerSystem result = session.createQuery( "select s from DistributorCompany c join c.computerSystems s", DistributorComputerSystem.class ).getSingleResult(); assertThat( result.getId() ).isEqualTo( 3L ); } ); } @SuppressWarnings({"FieldCanBeLocal", "unused"}) @Entity( name = "Company" ) @Inheritance( strategy = InheritanceType.JOINED ) public static abstract
OneToManyJoinedInheritanceAndDiscriminatorTest
java
google__guava
guava-testlib/src/com/google/common/collect/testing/TestsForListsInJavaUtil.java
{ "start": 2555, "end": 12654 }
class ____ { public static Test suite() { return new TestsForListsInJavaUtil().allTests(); } public Test allTests() { TestSuite suite = new TestSuite("java.util Lists"); suite.addTest(testsForEmptyList()); suite.addTest(testsForSingletonList()); suite.addTest(testsForArraysAsList()); suite.addTest(testsForArrayList()); suite.addTest(testsForLinkedList()); suite.addTest(testsForCopyOnWriteArrayList()); suite.addTest(testsForUnmodifiableList()); suite.addTest(testsForCheckedList()); suite.addTest(testsForAbstractList()); suite.addTest(testsForAbstractSequentialList()); suite.addTest(testsForVector()); return suite; } protected Collection<Method> suppressForEmptyList() { return emptySet(); } protected Collection<Method> suppressForSingletonList() { return emptySet(); } protected Collection<Method> suppressForArraysAsList() { return emptySet(); } protected Collection<Method> suppressForArrayList() { return emptySet(); } protected Collection<Method> suppressForLinkedList() { return emptySet(); } protected Collection<Method> suppressForCopyOnWriteArrayList() { return asList( getSubListOriginalListSetAffectsSubListMethod(), getSubListOriginalListSetAffectsSubListLargeListMethod(), getSubListSubListRemoveAffectsOriginalLargeListMethod(), getListIteratorFullyModifiableMethod(), getSpliteratorNotImmutableCollectionAllowsAddMethod(), getSpliteratorNotImmutableCollectionAllowsRemoveMethod()); } protected Collection<Method> suppressForUnmodifiableList() { return emptySet(); } protected Collection<Method> suppressForCheckedList() { return emptySet(); } protected Collection<Method> suppressForAbstractList() { return emptySet(); } protected Collection<Method> suppressForAbstractSequentialList() { return emptySet(); } protected Collection<Method> suppressForVector() { return emptySet(); } @SuppressWarnings("EmptyList") // We specifically want to test emptyList() public Test testsForEmptyList() { return ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return emptyList(); } }) .named("emptyList") .withFeatures(CollectionFeature.SERIALIZABLE, CollectionSize.ZERO) .suppressing(suppressForEmptyList()) .createTestSuite(); } public Test testsForSingletonList() { return ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return singletonList(elements[0]); } }) .named("singletonList") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ONE) .suppressing(suppressForSingletonList()) .createTestSuite(); } public Test testsForArraysAsList() { return ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return asList(elements.clone()); } }) .named("Arrays.asList") .withFeatures( ListFeature.SUPPORTS_SET, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForArraysAsList()) .createTestSuite(); } public Test testsForArrayList() { return ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return new ArrayList<>(MinimalCollection.of(elements)); } }) .named("ArrayList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionSize.ANY) .suppressing(suppressForArrayList()) .createTestSuite(); } // We are testing LinkedList / testing our tests on LinkedList. @SuppressWarnings("JdkObsolete") public Test testsForLinkedList() { return ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return new LinkedList<>(MinimalCollection.of(elements)); } }) .named("LinkedList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionSize.ANY) .suppressing(suppressForLinkedList()) .createTestSuite(); } public Test testsForCopyOnWriteArrayList() { return ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return new CopyOnWriteArrayList<>(MinimalCollection.of(elements)); } }) .named("CopyOnWriteArrayList") .withFeatures( ListFeature.SUPPORTS_ADD_WITH_INDEX, ListFeature.SUPPORTS_REMOVE_WITH_INDEX, ListFeature.SUPPORTS_SET, CollectionFeature.SUPPORTS_ADD, CollectionFeature.SUPPORTS_REMOVE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForCopyOnWriteArrayList()) .createTestSuite(); } public Test testsForUnmodifiableList() { return ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override public List<String> create(String[] elements) { List<String> innerList = new ArrayList<>(); Collections.addAll(innerList, elements); return unmodifiableList(innerList); } }) .named("unmodifiableList/ArrayList") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForUnmodifiableList()) .createTestSuite(); } public Test testsForCheckedList() { return ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override public List<String> create(String[] elements) { List<String> innerList = new ArrayList<>(); Collections.addAll(innerList, elements); return Collections.checkedList(innerList, String.class); } }) .named("checkedList/ArrayList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.RESTRICTS_ELEMENTS, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForCheckedList()) .createTestSuite(); } public Test testsForAbstractList() { return ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override protected List<String> create(String[] elements) { return new AbstractList<String>() { @Override public int size() { return elements.length; } @Override public String get(int index) { return elements[index]; } }; } }) .named("AbstractList") .withFeatures( CollectionFeature.NONE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForAbstractList()) .createTestSuite(); } public Test testsForAbstractSequentialList() { return ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override protected List<String> create(String[] elements) { // For this test we trust ArrayList works List<String> list = new ArrayList<>(); Collections.addAll(list, elements); return new AbstractSequentialList<String>() { @Override public int size() { return list.size(); } @Override public ListIterator<String> listIterator(int index) { return list.listIterator(index); } }; } }) .named("AbstractSequentialList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForAbstractSequentialList()) .createTestSuite(); } // We are testing Vector / testing our tests on Vector. @SuppressWarnings("JdkObsolete") private Test testsForVector() { return ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override protected List<String> create(String[] elements) { return new Vector<>(MinimalCollection.of(elements)); } }) .named("Vector") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForVector()) .createTestSuite(); } }
TestsForListsInJavaUtil
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/MinLongAggregator.java
{ "start": 603, "end": 801 }
class ____ { public static long init() { return Long.MAX_VALUE; } public static long combine(long current, long v) { return Math.min(current, v); } }
MinLongAggregator
java
alibaba__nacos
address/src/test/java/com/alibaba/nacos/address/controller/ServerListControllerTest.java
{ "start": 1961, "end": 3905 }
class ____ { @Mock private NamingMetadataManager metadataManager; @Mock private ServiceStorage serviceStorage; private Service service; private MockMvc mockMvc; @BeforeEach void before() { this.mockMvc = MockMvcBuilders.standaloneSetup( new ServerListController(new AddressServerGeneratorManager(), metadataManager, serviceStorage)).build(); service = Service .newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false); ServiceManager.getInstance().getSingleton(service); } @AfterEach void tearDown() { ServiceManager.getInstance().removeSingleton(service); } @Test void testGetCluster() throws Exception { final Service service = Service .newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false); ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.getClusters().put("serverList", new ClusterMetadata()); when(metadataManager.getServiceMetadata(service)).thenReturn(Optional.of(serviceMetadata)); List<Instance> list = new ArrayList<>(2); list.add(new Instance()); list.add(new Instance()); ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setHosts(list); when(serviceStorage.getData(service)).thenReturn(serviceInfo); mockMvc.perform(get("/nacos/serverList")).andExpect(status().isOk()); } @Test void testGetClusterCannotFindService() throws Exception { tearDown(); mockMvc.perform(get("/default/serverList")).andExpect(status().isNotFound()); } @Test void testGetClusterCannotFindCluster() throws Exception { mockMvc.perform(get("/nacos/serverList")).andExpect(status().isNotFound()); } }
ServerListControllerTest
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/JoinNaming.java
{ "start": 1034, "end": 4445 }
class ____ { private Integer ed_id1; private Integer ed_id2; private Integer ing_id1; @BeforeClassTemplate public void initData(SessionFactoryScope scope) { // Revision 1 scope.inTransaction( em -> { JoinNamingRefEdEntity ed1 = new JoinNamingRefEdEntity( "data1" ); JoinNamingRefEdEntity ed2 = new JoinNamingRefEdEntity( "data2" ); JoinNamingRefIngEntity ing1 = new JoinNamingRefIngEntity( "x", ed1 ); em.persist( ed1 ); em.persist( ed2 ); em.persist( ing1 ); ed_id1 = ed1.getId(); ed_id2 = ed2.getId(); ing_id1 = ing1.getId(); } ); // Revision 2 scope.inTransaction( em -> { JoinNamingRefEdEntity ed2 = em.find( JoinNamingRefEdEntity.class, ed_id2 ); JoinNamingRefIngEntity ing1 = em.find( JoinNamingRefIngEntity.class, ing_id1 ); ing1.setData( "y" ); ing1.setReference( ed2 ); } ); } @Test public void testRevisionsCounts(SessionFactoryScope scope) { scope.inSession( em -> { final var auditReader = AuditReaderFactory.get( em ); assertEquals( Arrays.asList( 1, 2 ), auditReader.getRevisions( JoinNamingRefEdEntity.class, ed_id1 ) ); assertEquals( Arrays.asList( 1, 2 ), auditReader.getRevisions( JoinNamingRefEdEntity.class, ed_id2 ) ); assertEquals( Arrays.asList( 1, 2 ), auditReader.getRevisions( JoinNamingRefIngEntity.class, ing_id1 ) ); } ); } @Test public void testHistoryOfEdId1(SessionFactoryScope scope) { scope.inSession( em -> { final var auditReader = AuditReaderFactory.get( em ); JoinNamingRefEdEntity ver1 = new JoinNamingRefEdEntity( ed_id1, "data1" ); assertEquals( ver1, auditReader.find( JoinNamingRefEdEntity.class, ed_id1, 1 ) ); assertEquals( ver1, auditReader.find( JoinNamingRefEdEntity.class, ed_id1, 2 ) ); } ); } @Test public void testHistoryOfEdId2(SessionFactoryScope scope) { scope.inSession( em -> { final var auditReader = AuditReaderFactory.get( em ); JoinNamingRefEdEntity ver1 = new JoinNamingRefEdEntity( ed_id2, "data2" ); assertEquals( ver1, auditReader.find( JoinNamingRefEdEntity.class, ed_id2, 1 ) ); assertEquals( ver1, auditReader.find( JoinNamingRefEdEntity.class, ed_id2, 2 ) ); } ); } @Test public void testHistoryOfIngId1(SessionFactoryScope scope) { scope.inSession( em -> { final var auditReader = AuditReaderFactory.get( em ); JoinNamingRefIngEntity ver1 = new JoinNamingRefIngEntity( ing_id1, "x", null ); JoinNamingRefIngEntity ver2 = new JoinNamingRefIngEntity( ing_id1, "y", null ); assertEquals( ver1, auditReader.find( JoinNamingRefIngEntity.class, ing_id1, 1 ) ); assertEquals( ver2, auditReader.find( JoinNamingRefIngEntity.class, ing_id1, 2 ) ); assertEquals( new JoinNamingRefEdEntity( ed_id1, "data1" ), auditReader.find( JoinNamingRefIngEntity.class, ing_id1, 1 ).getReference() ); assertEquals( new JoinNamingRefEdEntity( ed_id2, "data2" ), auditReader.find( JoinNamingRefIngEntity.class, ing_id1, 2 ).getReference() ); } ); } @Test public void testJoinColumnName(DomainModelScope scope) { Iterator<Selectable> columns = scope.getDomainModel().getEntityBinding( "org.hibernate.orm.test.envers.integration.naming.JoinNamingRefIngEntity_AUD" ).getProperty( "reference_id" ).getSelectables().iterator(); assertTrue( columns.hasNext() ); assertEquals( "jnree_column_reference", columns.next().getText() ); assertFalse( columns.hasNext() ); } }
JoinNaming
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/CreatorWithNamingStrategyTest.java
{ "start": 644, "end": 1067 }
class ____ extends JacksonAnnotationIntrospector { @Override public String findImplicitPropertyName(MapperConfig<?> config, AnnotatedMember param) { if (param instanceof AnnotatedParameter ap) { return "paramName"+ap.getIndex(); } return super.findImplicitPropertyName(config, param); } } // [databind#2051] static
MyParamIntrospector
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/steps/BlockingOperationControlBuildStep.java
{ "start": 382, "end": 755 }
class ____ { @Record(ExecutionTime.STATIC_INIT) @BuildStep public void blockingOP(List<IOThreadDetectorBuildItem> threadDetectors, BlockingOperationRecorder recorder) { recorder .control(threadDetectors.stream().map(IOThreadDetectorBuildItem::getDetector).collect(Collectors.toList())); } }
BlockingOperationControlBuildStep
java
mockito__mockito
mockito-integration-tests/java-21-tests/src/test/java/org/mockito/internal/stubbing/answers/DeepStubReturnsEnumJava21Test.java
{ "start": 414, "end": 3991 }
class ____ { @Test public void cant_mock_enum_class_in_Java21_Issue_2984() { assertThatThrownBy( () -> { mock(TestEnum.class); }) .isInstanceOf(MockitoException.class) .hasMessageContaining("Sealed abstract enums can't be mocked.") .hasCauseInstanceOf(MockitoException.class); } @Test public void cant_mock_enum_class_as_deep_stub_in_Java21_Issue_2984() { assertThatThrownBy( () -> { mock(TestEnum.class, RETURNS_DEEP_STUBS); }) .isInstanceOf(MockitoException.class) .hasMessageContaining("Sealed abstract enums can't be mocked.") .hasCauseInstanceOf(MockitoException.class); } @Test public void deep_stub_cant_mock_enum_with_abstract_method_in_Java21_Issue_2984() { final var mock = mock(TestClass.class, RETURNS_DEEP_STUBS); assertThatThrownBy( () -> { mock.getTestEnum(); }) .isInstanceOf(MockitoException.class) .hasMessageContaining("Sealed abstract enums can't be mocked.") .hasCauseInstanceOf(MockitoException.class); } @Test public void deep_stub_can_override_mock_enum_with_abstract_method_in_Java21_Issue_2984() { final var mock = mock(TestClass.class, RETURNS_DEEP_STUBS); // We need the doReturn() because when calling when(mock.getTestEnum()) it will already // throw an exception. doReturn(TestEnum.A).when(mock).getTestEnum(); assertThat(mock.getTestEnum()).isEqualTo(TestEnum.A); assertThat(mock.getTestEnum().getValue()).isEqualTo("A"); assertThat(mockingDetails(mock.getTestEnum()).isMock()).isFalse(); } @Test public void deep_stub_can_mock_enum_without_method_in_Java21_Issue_2984() { final var mock = mock(TestClass.class, RETURNS_DEEP_STUBS); assertThat(mock.getTestNonAbstractEnum()).isNotNull(); assertThat(mockingDetails(mock.getTestNonAbstractEnum()).isMock()).isTrue(); when(mock.getTestNonAbstractEnum()).thenReturn(TestNonAbstractEnum.B); assertThat(mock.getTestNonAbstractEnum()).isEqualTo(TestNonAbstractEnum.B); } @Test public void deep_stub_can_mock_enum_without_abstract_method_in_Java21_Issue_2984() { final var mock = mock(TestClass.class, RETURNS_DEEP_STUBS); assertThat(mock.getTestNonAbstractEnumWithMethod()).isNotNull(); assertThat(mock.getTestNonAbstractEnumWithMethod().getValue()).isNull(); assertThat(mockingDetails(mock.getTestNonAbstractEnumWithMethod()).isMock()).isTrue(); when(mock.getTestNonAbstractEnumWithMethod().getValue()).thenReturn("Mock"); assertThat(mock.getTestNonAbstractEnumWithMethod().getValue()).isEqualTo("Mock"); when(mock.getTestNonAbstractEnumWithMethod()).thenReturn(TestNonAbstractEnumWithMethod.B); assertThat(mock.getTestNonAbstractEnumWithMethod()) .isEqualTo(TestNonAbstractEnumWithMethod.B); } @Test public void mock_mocking_enum_getter_Issue_2984() { final var mock = mock(TestClass.class); when(mock.getTestEnum()).thenReturn(TestEnum.B); assertThat(mock.getTestEnum()).isEqualTo(TestEnum.B); assertThat(mock.getTestEnum().getValue()).isEqualTo("B"); } static
DeepStubReturnsEnumJava21Test
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/TestTypedSerialization.java
{ "start": 892, "end": 1141 }
class ____ extends Animal { public int boneCount; private Dog() { super(null); } public Dog(String name, int b) { super(name); boneCount = b; } } @JsonTypeName("kitty") static
Dog
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/builditem/nativeimage/ReflectiveClassBuildItem.java
{ "start": 10219, "end": 10709 }
class ____ well as invoking them reflectively. */ public Builder methods(boolean methods) { this.methods = methods; return this; } public Builder methods() { return methods(true); } /** * Configures whether declared methods should be registered for reflection, for query purposes only, * i.e. {@link Class#getDeclaredMethods()}. Setting this enables getting all declared methods for the
as
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/netty/NettyRemotingServer.java
{ "start": 25330, "end": 28999 }
class ____ extends ChannelDuplexHandler { @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel()); log.info("NETTY SERVER PIPELINE: channelRegistered {}", remoteAddress); super.channelRegistered(ctx); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel()); log.info("NETTY SERVER PIPELINE: channelUnregistered, the channel[{}]", remoteAddress); super.channelUnregistered(ctx); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel()); log.info("NETTY SERVER PIPELINE: channelActive, the channel[{}]", remoteAddress); super.channelActive(ctx); if (NettyRemotingServer.this.channelEventListener != null) { NettyRemotingServer.this.putNettyEvent(new NettyEvent(NettyEventType.CONNECT, remoteAddress, ctx.channel())); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel()); log.info("NETTY SERVER PIPELINE: channelInactive, the channel[{}]", remoteAddress); super.channelInactive(ctx); if (NettyRemotingServer.this.channelEventListener != null) { NettyRemotingServer.this.putNettyEvent(new NettyEvent(NettyEventType.CLOSE, remoteAddress, ctx.channel())); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state().equals(IdleState.ALL_IDLE)) { final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel()); log.warn("NETTY SERVER PIPELINE: IDLE exception [{}]", remoteAddress); RemotingHelper.closeChannel(ctx.channel()); if (NettyRemotingServer.this.channelEventListener != null) { NettyRemotingServer.this .putNettyEvent(new NettyEvent(NettyEventType.IDLE, remoteAddress, ctx.channel())); } } } ctx.fireUserEventTriggered(evt); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel()); log.warn("NETTY SERVER PIPELINE: exceptionCaught {}", remoteAddress); log.warn("NETTY SERVER PIPELINE: exceptionCaught exception.", cause); if (NettyRemotingServer.this.channelEventListener != null) { NettyRemotingServer.this.putNettyEvent(new NettyEvent(NettyEventType.EXCEPTION, remoteAddress, ctx.channel())); } RemotingHelper.closeChannel(ctx.channel()); } } /** * The NettyRemotingServer supports bind multiple ports, each port bound by a SubRemotingServer. The * SubRemotingServer will delegate all the functions to NettyRemotingServer, so the sub server can share all the * resources from its parent server. */
NettyConnectManageHandler
java
playframework__playframework
web/play-openid/src/main/java/play/libs/openid/UserInfo.java
{ "start": 271, "end": 730 }
class ____ { private final String id; private final Map<String, String> attributes; public UserInfo(String id) { this.id = id; this.attributes = Collections.emptyMap(); } public UserInfo(String id, Map<String, String> attributes) { this.id = id; this.attributes = Collections.unmodifiableMap(attributes); } public String id() { return id; } public Map<String, String> attributes() { return attributes; } }
UserInfo
java
apache__flink
flink-formats/flink-json/src/test/java/org/apache/flink/formats/json/JsonSerDeSchemaTest.java
{ "start": 1115, "end": 2529 }
class ____ { private static final JsonSerializationSchema<Event> SERIALIZATION_SCHEMA; private static final JsonDeserializationSchema<Event> DESERIALIZATION_SCHEMA; private static final String JSON = "{\"x\":34,\"y\":\"hello\"}"; static { SERIALIZATION_SCHEMA = new JsonSerializationSchema<>(); SERIALIZATION_SCHEMA.open(new DummyInitializationContext()); DESERIALIZATION_SCHEMA = new JsonDeserializationSchema<>(Event.class); DESERIALIZATION_SCHEMA.open(new DummyInitializationContext()); } @Test void testSrialization() throws IOException { final byte[] serialized = SERIALIZATION_SCHEMA.serialize(new Event(34, "hello")); assertThat(serialized).isEqualTo(JSON.getBytes(StandardCharsets.UTF_8)); } @Test void testDeserialization() throws IOException { final Event deserialized = DESERIALIZATION_SCHEMA.deserialize(JSON.getBytes(StandardCharsets.UTF_8)); assertThat(deserialized).isEqualTo(new Event(34, "hello")); } @Test void testRoundTrip() throws IOException { final Event original = new Event(34, "hello"); final byte[] serialized = SERIALIZATION_SCHEMA.serialize(original); final Event deserialized = DESERIALIZATION_SCHEMA.deserialize(serialized); assertThat(deserialized).isEqualTo(original); } private static
JsonSerDeSchemaTest
java
quarkusio__quarkus
extensions/redis-client/deployment/src/test/java/io/quarkus/redis/deployment/client/patterns/CounterTest.java
{ "start": 1585, "end": 2050 }
class ____ { private final ValueCommands<String, Long> commands; public MyRedisCounter(RedisDataSource ds) { commands = ds.value(Long.class); } public long get(String key) { Long l = commands.get(key); if (l == null) { return 0L; } return l; } public void incr(String key) { commands.incr(key); } } }
MyRedisCounter
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/GenericsParamConverterTest.java
{ "start": 2821, "end": 3249 }
class ____ implements ParamConverter<Wrapper<?>> { @Override public Wrapper<?> fromString(String value) { return new Wrapper<>(Enum.valueOf(TestEnum.class, value)); } @Override public String toString(Wrapper<?> wrapper) { return wrapper != null ? wrapper.getValue().toString() : null; } } } }
WrapperParamConverter
java
redisson__redisson
redisson/src/main/java/org/redisson/config/SentinelServersConfig.java
{ "start": 906, "end": 6988 }
class ____ extends BaseMasterSlaveServersConfig<SentinelServersConfig> { private List<String> sentinelAddresses = new ArrayList<>(); private NatMapper natMapper = NatMapper.direct(); private String masterName; private String sentinelUsername; private String sentinelPassword; /** * Database index used for Redis connection */ private int database = 0; /** * Sentinel scan interval in milliseconds */ private int scanInterval = 1000; private boolean checkSentinelsList = true; private boolean checkSlaveStatusWithSyncing = true; private boolean sentinelsDiscovery = true; public SentinelServersConfig() { } SentinelServersConfig(SentinelServersConfig config) { super(config); setSentinelAddresses(config.getSentinelAddresses()); setMasterName(config.getMasterName()); setDatabase(config.getDatabase()); setScanInterval(config.getScanInterval()); setNatMapper(config.getNatMapper()); setCheckSentinelsList(config.isCheckSentinelsList()); setSentinelUsername(config.getSentinelUsername()); setSentinelPassword(config.getSentinelPassword()); setCheckSlaveStatusWithSyncing(config.isCheckSlaveStatusWithSyncing()); setSentinelsDiscovery(config.isSentinelsDiscovery()); } /** * Master server name used by Redis Sentinel servers and master change monitoring task. * * @param masterName of Redis * @return config */ public SentinelServersConfig setMasterName(String masterName) { this.masterName = masterName; return this; } public String getMasterName() { return masterName; } /** * Username required by the Redis Sentinel servers for authentication. * * @param sentinelUsername of Redis * @return config */ public SentinelServersConfig setSentinelUsername(String sentinelUsername) { this.sentinelUsername = sentinelUsername; return this; } public String getSentinelUsername() { return sentinelUsername; } /** * Password required by the Redis Sentinel servers for authentication. * Used only if sentinel password differs from master and slave. * * @param sentinelPassword of Redis * @return config */ public SentinelServersConfig setSentinelPassword(String sentinelPassword) { this.sentinelPassword = sentinelPassword; return this; } public String getSentinelPassword() { return sentinelPassword; } /** * Add Redis Sentinel node address in host:port format. Multiple nodes at once could be added. * * @param addresses of Redis * @return config */ public SentinelServersConfig addSentinelAddress(String... addresses) { sentinelAddresses.addAll(Arrays.asList(addresses)); return this; } public List<String> getSentinelAddresses() { return sentinelAddresses; } public void setSentinelAddresses(List<String> sentinelAddresses) { this.sentinelAddresses = sentinelAddresses; } /** * Database index used for Redis connection * Default is <code>0</code> * * @param database number * @return config */ public SentinelServersConfig setDatabase(int database) { this.database = database; return this; } public int getDatabase() { return database; } public int getScanInterval() { return scanInterval; } /** * Sentinel scan interval in milliseconds * <p> * Default is <code>1000</code> * * @param scanInterval in milliseconds * @return config */ public SentinelServersConfig setScanInterval(int scanInterval) { this.scanInterval = scanInterval; return this; } /* * Use {@link #setNatMapper(NatMapper)} */ @Deprecated public SentinelServersConfig setNatMap(Map<String, String> natMap) { HostPortNatMapper mapper = new HostPortNatMapper(); mapper.setHostsPortMap(natMap); this.natMapper = mapper; return this; } public NatMapper getNatMapper() { return natMapper; } /** * Defines NAT mapper which maps Redis URI object. * Applied to all Redis connections. * * @see HostNatMapper * @see HostPortNatMapper * * @param natMapper - nat mapper object * @return config */ public SentinelServersConfig setNatMapper(NatMapper natMapper) { this.natMapper = natMapper; return this; } public boolean isCheckSentinelsList() { return checkSentinelsList; } /** * Enables sentinels list check during Redisson startup. * <p> * Default is <code>true</code> * * @param checkSentinelsList - boolean value * @return config */ public SentinelServersConfig setCheckSentinelsList(boolean checkSentinelsList) { this.checkSentinelsList = checkSentinelsList; return this; } public boolean isCheckSlaveStatusWithSyncing() { return checkSlaveStatusWithSyncing; } /** * check node status from sentinel with 'master-link-status' flag * <p> * Default is <code>true</code> * * @param checkSlaveStatusWithSyncing - boolean value * @return config */ public SentinelServersConfig setCheckSlaveStatusWithSyncing(boolean checkSlaveStatusWithSyncing) { this.checkSlaveStatusWithSyncing = checkSlaveStatusWithSyncing; return this; } public boolean isSentinelsDiscovery() { return sentinelsDiscovery; } /** * Enables sentinels discovery. * <p> * Default is <code>true</code> * * @param sentinelsDiscovery - boolean value * @return config */ public SentinelServersConfig setSentinelsDiscovery(boolean sentinelsDiscovery) { this.sentinelsDiscovery = sentinelsDiscovery; return this; } }
SentinelServersConfig
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/remote/core/ServerReloaderRequestHandler.java
{ "start": 1782, "end": 3071 }
class ____ extends RequestHandler<ServerReloadRequest, ServerReloadResponse> { @Autowired private ConnectionManager connectionManager; @Override @Secured(resource = "serverReload", signType = SignType.SPECIFIED, apiType = ApiType.INNER_API) public ServerReloadResponse handle(ServerReloadRequest request, RequestMeta meta) throws NacosException { ServerReloadResponse response = new ServerReloadResponse(); Loggers.REMOTE.info("server reload request receive,reload count={},redirectServer={},requestIp={}", request.getReloadCount(), request.getReloadServer(), meta.getClientIp()); int reloadCount = request.getReloadCount(); Map<String, String> filter = new HashMap<>(2); filter.put(RemoteConstants.LABEL_SOURCE, RemoteConstants.LABEL_SOURCE_SDK); int sdkCount = connectionManager.currentClientsCount(filter); if (sdkCount <= reloadCount) { response.setMessage("ignore"); } else { reloadCount = (int) Math.max(reloadCount, sdkCount * (1 - RemoteUtils.LOADER_FACTOR)); connectionManager.loadCount(reloadCount, request.getReloadServer()); response.setMessage("ok"); } return response; } }
ServerReloaderRequestHandler
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/WellKnownKeep.java
{ "start": 1382, "end": 8439 }
class ____ { /** * Annotations that exempt variables from being considered unused. * * <p>Try to avoid adding more annotations here. Annotating these annotations with {@code @Keep} * has the same effect; this list is chiefly for third-party annotations which cannot be * annotated. */ private static final ImmutableSet<String> EXEMPTING_VARIABLE_ANNOTATIONS = ImmutableSet.of( "jakarta.persistence.Basic", "jakarta.persistence.Column", "jakarta.persistence.Id", "jakarta.persistence.Version", "jakarta.xml.bind.annotation.XmlElement", "javax.persistence.Basic", "javax.persistence.Column", "javax.persistence.Id", "javax.persistence.Version", "javax.xml.bind.annotation.XmlElement", "net.starlark.java.annot.StarlarkBuiltin", "org.junit.Rule", "org.junit.jupiter.api.extension.RegisterExtension", "org.openqa.selenium.support.FindAll", "org.openqa.selenium.support.FindBy", "org.openqa.selenium.support.FindBys", "org.apache.beam.sdk.transforms.DoFn.TimerId", "org.apache.beam.sdk.transforms.DoFn.StateId", "org.springframework.boot.test.mock.mockito.MockBean"); /** * Annotations that exempt methods from being considered unused. * * <p>Try to avoid adding more annotations here. Annotating these annotations with {@code @Keep} * has the same effect; this list is chiefly for third-party annotations which cannot be * annotated. */ private static final ImmutableSet<String> EXEMPTING_METHOD_ANNOTATIONS = ImmutableSet.of( "android.webkit.JavascriptInterface", "com.fasterxml.jackson.annotation.JsonCreator", "com.fasterxml.jackson.annotation.JsonProperty", "com.fasterxml.jackson.annotation.JsonSetter", "com.fasterxml.jackson.annotation.JsonValue", "com.google.acai.AfterTest", "com.google.acai.BeforeSuite", "com.google.acai.BeforeTest", "com.google.caliper.Benchmark", "com.google.common.eventbus.Subscribe", "com.google.inject.Provides", "com.google.inject.Inject", "com.google.inject.multibindings.ProvidesIntoMap", "com.google.inject.multibindings.ProvidesIntoSet", "com.google.inject.throwingproviders.CheckedProvides", "com.tngtech.java.junit.dataprovider.DataProvider", "jakarta.annotation.PreDestroy", "jakarta.annotation.PostConstruct", "jakarta.inject.Inject", "jakarta.persistence.PostLoad", "jakarta.persistence.PostPersist", "jakarta.persistence.PostRemove", "jakarta.persistence.PostUpdate", "jakarta.persistence.PrePersist", "jakarta.persistence.PreRemove", "jakarta.persistence.PreUpdate", "jakarta.validation.constraints.AssertFalse", "jakarta.validation.constraints.AssertTrue", "javax.annotation.PreDestroy", "javax.annotation.PostConstruct", "javax.inject.Inject", "javax.persistence.PostLoad", "javax.persistence.PostPersist", "javax.persistence.PostRemove", "javax.persistence.PostUpdate", "javax.persistence.PrePersist", "javax.persistence.PreRemove", "javax.persistence.PreUpdate", "javax.validation.constraints.AssertFalse", "javax.validation.constraints.AssertTrue", "net.bytebuddy.asm.Advice.OnMethodEnter", "net.bytebuddy.asm.Advice.OnMethodExit", "org.apache.beam.sdk.transforms.DoFn.FinishBundle", "org.apache.beam.sdk.transforms.DoFn.ProcessElement", "org.apache.beam.sdk.transforms.DoFn.StartBundle", "org.aspectj.lang.annotation.Pointcut", "org.aspectj.lang.annotation.After", "org.aspectj.lang.annotation.Before", "org.springframework.context.annotation.Bean", "org.testng.annotations.AfterClass", "org.testng.annotations.AfterMethod", "org.testng.annotations.BeforeClass", "org.testng.annotations.BeforeMethod", "org.testng.annotations.DataProvider", "org.junit.jupiter.api.BeforeAll", "org.junit.jupiter.api.AfterAll", "org.junit.jupiter.api.AfterEach", "org.junit.jupiter.api.BeforeEach", "org.junit.jupiter.api.RepeatedTest", "org.junit.jupiter.api.Test", "org.junit.jupiter.params.ParameterizedTest"); private static final ImmutableSet<String> EXEMPTING_CLASS_ANNOTATIONS = ImmutableSet.of("org.junit.jupiter.api.Nested"); private final ImmutableSet<String> exemptingMethodAnnotations; @Inject WellKnownKeep(ErrorProneFlags flags) { this.exemptingMethodAnnotations = ImmutableSet.<String>builder() .addAll(EXEMPTING_METHOD_ANNOTATIONS) .addAll(flags.getSetOrEmpty("UnusedMethod:ExemptingMethodAnnotations")) .build(); } public final boolean shouldKeep(VariableTree tree) { return shouldKeep(tree, tree.getModifiers(), EXEMPTING_VARIABLE_ANNOTATIONS); } public final boolean shouldKeep(MethodTree tree) { return shouldKeep(tree, tree.getModifiers(), exemptingMethodAnnotations); } public final boolean shouldKeep(ClassTree tree) { return shouldKeep(tree, tree.getModifiers(), EXEMPTING_CLASS_ANNOTATIONS); } public final boolean shouldKeep(Tree tree) { return firstNonNull( new SimpleTreeVisitor<Boolean, Void>() { @Override public Boolean visitVariable(VariableTree tree, Void unused) { return shouldKeep(tree); } @Override public Boolean visitMethod(MethodTree tree, Void unused) { return shouldKeep(tree); } @Override public Boolean visitClass(ClassTree tree, Void unused) { return shouldKeep(tree); } }.visit(tree, null), false); } private final boolean shouldKeep( Tree tree, ModifiersTree modifiers, ImmutableSet<String> exemptingAnnotations) { if (ASTHelpers.shouldKeep(tree)) { return true; } if (exemptedByAnnotation(modifiers.getAnnotations(), exemptingAnnotations)) { return true; } return false; } /** * Looks at the list of {@code annotations} and see if there is any annotation which exists {@code * exemptingAnnotations}. */ private static boolean exemptedByAnnotation( List<? extends AnnotationTree> annotations, ImmutableSet<String> exemptingAnnotations) { for (AnnotationTree annotation : annotations) { Type annotationType = ASTHelpers.getType(annotation); if (annotationType == null) { continue; } TypeSymbol tsym = annotationType.tsym; if (exemptingAnnotations.contains(tsym.getQualifiedName().toString())) { return true; } } return false; } }
WellKnownKeep
java
spring-projects__spring-boot
module/spring-boot-liquibase/src/main/java/org/springframework/boot/liquibase/autoconfigure/LiquibaseConnectionDetails.java
{ "start": 1884, "end": 2210 }
class ____ or {@code null} * @see #getJdbcUrl() * @see DatabaseDriver#fromJdbcUrl(String) * @see DatabaseDriver#getDriverClassName() */ @Nullable default String getDriverClassName() { String jdbcUrl = getJdbcUrl(); return (jdbcUrl != null) ? DatabaseDriver.fromJdbcUrl(jdbcUrl).getDriverClassName() : null; } }
name
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java
{ "start": 14659, "end": 16092 }
class ____ implements ParameterNameDiscoverer { private static final ParameterNameDiscoverer DEFAULT_DELEGATE = new DefaultParameterNameDiscoverer(); private static final ParameterNameDiscoverer LENIENT = new Discoverer(DEFAULT_DELEGATE, (message) -> { }); private static final ParameterNameDiscoverer STRICT = new Discoverer(DEFAULT_DELEGATE, (message) -> { throw new IllegalStateException(message.toString()); }); private final ParameterNameDiscoverer delegate; private final Consumer<LogMessage> noParameterNamesHandler; private Discoverer(ParameterNameDiscoverer delegate, Consumer<LogMessage> noParameterNamesHandler) { this.delegate = delegate; this.noParameterNamesHandler = noParameterNamesHandler; } @Override public String[] getParameterNames(Method method) { throw new UnsupportedOperationException(); } @Override public @Nullable String @Nullable [] getParameterNames(Constructor<?> constructor) { @Nullable String @Nullable [] names = this.delegate.getParameterNames(constructor); if (names != null) { return names; } LogMessage message = LogMessage.format( "Unable to use value object binding with constructor [%s] as parameter names cannot be discovered. " + "Ensure that the compiler uses the '-parameters' flag", constructor); this.noParameterNamesHandler.accept(message); logger.debug(message); return null; } } }
Discoverer
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java
{ "start": 840, "end": 1195 }
class ____ extends RpcException { public TriRpcStatus getStatus() { return status; } private final TriRpcStatus status; public StatusRpcException(TriRpcStatus status) { super(TriRpcStatus.triCodeToDubboCode(status.code), status.toMessageWithoutCause(), status.cause); this.status = status; } }
StatusRpcException
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/JHLogAnalyzer.java
{ "start": 7827, "end": 8420 }
enum ____ { STAT_ALL_SLOT_TIME (AccumulatingReducer.VALUE_TYPE_LONG + "allSlotTime"), STAT_FAILED_SLOT_TIME (AccumulatingReducer.VALUE_TYPE_LONG + "failedSlotTime"), STAT_SUBMIT_PENDING_SLOT_TIME (AccumulatingReducer.VALUE_TYPE_LONG + "submitPendingSlotTime"), STAT_LAUNCHED_PENDING_SLOT_TIME (AccumulatingReducer.VALUE_TYPE_LONG + "launchedPendingSlotTime"); private String statName = null; private StatSeries(String name) {this.statName = name;} public String toString() {return statName;} } private static
StatSeries
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/annotation/LookupAnnotationTests.java
{ "start": 7988, "end": 8063 }
class ____ extends NumberStore<Float> { } public abstract static
FloatStore
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/PahoMqtt5ComponentBuilderFactory.java
{ "start": 31429, "end": 37182 }
class ____ extends AbstractComponentBuilder<PahoMqtt5Component> implements PahoMqtt5ComponentBuilder { @Override protected PahoMqtt5Component buildConcreteComponent() { return new PahoMqtt5Component(); } private org.apache.camel.component.paho.mqtt5.PahoMqtt5Configuration getOrCreateConfiguration(PahoMqtt5Component component) { if (component.getConfiguration() == null) { component.setConfiguration(new org.apache.camel.component.paho.mqtt5.PahoMqtt5Configuration()); } return component.getConfiguration(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "automaticReconnect": getOrCreateConfiguration((PahoMqtt5Component) component).setAutomaticReconnect((boolean) value); return true; case "brokerUrl": getOrCreateConfiguration((PahoMqtt5Component) component).setBrokerUrl((java.lang.String) value); return true; case "cleanStart": getOrCreateConfiguration((PahoMqtt5Component) component).setCleanStart((boolean) value); return true; case "clientId": getOrCreateConfiguration((PahoMqtt5Component) component).setClientId((java.lang.String) value); return true; case "configuration": ((PahoMqtt5Component) component).setConfiguration((org.apache.camel.component.paho.mqtt5.PahoMqtt5Configuration) value); return true; case "connectionTimeout": getOrCreateConfiguration((PahoMqtt5Component) component).setConnectionTimeout((int) value); return true; case "filePersistenceDirectory": getOrCreateConfiguration((PahoMqtt5Component) component).setFilePersistenceDirectory((java.lang.String) value); return true; case "keepAliveInterval": getOrCreateConfiguration((PahoMqtt5Component) component).setKeepAliveInterval((int) value); return true; case "maxReconnectDelay": getOrCreateConfiguration((PahoMqtt5Component) component).setMaxReconnectDelay((int) value); return true; case "persistence": getOrCreateConfiguration((PahoMqtt5Component) component).setPersistence((org.apache.camel.component.paho.mqtt5.PahoMqtt5Persistence) value); return true; case "qos": getOrCreateConfiguration((PahoMqtt5Component) component).setQos((int) value); return true; case "receiveMaximum": getOrCreateConfiguration((PahoMqtt5Component) component).setReceiveMaximum((int) value); return true; case "retained": getOrCreateConfiguration((PahoMqtt5Component) component).setRetained((boolean) value); return true; case "serverURIs": getOrCreateConfiguration((PahoMqtt5Component) component).setServerURIs((java.lang.String) value); return true; case "sessionExpiryInterval": getOrCreateConfiguration((PahoMqtt5Component) component).setSessionExpiryInterval((long) value); return true; case "willMqttProperties": getOrCreateConfiguration((PahoMqtt5Component) component).setWillMqttProperties((org.eclipse.paho.mqttv5.common.packet.MqttProperties) value); return true; case "willPayload": getOrCreateConfiguration((PahoMqtt5Component) component).setWillPayload((java.lang.String) value); return true; case "willQos": getOrCreateConfiguration((PahoMqtt5Component) component).setWillQos((int) value); return true; case "willRetained": getOrCreateConfiguration((PahoMqtt5Component) component).setWillRetained((boolean) value); return true; case "willTopic": getOrCreateConfiguration((PahoMqtt5Component) component).setWillTopic((java.lang.String) value); return true; case "bridgeErrorHandler": ((PahoMqtt5Component) component).setBridgeErrorHandler((boolean) value); return true; case "manualAcksEnabled": getOrCreateConfiguration((PahoMqtt5Component) component).setManualAcksEnabled((boolean) value); return true; case "lazyStartProducer": ((PahoMqtt5Component) component).setLazyStartProducer((boolean) value); return true; case "autowiredEnabled": ((PahoMqtt5Component) component).setAutowiredEnabled((boolean) value); return true; case "client": ((PahoMqtt5Component) component).setClient((org.eclipse.paho.mqttv5.client.MqttClient) value); return true; case "customWebSocketHeaders": getOrCreateConfiguration((PahoMqtt5Component) component).setCustomWebSocketHeaders((java.util.Map) value); return true; case "executorServiceTimeout": getOrCreateConfiguration((PahoMqtt5Component) component).setExecutorServiceTimeout((int) value); return true; case "httpsHostnameVerificationEnabled": getOrCreateConfiguration((PahoMqtt5Component) component).setHttpsHostnameVerificationEnabled((boolean) value); return true; case "password": getOrCreateConfiguration((PahoMqtt5Component) component).setPassword((java.lang.String) value); return true; case "socketFactory": getOrCreateConfiguration((PahoMqtt5Component) component).setSocketFactory((javax.net.SocketFactory) value); return true; case "sslClientProps": getOrCreateConfiguration((PahoMqtt5Component) component).setSslClientProps((java.util.Properties) value); return true; case "sslHostnameVerifier": getOrCreateConfiguration((PahoMqtt5Component) component).setSslHostnameVerifier((javax.net.ssl.HostnameVerifier) value); return true; case "userName": getOrCreateConfiguration((PahoMqtt5Component) component).setUserName((java.lang.String) value); return true; default: return false; } } } }
PahoMqtt5ComponentBuilderImpl
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/MapFile.java
{ "start": 33875, "end": 34112 }
class ____ " + dir + ", expected" + keyClass.getName() + ", got " + dataReader.getKeyClass().getName()); } if (!dataReader.getValueClass().equals(valueClass)) { throw new Exception(dr + "Wrong value
in
java
quarkusio__quarkus
extensions/micrometer/deployment/src/test/java/io/quarkus/micrometer/deployment/export/PrometheusEnabledTest.java
{ "start": 552, "end": 2742 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .setFlatClassPath(true) .withConfigurationResource("test-logging.properties") .overrideConfigKey("quarkus.micrometer.binder-enabled-default", "false") .overrideConfigKey("quarkus.micrometer.export.prometheus.enabled", "true") .overrideConfigKey("quarkus.micrometer.registry-enabled-default", "false") .overrideConfigKey("quarkus.redis.devservices.enabled", "false") .overrideConfigKey("quarkus.http.enable-compression", "true") .withEmptyApplication(); @Inject MeterRegistry registry; @Inject PrometheusMeterRegistry promRegistry; @Test public void testMeterRegistryPresent() { // Prometheus is enabled (only registry) Assertions.assertNotNull(registry, "A registry should be configured"); Set<MeterRegistry> subRegistries = ((CompositeMeterRegistry) registry).getRegistries(); Assertions.assertEquals(1, subRegistries.size(), "There should be only one configured subregistry. Found " + subRegistries); PrometheusMeterRegistry subPromRegistry = (PrometheusMeterRegistry) subRegistries.iterator().next(); Assertions.assertEquals(PrometheusMeterRegistry.class, subPromRegistry.getClass(), "Should be PrometheusMeterRegistry"); Assertions.assertEquals(subPromRegistry, promRegistry, "Should be the same bean as the injected PrometheusMeterRegistry"); } @Test public void metricsEndpoint() { // RestAssured prepends /app for us given() .accept("application/json") .get("/q/metrics") .then() .log().all() .statusCode(406); given() .get("/q/metrics") .then() .statusCode(200); given().header("Accept-Encoding", "gzip") .get("/q/metrics") .then() .statusCode(200) .header("content-encoding", is("gzip")); } }
PrometheusEnabledTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeKey.java
{ "start": 856, "end": 2007 }
class ____ implements Writeable { private final Comparable[] values; CompositeKey(Comparable... values) { this.values = values; } CompositeKey(StreamInput in) throws IOException { values = in.readArray(i -> (Comparable) i.readGenericValue(), Comparable[]::new); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeArray(StreamOutput::writeGenericValue, values); } Comparable[] values() { return values; } int size() { return values.length; } Comparable get(int pos) { assert pos < values.length; return values[pos]; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CompositeKey that = (CompositeKey) o; return Arrays.equals(values, that.values); } @Override public int hashCode() { return Arrays.hashCode(values); } @Override public String toString() { return "CompositeKey{" + "values=" + Arrays.toString(values) + '}'; } }
CompositeKey
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/cluster/allocation/AwarenessAllocationIT.java
{ "start": 1881, "end": 13860 }
class ____ extends ESIntegTestCase { private static final Logger logger = LogManager.getLogger(AwarenessAllocationIT.class); @Override protected int numberOfReplicas() { return 1; } public void testSimpleAwareness() throws Exception { Settings commonSettings = Settings.builder().put("cluster.routing.allocation.awareness.attributes", "rack_id").build(); logger.info("--> starting 2 nodes on the same rack"); internalCluster().startNodes(2, Settings.builder().put(commonSettings).put("node.attr.rack_id", "rack_1").build()); createIndex("test1"); createIndex("test2"); NumShards test1 = getNumShards("test1"); NumShards test2 = getNumShards("test2"); // no replicas will be allocated as both indices end up on a single node final int totalPrimaries = test1.numPrimaries + test2.numPrimaries; ensureGreen(); final List<String> indicesToClose = randomSubsetOf(Arrays.asList("test1", "test2")); indicesToClose.forEach(indexToClose -> assertAcked(indicesAdmin().prepareClose(indexToClose).get())); logger.info("--> starting 1 node on a different rack"); final String node3 = internalCluster().startNode(Settings.builder().put(commonSettings).put("node.attr.rack_id", "rack_2").build()); // On slow machines the initial relocation might be delayed assertBusy(() -> { logger.info("--> waiting for no relocation"); ClusterHealthResponse clusterHealth = clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT) .setIndices("test1", "test2") .setWaitForEvents(Priority.LANGUID) .setWaitForGreenStatus() .setWaitForNodes("3") .setWaitForNoRelocatingShards(true) .get(); assertThat("Cluster health request timed out", clusterHealth.isTimedOut(), equalTo(false)); logger.info("--> checking current state"); ClusterState clusterState = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); // check that closed indices are effectively closed final List<String> notClosedIndices = indicesToClose.stream() .filter(index -> clusterState.metadata().getProject().index(index).getState() != State.CLOSE) .toList(); assertThat("Some indices not closed", notClosedIndices, empty()); // verify that we have all the primaries on node3 Map<String, Integer> counts = computeShardCounts(clusterState); assertThat(counts.get(node3), equalTo(totalPrimaries)); }, 10, TimeUnit.SECONDS); } public void testAwarenessZones() { Settings commonSettings = Settings.builder() .put(AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_FORCE_GROUP_SETTING.getKey() + "zone.values", "a,b") .put(AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING.getKey(), "zone") .build(); logger.info("--> starting 4 nodes on different zones"); List<String> nodes = internalCluster().startNodes( Settings.builder().put(commonSettings).put("node.attr.zone", "a").build(), Settings.builder().put(commonSettings).put("node.attr.zone", "b").build(), Settings.builder().put(commonSettings).put("node.attr.zone", "b").build(), Settings.builder().put(commonSettings).put("node.attr.zone", "a").build() ); String A_0 = nodes.get(0); String B_0 = nodes.get(1); String B_1 = nodes.get(2); String A_1 = nodes.get(3); logger.info("--> waiting for nodes to form a cluster"); ClusterHealthResponse health = clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForNodes("4").get(); assertThat(health.isTimedOut(), equalTo(false)); createIndex("test", 5, 1); if (randomBoolean()) { assertAcked(indicesAdmin().prepareClose("test")); } logger.info("--> waiting for shards to be allocated"); health = clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT) .setIndices("test") .setWaitForEvents(Priority.LANGUID) .setWaitForGreenStatus() .setWaitForNoRelocatingShards(true) .get(); assertThat(health.isTimedOut(), equalTo(false)); ClusterState clusterState = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); Map<String, Integer> counts = computeShardCounts(clusterState); assertThat(counts.get(A_1), anyOf(equalTo(2), equalTo(3))); assertThat(counts.get(B_1), anyOf(equalTo(2), equalTo(3))); assertThat(counts.get(A_0), anyOf(equalTo(2), equalTo(3))); assertThat(counts.get(B_0), anyOf(equalTo(2), equalTo(3))); } public void testAwarenessZonesIncrementalNodes() { Settings commonSettings = Settings.builder() .put("cluster.routing.allocation.awareness.force.zone.values", "a,b") .put("cluster.routing.allocation.awareness.attributes", "zone") .build(); logger.info("--> starting 2 nodes on zones 'a' & 'b'"); List<String> nodes = internalCluster().startNodes( Settings.builder().put(commonSettings).put("node.attr.zone", "a").build(), Settings.builder().put(commonSettings).put("node.attr.zone", "b").build() ); String A_0 = nodes.get(0); String B_0 = nodes.get(1); createIndex("test", 5, 1); if (randomBoolean()) { assertAcked(indicesAdmin().prepareClose("test")); } ClusterHealthResponse health = clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT) .setIndices("test") .setWaitForEvents(Priority.LANGUID) .setWaitForGreenStatus() .setWaitForNodes("2") .setWaitForNoRelocatingShards(true) .get(); assertThat(health.isTimedOut(), equalTo(false)); ClusterState clusterState = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); Map<String, Integer> counts = computeShardCounts(clusterState); assertThat(counts.get(A_0), equalTo(5)); assertThat(counts.get(B_0), equalTo(5)); logger.info("--> starting another node in zone 'b'"); String B_1 = internalCluster().startNode(Settings.builder().put(commonSettings).put("node.attr.zone", "b").build()); health = clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT) .setIndices("test") .setWaitForEvents(Priority.LANGUID) .setWaitForGreenStatus() .setWaitForNodes("3") .get(); assertThat(health.isTimedOut(), equalTo(false)); ClusterRerouteUtils.reroute(client()); health = clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT) .setIndices("test") .setWaitForEvents(Priority.LANGUID) .setWaitForGreenStatus() .setWaitForNodes("3") .setWaitForActiveShards(10) .setWaitForNoRelocatingShards(true) .get(); assertThat(health.isTimedOut(), equalTo(false)); clusterState = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); counts = computeShardCounts(clusterState); assertThat(counts.get(A_0), equalTo(5)); assertThat(counts.get(B_0), equalTo(3)); assertThat(counts.get(B_1), equalTo(2)); String noZoneNode = internalCluster().startNode(); health = clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT) .setIndices("test") .setWaitForEvents(Priority.LANGUID) .setWaitForGreenStatus() .setWaitForNodes("4") .get(); assertThat(health.isTimedOut(), equalTo(false)); ClusterRerouteUtils.reroute(client()); health = clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT) .setIndices("test") .setWaitForEvents(Priority.LANGUID) .setWaitForGreenStatus() .setWaitForNodes("4") .setWaitForActiveShards(10) .setWaitForNoRelocatingShards(true) .get(); assertThat(health.isTimedOut(), equalTo(false)); clusterState = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); counts = computeShardCounts(clusterState); assertThat(counts.get(A_0), equalTo(5)); assertThat(counts.get(B_0), equalTo(3)); assertThat(counts.get(B_1), equalTo(2)); assertThat(counts.containsKey(noZoneNode), equalTo(false)); updateClusterSettings(Settings.builder().put("cluster.routing.allocation.awareness.attributes", "")); health = clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT) .setIndices("test") .setWaitForEvents(Priority.LANGUID) .setWaitForGreenStatus() .setWaitForNodes("4") .setWaitForActiveShards(10) .setWaitForNoRelocatingShards(true) .get(); assertThat(health.isTimedOut(), equalTo(false)); clusterState = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); counts = computeShardCounts(clusterState); assertThat(counts.get(A_0), equalTo(3)); assertThat(counts.get(B_0), equalTo(3)); assertThat(counts.get(B_1), equalTo(2)); assertThat(counts.get(noZoneNode), equalTo(2)); } public void testForceAwarenessSettingValidation() { internalCluster().startNode(); final String prefix = AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_FORCE_GROUP_SETTING.getKey(); final IllegalArgumentException illegalArgumentException = expectThrows( IllegalArgumentException.class, clusterAdmin().prepareUpdateSettings(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT) .setPersistentSettings(Settings.builder().put(prefix + "nonsense", "foo")) ); assertThat(illegalArgumentException.getMessage(), containsString("[cluster.routing.allocation.awareness.force.]")); assertThat(illegalArgumentException.getCause(), instanceOf(SettingsException.class)); assertThat(illegalArgumentException.getCause().getMessage(), containsString("nonsense")); assertThat( expectThrows( IllegalArgumentException.class, clusterAdmin().prepareUpdateSettings(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT) .setPersistentSettings(Settings.builder().put(prefix + "attr.not_values", "foo")) ).getMessage(), containsString("[cluster.routing.allocation.awareness.force.attr.not_values]") ); assertThat( expectThrows( IllegalArgumentException.class, clusterAdmin().prepareUpdateSettings(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT) .setPersistentSettings(Settings.builder().put(prefix + "attr.values.junk", "foo")) ).getMessage(), containsString("[cluster.routing.allocation.awareness.force.attr.values.junk]") ); } Map<String, Integer> computeShardCounts(ClusterState clusterState) { Map<String, Integer> counts = new HashMap<>(); for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) { for (int shardId = 0; shardId < indexRoutingTable.size(); shardId++) { final IndexShardRoutingTable indexShardRoutingTable = indexRoutingTable.shard(shardId); for (int copy = 0; copy < indexShardRoutingTable.size(); copy++) { counts.merge(clusterState.nodes().get(indexShardRoutingTable.shard(copy).currentNodeId()).getName(), 1, Integer::sum); } } } return counts; } }
AwarenessAllocationIT
java
google__guava
android/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java
{ "start": 9159, "end": 9234 }
class ____ extends RuntimeException {} private static
SampleRuntimeException
java
spring-projects__spring-boot
module/spring-boot-actuator/src/testFixtures/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointInfrastructureProvider.java
{ "start": 987, "end": 1559 }
interface ____ { /** * Specify if the given {@link Infrastructure} is supported. * @param infrastructure the infrastructure to target * @return {@code true} if this instance can provide the configuration */ boolean supports(Infrastructure infrastructure); /** * Return the configuration to use for the given {@code infrastructure}. * @param infrastructure the infrastructure to target * @return the configuration for that infrastructure */ List<Class<?>> getInfrastructureConfiguration(Infrastructure infrastructure); }
WebEndpointInfrastructureProvider
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/IndexedInputGate.java
{ "start": 1260, "end": 2929 }
class ____ extends InputGate implements CheckpointableInput { /** Returns the index of this input gate. Only supported on */ public abstract int getGateIndex(); /** Returns the list of channels that have not received EndOfPartitionEvent. */ public abstract List<InputChannelInfo> getUnfinishedChannels(); @Override public void checkpointStarted(CheckpointBarrier barrier) throws CheckpointException { for (int index = 0, numChannels = getNumberOfInputChannels(); index < numChannels; index++) { getChannel(index).checkpointStarted(barrier); } } @Override public void checkpointStopped(long cancelledCheckpointId) { for (int index = 0, numChannels = getNumberOfInputChannels(); index < numChannels; index++) { getChannel(index).checkpointStopped(cancelledCheckpointId); } } @Override public int getInputGateIndex() { return getGateIndex(); } @Override public void blockConsumption(InputChannelInfo channelInfo) { // Unused. Network stack is blocking consumption automatically by revoking credits. } @Override public void convertToPriorityEvent(int channelIndex, int sequenceNumber) throws IOException { getChannel(channelIndex).convertToPriorityEvent(sequenceNumber); } /** * Returns the type of this input channel's consumed result partition. * * @return consumed result partition type */ public abstract ResultPartitionType getConsumedPartitionType(); public abstract void triggerDebloating(); }
IndexedInputGate
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/event/ContextRestartedEvent.java
{ "start": 1151, "end": 1454 }
class ____ extends ContextStartedEvent { /** * Create a new {@code ContextRestartedEvent}. * @param source the {@code ApplicationContext} that has been restarted * (must not be {@code null}) */ public ContextRestartedEvent(ApplicationContext source) { super(source); } }
ContextRestartedEvent
java
spring-projects__spring-boot
build-plugin/spring-boot-maven-plugin/src/intTest/projects/test-run/src/test/java/org/test/TestSampleApplication.java
{ "start": 821, "end": 1047 }
class ____ = " + TestSampleApplication.class.getName()); int i = 1; for (String entry : ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) { System.out.println(i++ + ". " + entry); } } }
name
java
quarkusio__quarkus
extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CodeFlowDevModeDefaultTenantTestCase.java
{ "start": 768, "end": 3668 }
class ____ { private static Class<?>[] testClasses = { ProtectedResource.class, UnprotectedResource.class }; @RegisterExtension static final QuarkusDevModeTest test = new QuarkusDevModeTest() .withApplicationRoot((jar) -> jar .addClasses(testClasses) .addAsResource("application-dev-mode-default-tenant.properties", "application.properties")); @Test public void testAccessAndRefreshTokenInjectionDevMode() throws IOException, InterruptedException { try (final WebClient webClient = createWebClient()) { try { webClient.getPage("http://localhost:8080/protected"); fail("Exception is expected because by default the bearer token is required"); } catch (FailingHttpStatusCodeException ex) { // Reported by Quarkus assertEquals(401, ex.getStatusCode()); } // Enable 'web-app' application type test.modifyResourceFile("application.properties", s -> s.replace("#quarkus.oidc.application-type=web-app", "quarkus.oidc.application-type=web-app")); HtmlPage page = webClient.getPage("http://localhost:8080/protected"); assertEquals("Sign in to quarkus", page.getTitleText()); HtmlForm loginForm = page.getForms().get(0); loginForm.getInputByName("username").setValueAttribute("alice"); loginForm.getInputByName("password").setValueAttribute("alice"); page = loginForm.getButtonByName("login").click(); assertEquals("alice", page.getBody().asNormalizedText()); webClient.getCookieManager().clearCookies(); // Enable the invalid scope test.modifyResourceFile("application.properties", s -> s.replace("#quarkus.oidc.authentication.scopes=invalid-scope", "quarkus.oidc.authentication.scopes=invalid-scope")); try { webClient.getPage("http://localhost:8080/protected"); fail("Exception is expected because an invalid scope is provided"); } catch (FailingHttpStatusCodeException ex) { assertEquals(401, ex.getStatusCode()); assertTrue(ex.getResponse().getContentAsString() .contains( "Authorization code flow has failed, error code: invalid_scope, error description: Invalid scopes: openid invalid-scope"), "The reason behind 401 must be returned in devmode"); } } } private WebClient createWebClient() { WebClient webClient = new WebClient(); webClient.setCssErrorHandler(new SilentCssErrorHandler()); return webClient; } }
CodeFlowDevModeDefaultTenantTestCase
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/config/ViewControllerBeanDefinitionParser.java
{ "start": 2156, "end": 6210 }
class ____ implements BeanDefinitionParser { private static final String HANDLER_MAPPING_BEAN_NAME = "org.springframework.web.servlet.config.viewControllerHandlerMapping"; @Override @SuppressWarnings("unchecked") public @Nullable BeanDefinition parse(Element element, ParserContext parserContext) { Object source = parserContext.extractSource(element); // Register SimpleUrlHandlerMapping for view controllers BeanDefinition hm = registerHandlerMapping(parserContext, source); // Ensure BeanNameUrlHandlerMapping (SPR-8289) and default HandlerAdapters are not "turned off" MvcNamespaceUtils.registerDefaultComponents(parserContext, source); // Create view controller bean definition RootBeanDefinition controller = new RootBeanDefinition(ParameterizableViewController.class); controller.setSource(source); HttpStatusCode statusCode = null; if (element.hasAttribute("status-code")) { int statusValue = Integer.parseInt(element.getAttribute("status-code")); statusCode = HttpStatusCode.valueOf(statusValue); } String name = element.getLocalName(); switch (name) { case "view-controller" -> { if (element.hasAttribute("view-name")) { controller.getPropertyValues().add("viewName", element.getAttribute("view-name")); } if (statusCode != null) { controller.getPropertyValues().add("statusCode", statusCode); } } case "redirect-view-controller" -> controller.getPropertyValues().add("view", getRedirectView(element, statusCode, source)); case "status-controller" -> { controller.getPropertyValues().add("statusCode", statusCode); controller.getPropertyValues().add("statusOnly", true); } default -> // Should never happen... throw new IllegalStateException("Unexpected tag name: " + name); } Map<String, BeanDefinition> urlMap = (Map<String, BeanDefinition>) hm.getPropertyValues().get("urlMap"); if (urlMap == null) { urlMap = new ManagedMap<>(); hm.getPropertyValues().add("urlMap", urlMap); } urlMap.put(element.getAttribute("path"), controller); return null; } private BeanDefinition registerHandlerMapping(ParserContext context, @Nullable Object source) { if (context.getRegistry().containsBeanDefinition(HANDLER_MAPPING_BEAN_NAME)) { return context.getRegistry().getBeanDefinition(HANDLER_MAPPING_BEAN_NAME); } RootBeanDefinition beanDef = new RootBeanDefinition(SimpleUrlHandlerMapping.class); beanDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); context.getRegistry().registerBeanDefinition(HANDLER_MAPPING_BEAN_NAME, beanDef); context.registerComponent(new BeanComponentDefinition(beanDef, HANDLER_MAPPING_BEAN_NAME)); beanDef.setSource(source); beanDef.getPropertyValues().add("order", "1"); MvcNamespaceUtils.configurePathMatching(beanDef, context, source); beanDef.getPropertyValues().add("urlPathHelper", MvcNamespaceUtils.registerUrlPathHelper(null, context, source)); RuntimeBeanReference corsConfigurationsRef = MvcNamespaceUtils.registerCorsConfigurations(null, context, source); beanDef.getPropertyValues().add("corsConfigurations", corsConfigurationsRef); return beanDef; } private RootBeanDefinition getRedirectView(Element element, @Nullable HttpStatusCode status, @Nullable Object source) { RootBeanDefinition redirectView = new RootBeanDefinition(RedirectView.class); redirectView.setSource(source); redirectView.getConstructorArgumentValues().addIndexedArgumentValue(0, element.getAttribute("redirect-url")); if (status != null) { redirectView.getPropertyValues().add("statusCode", status); } if (element.hasAttribute("context-relative")) { redirectView.getPropertyValues().add("contextRelative", element.getAttribute("context-relative")); } else { redirectView.getPropertyValues().add("contextRelative", true); } if (element.hasAttribute("keep-query-params")) { redirectView.getPropertyValues().add("propagateQueryParams", element.getAttribute("keep-query-params")); } return redirectView; } }
ViewControllerBeanDefinitionParser
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/introspect/IgnoredCreatorProperty1572Test.java
{ "start": 480, "end": 579 }
class ____ { public String str; public String otherStr; } static
InnerTest
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/view/feed/AbstractAtomFeedView.java
{ "start": 1955, "end": 3908 }
class ____ extends AbstractFeedView<Feed> { /** * The default feed type used. */ public static final String DEFAULT_FEED_TYPE = "atom_1.0"; private String feedType = DEFAULT_FEED_TYPE; public AbstractAtomFeedView() { setContentType("application/atom+xml"); } /** * Set the Rome feed type to use. * <p>Defaults to Atom 1.0. * @see Feed#setFeedType(String) * @see #DEFAULT_FEED_TYPE */ public void setFeedType(String feedType) { this.feedType = feedType; } /** * Create a new Feed instance to hold the entries. * <p>By default returns an Atom 1.0 feed, but the subclass can specify any Feed. * @see #setFeedType(String) */ @Override protected Feed newFeed() { return new Feed(this.feedType); } /** * Invokes {@link #buildFeedEntries(Map, HttpServletRequest, HttpServletResponse)} * to get a list of feed entries. */ @Override protected final void buildFeedEntries(Map<String, Object> model, Feed feed, HttpServletRequest request, HttpServletResponse response) throws Exception { List<Entry> entries = buildFeedEntries(model, request, response); feed.setEntries(entries); } /** * Subclasses must implement this method to build feed entries, given the model. * <p>Note that the passed-in HTTP response is just supposed to be used for * setting cookies or other HTTP headers. The built feed itself will automatically * get written to the response after this method returns. * @param model the model Map * @param request in case we need locale etc. Shouldn't look at attributes. * @param response in case we need to set cookies. Shouldn't write to it. * @return the feed entries to be added to the feed * @throws Exception any exception that occurred during document building * @see Entry */ protected abstract List<Entry> buildFeedEntries( Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception; }
AbstractAtomFeedView
java
apache__camel
components/camel-kudu/src/test/java/org/apache/camel/component/kudu/IntegrationKuduConfiguration.java
{ "start": 1549, "end": 2624 }
class ____ implements BeforeEachCallback, AfterEachCallback { private static final Logger LOG = LoggerFactory.getLogger(IntegrationKuduConfiguration.class); private final Internal internal = new Internal(); private boolean hasKuduHarness; public IntegrationKuduConfiguration() { } public KuduClient getClient() { return internal.getClient(); } public void setupCamelContext(ModelCamelContext context) { internal.setupCamelContext(context); } @Override public void afterEach(ExtensionContext context) { if (hasKuduHarness) { internal.after(); } } @Override public void beforeEach(ExtensionContext context) { try { internal.before(); hasKuduHarness = true; } catch (Exception e) { hasKuduHarness = false; LOG.debug("Kudu harness is not runnable because: {}", e.getMessage(), e); } } public boolean hasKuduHarness() { return hasKuduHarness; } static
IntegrationKuduConfiguration
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyCaching.java
{ "start": 985, "end": 4056 }
interface ____ { /** * Enable caching with an unlimited time-to-live. */ void enable(); /** * Disable caching. */ void disable(); /** * Set amount of time that an item can live in the cache. Calling this method will * also enable the cache. * @param timeToLive the time to live value. */ void setTimeToLive(Duration timeToLive); /** * Clear the cache and force it to be reloaded on next access. */ void clear(); /** * Override caching to temporarily enable it. Once caching is no longer needed the * returned {@link CacheOverride} should be closed to restore previous cache settings. * @return a {@link CacheOverride} * @since 3.5.0 */ CacheOverride override(); /** * Get for all configuration property sources in the environment. * @param environment the spring environment * @return a caching instance that controls all sources in the environment */ static ConfigurationPropertyCaching get(Environment environment) { return get(environment, null); } /** * Get for a specific configuration property source in the environment. * @param environment the spring environment * @param underlyingSource the * {@link ConfigurationPropertySource#getUnderlyingSource() underlying source} that * must match * @return a caching instance that controls the matching source */ static ConfigurationPropertyCaching get(Environment environment, @Nullable Object underlyingSource) { Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment); return get(sources, underlyingSource); } /** * Get for all specified configuration property sources. * @param sources the configuration property sources * @return a caching instance that controls the sources */ static ConfigurationPropertyCaching get(Iterable<ConfigurationPropertySource> sources) { return get(sources, null); } /** * Get for a specific configuration property source in the specified configuration * property sources. * @param sources the configuration property sources * @param underlyingSource the * {@link ConfigurationPropertySource#getUnderlyingSource() underlying source} that * must match * @return a caching instance that controls the matching source */ static ConfigurationPropertyCaching get(Iterable<ConfigurationPropertySource> sources, @Nullable Object underlyingSource) { Assert.notNull(sources, "'sources' must not be null"); if (underlyingSource == null) { return new ConfigurationPropertySourcesCaching(sources); } for (ConfigurationPropertySource source : sources) { if (source.getUnderlyingSource() == underlyingSource) { ConfigurationPropertyCaching caching = CachingConfigurationPropertySource.find(source); if (caching != null) { return caching; } } } throw new IllegalStateException("Unable to find cache from configuration property sources"); } /** * {@link AutoCloseable} used to control a * {@link ConfigurationPropertyCaching#override() cache override}. * * @since 3.5.0 */
ConfigurationPropertyCaching
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/MonoMap.java
{ "start": 1114, "end": 2200 }
class ____<T, R> extends InternalMonoOperator<T, R> { final Function<? super T, ? extends R> mapper; /** * Constructs a StreamMap instance with the given source and mapper. * * @param source the source Publisher instance * @param mapper the mapper function * @throws NullPointerException if either {@code source} or {@code mapper} is null. */ MonoMap(Mono<? extends T> source, Function<? super T, ? extends R> mapper) { super(source); this.mapper = Objects.requireNonNull(mapper, "mapper"); } @Override @SuppressWarnings("unchecked") public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super R> actual) { if (actual instanceof Fuseable.ConditionalSubscriber) { Fuseable.ConditionalSubscriber<? super R> cs = (Fuseable.ConditionalSubscriber<? super R>) actual; return new FluxMap.MapConditionalSubscriber<>(cs, mapper); } return new FluxMap.MapSubscriber<>(actual, mapper); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } }
MonoMap
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/InstrumentedLock.java
{ "start": 9086, "end": 9514 }
class ____ { private long suppressedCount = 0; private long maxSuppressedWait = 0; public SuppressedSnapshot(long suppressedCount, long maxWait) { this.suppressedCount = suppressedCount; this.maxSuppressedWait = maxWait; } public long getMaxSuppressedWait() { return maxSuppressedWait; } public long getSuppressedCount() { return suppressedCount; } } }
SuppressedSnapshot
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/idprops/PropertyNamedIdOutOfIdClassTest.java
{ "start": 832, "end": 1812 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { session.persist( new Person( "John Doe", 0 ) ); session.persist( new Person( "John Doe", 1, 1 ) ); session.persist( new Person( "John Doe", 2, 2 ) ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test @JiraKey(value = "HHH-13084") public void testHql(SessionFactoryScope scope) { scope.inTransaction( session -> { assertEquals( 1, session.createQuery( "from Person p where p.id is null", Person.class ).list().size() ); assertEquals( 2, session.createQuery( "from Person p where p.id is not null", Person.class ).list().size() ); assertEquals( 3L, session.createQuery( "select count( p ) from Person p" ).uniqueResult() ); } ); } @Entity(name = "Person") @IdClass(PersonId.class) public static
PropertyNamedIdOutOfIdClassTest
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RSearch.java
{ "start": 1310, "end": 8213 }
interface ____ extends RSearchAsync { /** * Creates an index. * <p> * Code example: * <pre> * search.create("idx", IndexOptions.defaults() * .on(IndexType.HASH) * .prefix(Arrays.asList("doc:")), * FieldIndex.text("t1"), * FieldIndex.tag("t2").withSuffixTrie()); * </pre> * * @param indexName index name * @param options index options * @param fields fields */ void createIndex(String indexName, IndexOptions options, FieldIndex... fields); /** * Executes search over defined index using defined query. * <p> * Code example: * <pre> * SearchResult r = s.search("idx", "*", QueryOptions.defaults() * .returnAttributes(new ReturnAttribute("t1"), new ReturnAttribute("t2"))); * </pre> * * @param indexName index name * @param query query value * @param options query options * @return search result */ SearchResult search(String indexName, String query, QueryOptions options); /** * Executes aggregation over defined index using defined query. * <p> * Code example: * <pre> * AggregationResult r = s.aggregate("idx", "*", AggregationOptions.defaults() * .load("t1", "t2")); * </pre> * * @param indexName index name * @param query query value * @param options aggregation options * @return aggregation result */ AggregationResult aggregate(String indexName, String query, AggregationOptions options); /** * Executes aggregation over defined index using defined query. * <p> * Code example: * <pre> * Iterable<AggregationEntry> r = s.aggregate("idx", "*", IterableAggregationOptions.defaults() * .load("t1", "t2")); * </pre> * * @param indexName index name * @param query query value * @param options iterable aggregationOptions options * @return iterable aggregation result */ Iterable<AggregationEntry> aggregate(String indexName, String query, IterableAggregationOptions options); /** * Adds alias to defined index name * * @param alias alias value * @param indexName index name */ void addAlias(String alias, String indexName); /** * Deletes index alias * * @param alias alias value */ void delAlias(String alias); /** * Adds alias to defined index name. * Re-assigns the alias if it was used before with a different index. * * @param alias alias value * @param indexName index name */ void updateAlias(String alias, String indexName); /** * Adds a new attribute to the index * * @param indexName index name * @param skipInitialScan doesn't scan the index if <code>true</code> * @param fields field indexes */ void alter(String indexName, boolean skipInitialScan, FieldIndex... fields); /** * Returns configuration map by defined parameter name * * @param parameter parameter name * @return configuration map */ Map<String, String> getConfig(String parameter); /** * Sets configuration value by the parameter name * * @param parameter parameter name * @param value parameter value */ void setConfig(String parameter, String value); /** * Deletes cursor by index name and id * * @param indexName index name * @param cursorId cursor id */ void delCursor(String indexName, long cursorId); /** * Returns next results by index name and cursor id * * @param indexName index name * @param cursorId cursor id * @return aggregation result */ AggregationResult readCursor(String indexName, long cursorId); /** * Returns next results by index name, cursor id and results size * * @param indexName index name * @param cursorId cursor id * @param count results size * @return aggregation result */ AggregationResult readCursor(String indexName, long cursorId, int count); /** * Adds defined terms to the dictionary * * @param dictionary dictionary name * @param terms terms * @return number of new terms */ long addDict(String dictionary, String... terms); /** * Deletes defined terms from the dictionary * * @param dictionary dictionary name * @param terms terms * @return number of deleted terms */ long delDict(String dictionary, String... terms); /** * Returns terms stored in the dictionary * * @param dictionary dictionary name * @return terms */ List<String> dumpDict(String dictionary); /** * Deletes index by name * * @param indexName index name */ void dropIndex(String indexName); /** * Deletes index by name and associated documents. * Associated documents are deleted asynchronously. * Method {@link #info(String)} can be used to check for process completion. * * @param indexName index name */ void dropIndexAndDocuments(String indexName); /** * Returns index info by name * * @param indexName index name * @return index info */ IndexInfo info(String indexName); /** * Executes spell checking by defined index name and query. * Returns a map of misspelled terms and their score. * * <pre> * Map<String, Map<String, Double>> res = s.spellcheck("idx", "Hocke sti", SpellcheckOptions.defaults() * .includedTerms("name")); * </pre> * * @param indexName index name * @param query query * @param options spell checking options * @return map of misspelled terms and their score */ Map<String, Map<String, Double>> spellcheck(String indexName, String query, SpellcheckOptions options); /** * Returns synonyms mapped by word by defined index name * * @param indexName index name * @return synonyms map */ Map<String, List<String>> dumpSynonyms(String indexName); /** * Updates synonyms * * @param indexName index name * @param synonymGroupId synonym group id * @param terms terms */ void updateSynonyms(String indexName, String synonymGroupId, String... terms); /** * Returns list of all created indexes * * @return list of indexes */ List<String> getIndexes(); }
RSearch
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/inference/action/GetInferenceServicesAction.java
{ "start": 881, "end": 1244 }
class ____ extends ActionType<GetInferenceServicesAction.Response> { public static final GetInferenceServicesAction INSTANCE = new GetInferenceServicesAction(); public static final String NAME = "cluster:monitor/xpack/inference/services/get"; public GetInferenceServicesAction() { super(NAME); } public static
GetInferenceServicesAction
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/bigdecimal/BigDecimalAssert_isNotNegative_Test.java
{ "start": 911, "end": 1248 }
class ____ extends BigDecimalAssertBaseTest { @Override protected BigDecimalAssert invoke_api_method() { return assertions.isNotNegative(); } @Override protected void verify_internal_effects() { verify(bigDecimals).assertIsNotNegative(getInfo(assertions), getActual(assertions)); } }
BigDecimalAssert_isNotNegative_Test
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
{ "start": 47475, "end": 51013 }
class ____ { @Test void privateSubclassOverridesPropertyInPublicInterface() { expression = parser.parseExpression("text"); PrivateSubclass privateSubclass = new PrivateSubclass(); // Prerequisite: type must not be public for this use case. assertNotPublic(privateSubclass.getClass()); String result = expression.getValue(context, privateSubclass, String.class); assertThat(result).isEqualTo("enigma"); assertCanCompile(expression); result = expression.getValue(context, privateSubclass, String.class); assertThat(result).isEqualTo("enigma"); } @Test void privateSubclassOverridesPropertyInPrivateInterface() { expression = parser.parseExpression("message"); PrivateSubclass privateSubclass = new PrivateSubclass(); // Prerequisite: type must not be public for this use case. assertNotPublic(privateSubclass.getClass()); String result = expression.getValue(context, privateSubclass, String.class); assertThat(result).isEqualTo("hello"); assertCanCompile(expression); result = expression.getValue(context, privateSubclass, String.class); assertThat(result).isEqualTo("hello"); } @Test void privateSubclassOverridesPropertyInPublicSuperclass() { expression = parser.parseExpression("number"); PrivateSubclass privateSubclass = new PrivateSubclass(); // Prerequisite: type must not be public for this use case. assertNotPublic(privateSubclass.getClass()); Integer result = expression.getValue(context, privateSubclass, Integer.class); assertThat(result).isEqualTo(2); assertCanCompile(expression); result = expression.getValue(context, privateSubclass, Integer.class); assertThat(result).isEqualTo(2); } @Test void indexIntoPropertyInPrivateSubclassThatOverridesPropertyInPublicInterface() { expression = parser.parseExpression("#root['text']"); PrivateSubclass privateSubclass = new PrivateSubclass(); // Prerequisite: type must not be public for this use case. assertNotPublic(privateSubclass.getClass()); String result = expression.getValue(context, privateSubclass, String.class); assertThat(result).isEqualTo("enigma"); assertCanCompile(expression); result = expression.getValue(context, privateSubclass, String.class); assertThat(result).isEqualTo("enigma"); } @Test void indexIntoPropertyInPrivateSubclassThatOverridesPropertyInPrivateInterface() { expression = parser.parseExpression("#root['message']"); PrivateSubclass privateSubclass = new PrivateSubclass(); // Prerequisite: type must not be public for this use case. assertNotPublic(privateSubclass.getClass()); String result = expression.getValue(context, privateSubclass, String.class); assertThat(result).isEqualTo("hello"); assertCanCompile(expression); result = expression.getValue(context, privateSubclass, String.class); assertThat(result).isEqualTo("hello"); } @Test void indexIntoPropertyInPrivateSubclassThatOverridesPropertyInPublicSuperclass() { expression = parser.parseExpression("#root['number']"); PrivateSubclass privateSubclass = new PrivateSubclass(); // Prerequisite: type must not be public for this use case. assertNotPublic(privateSubclass.getClass()); Integer result = expression.getValue(context, privateSubclass, Integer.class); assertThat(result).isEqualTo(2); assertCanCompile(expression); result = expression.getValue(context, privateSubclass, Integer.class); assertThat(result).isEqualTo(2); } } @Nested
PropertyVisibilityTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/javatime/ser/LocalTimeSerTest.java
{ "start": 1374, "end": 1614 }
class ____ extends LocalTimeSerializer { public CustomLocalTimeSerializer() { // Default doesn't cut it for us. super(DateTimeFormatter.ofPattern("HH/mm")); } } static
CustomLocalTimeSerializer
java
apache__avro
lang/java/thrift/src/test/java/org/apache/avro/thrift/test/Foo.java
{ "start": 30034, "end": 35356 }
enum ____ implements org.apache.thrift.TFieldIdEnum { ; private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByThriftId(int fieldId) { switch (fieldId) { default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception if it * is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>( _Fields.class); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ping_result.class, metaDataMap); } public ping_result() { } /** * Performs a deep copy on <i>other</i>. */ public ping_result(ping_result other) { } public ping_result deepCopy() { return new ping_result(this); } @Override public void clear() { } public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) { switch (field) { } } @org.apache.thrift.annotation.Nullable public java.lang.Object getFieldValue(_Fields field) { switch (field) { } throw new java.lang.IllegalStateException(); } /** * Returns true if field corresponding to fieldID is set (has been assigned a * value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that instanceof ping_result) return this.equals((ping_result) that); return false; } public boolean equals(ping_result that) { if (that == null) return false; if (this == that) return true; return true; } @Override public int hashCode() { int hashCode = 1; return hashCode; } @Override public int compareTo(ping_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; return 0; } @org.apache.thrift.annotation.Nullable public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("ping_result("); boolean first = true; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static
_Fields
java
apache__camel
components/camel-consul/src/main/java/org/apache/camel/component/consul/cluster/ConsulClusterConfiguration.java
{ "start": 978, "end": 2446 }
class ____ extends ConsulClientConfiguration { private int sessionTtl = 60; private int sessionLockDelay = 5; private int sessionRefreshInterval = 5; private String rootPath = "/camel"; // *********************************************** // Properties // *********************************************** public int getSessionTtl() { return sessionTtl; } public void setSessionTtl(int sessionTtl) { this.sessionTtl = sessionTtl; } public int getSessionLockDelay() { return sessionLockDelay; } public void setSessionLockDelay(int sessionLockDelay) { this.sessionLockDelay = sessionLockDelay; } public String getRootPath() { return rootPath; } public void setRootPath(String rootPath) { this.rootPath = rootPath; } public int getSessionRefreshInterval() { return sessionRefreshInterval; } public void setSessionRefreshInterval(int sessionRefreshInterval) { this.sessionRefreshInterval = sessionRefreshInterval; } // *********************************************** // // *********************************************** @Override public ConsulClusterConfiguration copy() { try { return (ConsulClusterConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } }
ConsulClusterConfiguration
java
apache__flink
flink-yarn/src/main/java/org/apache/flink/yarn/ContainerRequestReflector.java
{ "start": 1531, "end": 5171 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(ContainerRequestReflector.class); static final ContainerRequestReflector INSTANCE = new ContainerRequestReflector(); @Nullable private Constructor<? extends AMRMClient.ContainerRequest> defaultConstructor; private ContainerRequestReflector() { this(AMRMClient.ContainerRequest.class); } @VisibleForTesting ContainerRequestReflector(Class<? extends AMRMClient.ContainerRequest> containerRequestClass) { Class<? extends AMRMClient.ContainerRequest> requestCls = containerRequestClass; try { /** * To support node-label, using the below constructor. Please refer to * https://github.com/apache/hadoop/blob/trunk/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/AMRMClient.java#L287 * * <p>Instantiates a {@link ContainerRequest} with the given constraints. * * @param capability The {@link Resource} to be requested for each container. * @param nodes Any hosts to request that the containers are placed on. * @param racks Any racks to request that the containers are placed on. The racks * corresponding to any hosts requested will be automatically added to this list. * @param priority The priority at which to request the containers. Higher priorities * have lower numerical values. * @param allocationRequestId The allocationRequestId of the request. To be used as a * tracking id to match Containers allocated against this request. Will default to 0 * if not specified. * @param relaxLocality If true, containers for this request may be assigned on hosts * and racks other than the ones explicitly requested. * @param nodeLabelsExpression Set node labels to allocate resource, now we only support * asking for only a single node label */ defaultConstructor = requestCls.getDeclaredConstructor( Resource.class, String[].class, String[].class, Priority.class, boolean.class, String.class); } catch (NoSuchMethodException exception) { LOG.debug( "The node-label mechanism of Yarn don't be supported in this Hadoop version."); } } public AMRMClient.ContainerRequest getContainerRequest( Resource containerResource, Priority priority, String nodeLabel) { if (StringUtils.isNullOrWhitespaceOnly(nodeLabel) || defaultConstructor == null) { return new AMRMClient.ContainerRequest(containerResource, null, null, priority); } try { /** * Set the param of relaxLocality to true, which tells the Yarn ResourceManager if the * application wants locality to be loose (i.e. allows fall-through to rack or any) */ return defaultConstructor.newInstance( containerResource, null, null, priority, true, nodeLabel); } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { LOG.warn("Errors on creating Container Request.", e); } return new AMRMClient.ContainerRequest(containerResource, null, null, priority); } }
ContainerRequestReflector
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/TransportVersionTests.java
{ "start": 2367, "end": 2755 }
class ____ { public static final TransportVersion V_0_00_01 = new TransportVersion(199); public static final TransportVersion V_0_000_002 = new TransportVersion(2); public static final TransportVersion V_0_000_003 = new TransportVersion(3); public static final TransportVersion V_0_000_004 = new TransportVersion(4); } public static
CorrectFakeVersion
java
apache__flink
flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/client/state/ImmutableValueState.java
{ "start": 1562, "end": 2428 }
class ____<V> extends ImmutableState implements ValueState<V> { private final V value; private ImmutableValueState(V value) { this.value = Preconditions.checkNotNull(value); } @Override public V value() { return value; } @Override public void update(V newValue) { throw MODIFICATION_ATTEMPT_ERROR; } @Override public void clear() { throw MODIFICATION_ATTEMPT_ERROR; } @SuppressWarnings("unchecked") public static <V, S extends State> S createState( StateDescriptor<S, V> stateDescriptor, byte[] serializedState) throws IOException { final V state = KvStateSerializer.deserializeValue( serializedState, stateDescriptor.getSerializer()); return (S) new ImmutableValueState<>(state); } }
ImmutableValueState
java
alibaba__nacos
naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/BatchInstanceRequestHandler.java
{ "start": 1846, "end": 3566 }
class ____ extends RequestHandler<BatchInstanceRequest, BatchInstanceResponse> { private final EphemeralClientOperationServiceImpl clientOperationService; public BatchInstanceRequestHandler(EphemeralClientOperationServiceImpl clientOperationService) { this.clientOperationService = clientOperationService; } @Override @NamespaceValidation @TpsControl(pointName = "RemoteNamingInstanceBatchRegister", name = "RemoteNamingInstanceBatchRegister") @Secured(action = ActionTypes.WRITE) @ExtractorManager.Extractor(rpcExtractor = BatchInstanceRequestParamExtractor.class) public BatchInstanceResponse handle(BatchInstanceRequest request, RequestMeta meta) throws NacosException { Service service = Service.newService(request.getNamespace(), request.getGroupName(), request.getServiceName(), true); InstanceUtil.batchSetInstanceIdIfEmpty(request.getInstances(), service.getGroupedServiceName()); switch (request.getType()) { case NamingRemoteConstants.BATCH_REGISTER_INSTANCE: return batchRegisterInstance(service, request, meta); default: throw new NacosException(NacosException.INVALID_PARAM, String.format("Unsupported request type %s", request.getType())); } } private BatchInstanceResponse batchRegisterInstance(Service service, BatchInstanceRequest request, RequestMeta meta) { clientOperationService.batchRegisterInstance(service, request.getInstances(), meta.getConnectionId()); return new BatchInstanceResponse(NamingRemoteConstants.BATCH_REGISTER_INSTANCE); } }
BatchInstanceRequestHandler
java
apache__flink
flink-rpc/flink-rpc-akka/src/test/java/org/apache/flink/runtime/rpc/pekko/PekkoRpcActorTest.java
{ "start": 29528, "end": 29895 }
class ____ implements Serializable { private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException { throw new ClassNotFoundException("test exception"); } } // ------------------------------------------------------------------------ private static
DeserializationFailingObject
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/constructor/nestedsource/ArtistToChartEntryComposedReverse.java
{ "start": 737, "end": 1769 }
class ____ { public static final ArtistToChartEntryComposedReverse MAPPER = Mappers.getMapper( ArtistToChartEntryComposedReverse.class ); @Mappings({ @Mapping(target = "songTitle", source = "title"), @Mapping(target = "artistName", source = "artist.name"), @Mapping(target = "label", source = "artist.label"), @Mapping(target = "position", ignore = true), @Mapping(target = "chartName", ignore = true ) }) abstract ChartEntryComposed mapForward(Song song); @Mappings({ @Mapping(target = "name", source = "name"), @Mapping(target = "recordedAt", source = "studio.name"), @Mapping(target = "city", source = "studio.city") }) abstract ChartEntryLabel mapForward(Label label); @InheritInverseConfiguration @Mapping(target = "positions", ignore = true) abstract Song mapReverse(ChartEntryComposed ce); @InheritInverseConfiguration abstract Label mapReverse(ChartEntryLabel label); }
ArtistToChartEntryComposedReverse
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleDelay.java
{ "start": 2369, "end": 2665 }
class ____ implements Runnable { private final T value; OnSuccess(T value) { this.value = value; } @Override public void run() { downstream.onSuccess(value); } } final
OnSuccess
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/descriptor/java/ObjectArrayJavaType.java
{ "start": 309, "end": 2406 }
class ____ extends AbstractClassJavaType<Object[]> { private final JavaType[] components; public ObjectArrayJavaType(JavaType[] components) { super( Object[].class, ImmutableMutabilityPlan.instance(), new ComponentArrayComparator( components ) ); this.components = components; } @Override public boolean isInstance(Object value) { return value instanceof Object[]; } @Override public String toString(Object[] value) { final StringBuilder sb = new StringBuilder(); sb.append( '(' ); append( sb, components, value, 0 ); for ( int i = 1; i < components.length; i++ ) { sb.append( ", " ); append( sb, components, value, i ); } sb.append( ')' ); return sb.toString(); } private void append(StringBuilder builder, JavaType[] components, Object[] value, int i) { final Object element = value[i]; if (element == null ) { builder.append( "null" ); } else { builder.append( components[i].toString( element ) ); } } @Override public boolean areEqual(Object[] one, Object[] another) { if ( one == another ) { return true; } if ( one != null && another != null && one.length == another.length ) { for ( int i = 0; i < components.length; i++ ) { if ( !components[i].areEqual( one[i], another[i] ) ) { return false; } } return true; } return false; } @Override public int extractHashCode(Object[] objects) { int hashCode = 1; for ( int i = 0; i < objects.length; i++ ) { hashCode = 31 * hashCode + components[i].extractHashCode( objects[i] ); } return hashCode; } @SuppressWarnings("unchecked") @Override public <X> X unwrap(Object[] value, Class<X> type, WrapperOptions options) { if ( value == null ) { return null; } if ( Object[].class.isAssignableFrom( type ) ) { return (X) value; } throw unknownUnwrap( type ); } @Override public <X> Object[] wrap(X value, WrapperOptions options) { if ( value == null ) { return null; } if (value instanceof Object[] objects) { return objects; } throw unknownWrap( value.getClass() ); } }
ObjectArrayJavaType
java
resilience4j__resilience4j
resilience4j-commons-configuration/src/main/java/io/github/resilience4j/commons/configuration/util/StringParseUtil.java
{ "start": 849, "end": 1669 }
class ____ { /** * Extracts the unique prefixes of the delimiter separated elements. * * @param iterator the iterator * @param delimiter the delimiter * @return the unique prefixes */ public static Set<String> extractUniquePrefixes(final Iterator<String> iterator, final String delimiter) { Set<String> uniquePrefixes = new HashSet<>(); try{ iterator.forEachRemaining(element -> { String prefix = element.substring(0, element.indexOf(delimiter)); uniquePrefixes.add(prefix); }); return uniquePrefixes; }catch (IndexOutOfBoundsException e){ throw new ConfigParseException(String.format("Unable to extract prefix with delimiter: %s", delimiter), e); } } }
StringParseUtil