language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurerTests.java
{ "start": 13630, "end": 14260 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .httpBasic(withDefaults()) .rememberMe(withDefaults()); return http.build(); // @formatter:on } @Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager( // @formatter:off org.springframework.security.core.userdetails.User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build() // @formatter:on ); } } @Configuration @EnableWebSecurity static
BasicUsesRememberMeConfig
java
apache__spark
sql/core/src/test/java/test/org/apache/spark/sql/JavaDatasetSuite.java
{ "start": 32220, "end": 34011 }
class ____ implements Serializable { String value; JavaSerializable(String value) { this.value = value; } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; return this.value.equals(((JavaSerializable) other).value); } @Override public int hashCode() { return this.value.hashCode(); } } @Test public void testKryoEncoder() { Encoder<KryoSerializable> encoder = Encoders.kryo(KryoSerializable.class); List<KryoSerializable> data = Arrays.asList( new KryoSerializable("hello"), new KryoSerializable("world")); Dataset<KryoSerializable> ds = spark.createDataset(data, encoder); Assertions.assertEquals(data, ds.collectAsList()); } @Test public void testJavaEncoder() { Encoder<JavaSerializable> encoder = Encoders.javaSerialization(JavaSerializable.class); List<JavaSerializable> data = Arrays.asList( new JavaSerializable("hello"), new JavaSerializable("world")); Dataset<JavaSerializable> ds = spark.createDataset(data, encoder); Assertions.assertEquals(data, ds.collectAsList()); } @Test public void testRandomSplit() { List<String> data = Arrays.asList("hello", "world", "from", "spark"); Dataset<String> ds = spark.createDataset(data, Encoders.STRING()); double[] arraySplit = {1, 2, 3}; List<Dataset<String>> randomSplit = ds.randomSplitAsList(arraySplit, 1); Assertions.assertEquals(randomSplit.size(), 3, "wrong number of splits"); } /** * For testing error messages when creating an encoder on a private class. This is done * here since we cannot create truly private classes in Scala. */ private static
JavaSerializable
java
quarkusio__quarkus
core/deployment/src/test/java/io/quarkus/deployment/builditem/DevServicesComposeProjectBuildItemTest.java
{ "start": 448, "end": 7438 }
class ____ { private DevServicesComposeProjectBuildItem buildItem; @BeforeEach void setUp() { // Create container info for postgres ContainerInfo postgresInfo = new ContainerInfo( "postgres123456789", new String[] { "postgres" }, "postgres:13", "running", Map.of("default", new String[] { "default" }), Collections.emptyMap(), new ContainerInfo.ContainerPort[] { new ContainerInfo.ContainerPort("0.0.0.0", 5432, 5432, "tcp") }); RunningContainer postgresContainer = new RunningContainer(postgresInfo, Collections.emptyMap()); // Create container info for mysql ContainerInfo mysqlInfo = new ContainerInfo( "mysql123456789", new String[] { "mysql" }, "mysql:8", "running", Map.of("default", new String[] { "default" }), Collections.emptyMap(), new ContainerInfo.ContainerPort[] { new ContainerInfo.ContainerPort("0.0.0.0", 3306, 3306, "tcp") }); RunningContainer mysqlContainer = new RunningContainer(mysqlInfo, Collections.emptyMap()); // Create container info for redis ContainerInfo redisInfo = new ContainerInfo( "redis123456789", new String[] { "redis" }, "redis:6", "running", Map.of("default", new String[] { "default" }), Collections.emptyMap(), new ContainerInfo.ContainerPort[] { new ContainerInfo.ContainerPort("0.0.0.0", 6379, 6379, "tcp") }); RunningContainer redisContainer = new RunningContainer(redisInfo, Collections.emptyMap()); // Create container info for ignored container Map<String, String> ignoredLabels = new HashMap<>(); ignoredLabels.put(DevServicesComposeProjectBuildItem.COMPOSE_IGNORE, "true"); ContainerInfo ignoredInfo = new ContainerInfo( "ignored123456789", new String[] { "ignored" }, "ignored:latest", "running", Map.of("default", new String[] { "default" }), ignoredLabels, new ContainerInfo.ContainerPort[] { new ContainerInfo.ContainerPort("0.0.0.0", 8080, 8080, "tcp") }); RunningContainer ignoredContainer = new RunningContainer(ignoredInfo, Collections.emptyMap()); // Create the build item with the containers Map<String, List<RunningContainer>> composeServices = new HashMap<>(); composeServices.put("default", Arrays.asList(postgresContainer, mysqlContainer, redisContainer, ignoredContainer)); buildItem = new DevServicesComposeProjectBuildItem("test-project", "default", composeServices, Collections.emptyMap()); } @Test void locate() { // Test locating postgres container by image and port Optional<RunningContainer> result = buildItem.locate(List.of("postgres"), 5432); assertTrue(result.isPresent()); assertEquals("postgres123456789", result.get().containerInfo().id()); // Test locating mysql container by image and port result = buildItem.locate(List.of("mysql"), 3306); assertTrue(result.isPresent()); assertEquals("mysql123456789", result.get().containerInfo().id()); // Test locating with non-existent port // The port filtering should work correctly ContainerInfo postgresInfoWithoutPort = new ContainerInfo( "postgres123456789", new String[] { "postgres" }, "postgres:13", "running", Map.of("default", new String[] { "default" }), Collections.emptyMap(), new ContainerInfo.ContainerPort[] {}); // Empty ports array RunningContainer postgresContainerWithoutPort = new RunningContainer(postgresInfoWithoutPort, Collections.emptyMap()); Map<String, List<RunningContainer>> servicesWithoutPort = new HashMap<>(); servicesWithoutPort.put("default", List.of(postgresContainerWithoutPort)); DevServicesComposeProjectBuildItem buildItemWithoutPort = new DevServicesComposeProjectBuildItem( "test-project", "default", servicesWithoutPort, Collections.emptyMap()); result = buildItemWithoutPort.locate(List.of("postgres"), 5432); assertTrue(result.isPresent()); // Test locating with non-existent image result = buildItem.locate(List.of("nonexistent"), 5432); assertFalse(result.isPresent()); // Test that ignored container is not found result = buildItem.locate(List.of("ignored"), 8080); assertFalse(result.isPresent()); } @Test void testLocate() { // Test locating by image partial List<RunningContainer> results = buildItem.locate(List.of("postgres")); assertEquals(1, results.size()); assertEquals("postgres123456789", results.get(0).containerInfo().id()); // Test locating with multiple image partials results = buildItem.locate(List.of("postgres", "mysql")); assertEquals(2, results.size()); assertTrue(results.stream().anyMatch(c -> c.containerInfo().id().equals("postgres123456789"))); assertTrue(results.stream().anyMatch(c -> c.containerInfo().id().equals("mysql123456789"))); // Test locating with non-existent image results = buildItem.locate(List.of("nonexistent")); assertTrue(results.isEmpty()); // Test that ignored container is not found results = buildItem.locate(List.of("ignored")); assertTrue(results.isEmpty()); } @Test void locateFirst() { // Test locating first container by image partial Optional<RunningContainer> result = buildItem.locateFirst(List.of("postgres")); assertTrue(result.isPresent()); assertEquals("postgres123456789", result.get().containerInfo().id()); // Test locating with multiple image partials (should return the first match) result = buildItem.locateFirst(List.of("postgres", "mysql")); assertTrue(result.isPresent()); // The first match depends on the order of containers in the composeServices map // In our setup, postgres should be first assertEquals("postgres123456789", result.get().containerInfo().id()); // Test locating with non-existent image result = buildItem.locateFirst(List.of("nonexistent")); assertFalse(result.isPresent()); // Test that ignored container is not found result = buildItem.locateFirst(List.of("ignored")); assertFalse(result.isPresent()); } }
DevServicesComposeProjectBuildItemTest
java
apache__kafka
metadata/src/test/java/org/apache/kafka/image/DelegationTokenImageTest.java
{ "start": 1838, "end": 6489 }
class ____ { public static final DelegationTokenImage IMAGE1; public static final List<ApiMessageAndVersion> DELTA1_RECORDS; static final DelegationTokenDelta DELTA1; static final DelegationTokenImage IMAGE2; static DelegationTokenData randomDelegationTokenData(String tokenId, long expireTimestamp) { TokenInformation ti = new TokenInformation( tokenId, SecurityUtils.parseKafkaPrincipal(KafkaPrincipal.USER_TYPE + ":" + "fred"), SecurityUtils.parseKafkaPrincipal(KafkaPrincipal.USER_TYPE + ":" + "fred"), new ArrayList<>(), 0, 1000, expireTimestamp); return new DelegationTokenData(ti); } static { Map<String, DelegationTokenData> image1 = new HashMap<>(); image1.put("somerandomuuid1", randomDelegationTokenData("somerandomuuid1", 100)); image1.put("somerandomuuid2", randomDelegationTokenData("somerandomuuid2", 100)); image1.put("somerandomuuid3", randomDelegationTokenData("somerandomuuid3", 100)); IMAGE1 = new DelegationTokenImage(image1); DELTA1_RECORDS = new ArrayList<>(); DELTA1_RECORDS.add(new ApiMessageAndVersion(new DelegationTokenRecord(). setOwner(KafkaPrincipal.USER_TYPE + ":" + "fred"). setRequester(KafkaPrincipal.USER_TYPE + ":" + "fred"). setIssueTimestamp(0). setMaxTimestamp(1000). setExpirationTimestamp(200). setTokenId("somerandomuuid1"), (short) 0)); DELTA1_RECORDS.add(new ApiMessageAndVersion(new RemoveDelegationTokenRecord(). setTokenId("somerandomuuid3"), (short) 0)); DELTA1 = new DelegationTokenDelta(IMAGE1); RecordTestUtils.replayAll(DELTA1, DELTA1_RECORDS); Map<String, DelegationTokenData> image2 = new HashMap<>(); image2.put("somerandomuuid1", randomDelegationTokenData("somerandomuuid1", 200)); image2.put("somerandomuuid2", randomDelegationTokenData("somerandomuuid2", 100)); IMAGE2 = new DelegationTokenImage(image2); } @Test public void testEmptyImageRoundTrip() throws Throwable { testToImage(DelegationTokenImage.EMPTY); } @Test public void testImage1RoundTrip() throws Throwable { testToImage(IMAGE1); } @Test public void testApplyDelta1() throws Throwable { assertEquals(IMAGE2, DELTA1.apply()); // check image1 + delta1 = image2, since records for image1 + delta1 might differ from records from image2 List<ApiMessageAndVersion> records = getImageRecords(IMAGE1); records.addAll(DELTA1_RECORDS); testToImage(IMAGE2, records); } @Test public void testImage2RoundTrip() throws Throwable { // testToImageAndBack(IMAGE2); testToImage(IMAGE2); } private static void testToImage(DelegationTokenImage image) { testToImage(image, Optional.empty()); } private static void testToImage(DelegationTokenImage image, Optional<List<ApiMessageAndVersion>> fromRecords) { testToImage(image, fromRecords.orElseGet(() -> getImageRecords(image))); } private static void testToImage(DelegationTokenImage image, List<ApiMessageAndVersion> fromRecords) { // test from empty image stopping each of the various intermediate images along the way new RecordTestUtils.TestThroughAllIntermediateImagesLeadingToFinalImageHelper<>( () -> DelegationTokenImage.EMPTY, DelegationTokenDelta::new ).test(image, fromRecords); } private static List<ApiMessageAndVersion> getImageRecords(DelegationTokenImage image) { RecordListWriter writer = new RecordListWriter(); image.write(writer, new ImageWriterOptions.Builder(MetadataVersion.latestProduction()).build()); return writer.records(); } @Test public void testEmptyWithInvalidIBP() { ImageWriterOptions imageWriterOptions = new ImageWriterOptions.Builder(MetadataVersion.IBP_3_5_IV2).build(); RecordListWriter writer = new RecordListWriter(); DelegationTokenImage.EMPTY.write(writer, imageWriterOptions); } @Test public void testImage1WithInvalidIBP() { ImageWriterOptions imageWriterOptions = new ImageWriterOptions.Builder(MetadataVersion.IBP_3_5_IV2).build(); RecordListWriter writer = new RecordListWriter(); assertThrows(Exception.class, () -> IMAGE1.write(writer, imageWriterOptions), "expected exception writing IMAGE with Delegation Token records for MetadataVersion.IBP_3_5_IV2"); } }
DelegationTokenImageTest
java
apache__flink
flink-table/flink-table-code-splitter/src/main/java/org/apache/flink/table/codesplit/JavaCodeSplitter.java
{ "start": 1112, "end": 2513 }
class ____ { public static String split(String code, int maxMethodLength, int maxClassMemberCount) { try { return splitImpl(code, maxMethodLength, maxClassMemberCount); } catch (Throwable t) { throw new RuntimeException( "JavaCodeSplitter failed. This is a bug. Please file an issue.", t); } } private static String splitImpl(String code, int maxMethodLength, int maxClassMemberCount) { checkArgument(code != null && !code.isEmpty(), "code cannot be empty"); checkArgument(maxMethodLength > 0, "maxMethodLength must be greater than 0"); checkArgument(maxClassMemberCount > 0, "maxClassMemberCount must be greater than 0"); if (code.length() <= maxMethodLength) { return code; } String returnValueRewrittenCode = new ReturnValueRewriter(code, maxMethodLength).rewrite(); return Optional.ofNullable( new DeclarationRewriter(returnValueRewrittenCode, maxMethodLength) .rewrite()) .map(text -> new BlockStatementRewriter(text, maxMethodLength).rewrite()) .map(text -> new FunctionSplitter(text, maxMethodLength).rewrite()) .map(text -> new MemberFieldRewriter(text, maxClassMemberCount).rewrite()) .orElse(code); } }
JavaCodeSplitter
java
apache__flink
flink-core/src/test/java/org/apache/flink/util/UserClassLoaderJarTestUtils.java
{ "start": 1570, "end": 2221 }
class ____ a JAR and return the path of the JAR. */ public static File createJarFile(File tmpDir, String jarName, String className, String javaCode) throws IOException { return createJarFile(tmpDir, jarName, Collections.singletonMap(className, javaCode)); } /** Pack the generated classes into a JAR and return the path of the JAR. */ public static File createJarFile( File tmpDir, String jarName, Map<String, String> classNameCodes) throws IOException { List<File> javaFiles = new ArrayList<>(); for (Map.Entry<String, String> entry : classNameCodes.entrySet()) { // write
into
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/index/IndexSettingsIT.java
{ "start": 853, "end": 1056 }
class ____ extends ESIntegTestCase { public static final Setting<Boolean> TEST_SETTING = Setting.boolSetting("index.test_setting", false, Setting.Property.IndexScope); public static
IndexSettingsIT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/SetIdentifierOnAEnhancedProxyTest.java
{ "start": 7235, "end": 7594 }
class ____ implements Serializable { Long id1; Long id2; public Long getId1() { return id1; } public void setId1(Long id1) { this.id1 = id1; } public Long getId2() { return id2; } public void setId2(Long id2) { this.id2 = id2; } } @Entity(name = "Parent") @Table(name = "PARENT") @IdClass( ModelId.class ) static
ModelId
java
quarkusio__quarkus
extensions/security-jpa/deployment/src/test/java/io/quarkus/security/jpa/RolesEndpointClassLevel.java
{ "start": 415, "end": 754 }
class ____ { @Inject RoutingContext routingContext; @GET public String echo(@Context SecurityContext sec) { return "Hello " + sec.getUserPrincipal().getName(); } @Path("routing-context") @GET public boolean hasRoutingContext() { return routingContext != null; } }
RolesEndpointClassLevel
java
elastic__elasticsearch
x-pack/plugin/core/src/internalClusterTest/java/org/elasticsearch/xpack/core/rest/action/XPackUsageRestCancellationIT.java
{ "start": 6224, "end": 7365 }
class ____ extends XPackUsageFeatureTransportAction { @Inject public BlockingXPackUsageAction( TransportService transportService, ClusterService clusterService, ThreadPool threadPool, ActionFilters actionFilters ) { super(BlockingUsageActionXPackPlugin.BLOCKING_XPACK_USAGE.name(), transportService, clusterService, threadPool, actionFilters); } @Override protected void localClusterStateOperation( Task task, XPackUsageRequest request, ClusterState state, ActionListener<XPackUsageFeatureResponse> listener ) throws Exception { blockingXPackUsageActionExecuting.countDown(); blockActionLatch.await(); listener.onResponse(new XPackUsageFeatureResponse(new XPackFeatureUsage("test", false, false) { @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.current(); } })); } } public static
BlockingXPackUsageAction
java
bumptech__glide
library/test/src/test/java/com/bumptech/glide/load/engine/bitmap_recycle/LruBitmapPoolTest.java
{ "start": 7800, "end": 8614 }
class ____ implements LruPoolStrategy { private final ArrayDeque<Bitmap> bitmaps = new ArrayDeque<>(); private int numRemoves; private int numPuts; @Override public void put(Bitmap bitmap) { numPuts++; bitmaps.add(bitmap); } @Override public Bitmap get(int width, int height, Bitmap.Config config) { return bitmaps.isEmpty() ? null : bitmaps.removeLast(); } @Override public Bitmap removeLast() { numRemoves++; return bitmaps.removeLast(); } @Override public String logBitmap(Bitmap bitmap) { return null; } @Override public String logBitmap(int width, int height, Bitmap.Config config) { return null; } @Override public int getSize(Bitmap bitmap) { return 1; } } }
MockStrategy
java
spring-projects__spring-security
acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java
{ "start": 17036, "end": 17670 }
class ____ { private final List<String> cacheNames; private final CacheManager cacheManager; private CacheManagerMock() { this.cacheNames = new ArrayList<>(); this.cacheManager = mock(CacheManager.class); given(this.cacheManager.getCacheNames()).willReturn(this.cacheNames); } private CacheManager getCacheManager() { return this.cacheManager; } private void addCache(String name) { this.cacheNames.add(name); Cache cache = new ConcurrentMapCache(name); given(this.cacheManager.getCache(name)).willReturn(cache); } private void clear() { this.cacheNames.clear(); } } }
CacheManagerMock
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/output/committer/manifest/files/TaskManifest.java
{ "start": 1943, "end": 2456 }
class ____ that of * job committer. * If any changes are made to the manifest which are backwards compatible, * this new manifest can still be loaded from JSON and processed. * * If the manifest is no longer compatible, the job output may * be invalid. * * It is CRITICAL that the {@link #VERSION} constant is updated whenever * such an incompatible change is made. */ @SuppressWarnings("unused") @InterfaceAudience.Private @InterfaceStability.Unstable @JsonInclude(JsonInclude.Include.NON_NULL) public
than
java
alibaba__druid
core/src/main/java/com/alibaba/druid/support/http/DruidWebSecurityProvider.java
{ "start": 867, "end": 1068 }
interface ____ { /** * 检查用户是否未授权访问. * * @param request 请求 * @return 如果用户未授权访问true, 否则返回false。 */ boolean isNotPermit(HttpServletRequest request); }
DruidWebSecurityProvider
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/monitor/topn/FixedSizePriorityQueue.java
{ "start": 865, "end": 3120 }
class ____<T> { private Object[] elements; private int size; private Comparator<T> comparator; public FixedSizePriorityQueue(int capacity, Comparator<T> comparator) { elements = new Object[capacity]; size = 0; this.comparator = comparator; } /** * Offer queue, if queue is full and offer element is not bigger than the first element in queue, offer element will * be ignored. * * @param element new element. */ public void offer(T element) { if (size == elements.length) { if (comparator.compare(element, (T) elements[0]) > 0) { elements[0] = element; siftDown(); } } else { elements[size] = element; siftUp(size); size++; } } private void siftUp(int index) { while (index > 0) { int parentIndex = (index - 1) / 2; if (comparator.compare((T) elements[index], (T) elements[parentIndex]) > 0) { break; } swap(index, parentIndex); index = parentIndex; } } private void siftDown() { int index = 0; while (index * 2 + 1 < size) { int leftChild = index * 2 + 1; int rightChild = index * 2 + 2; int minChildIndex = leftChild; if (rightChild < size && comparator.compare((T) elements[rightChild], (T) elements[leftChild]) < 0) { minChildIndex = rightChild; } if (comparator.compare((T) elements[index], (T) elements[minChildIndex]) < 0) { break; } swap(index, minChildIndex); index = minChildIndex; } } private void swap(int i, int j) { Object temp = elements[i]; elements[i] = elements[j]; elements[j] = temp; } /** * Transfer queue to list without order. * * @return list */ public List<T> toList() { List<T> result = new LinkedList<>(); for (int i = 0; i < size; i++) { result.add((T) elements[i]); } return result; } }
FixedSizePriorityQueue
java
apache__camel
dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java
{ "start": 257191, "end": 257868 }
class ____ the result type (type from output)", displayName = "Result Type"), @YamlProperty(name = "source", type = "string", description = "Source to use, instead of message body. You can prefix with variable:, header:, or property: to specify kind of source. Otherwise, the source is assumed to be a variable. Use empty or null to use default source, which is the message body.", displayName = "Source"), @YamlProperty(name = "trim", type = "boolean", defaultValue = "true", description = "Whether to trim the value to remove leading and trailing whitespaces and line breaks", displayName = "Trim") } ) public static
of
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractPathAssert.java
{ "start": 41698, "end": 43926 }
class ____ for more details. If this is not what you want, use {@link #hasParent(Path)} instead.</em> * </p> * * <p> * This assertion uses {@link Path#getParent()} with no modification, which means the only criterion for this * assertion's success is the path's components (its root and its name elements). * </p> * * <p> * This may lead to surprising results if the tested path and the path given as an argument are not normalized. For * instance, if the tested path is {@code /home/foo/../bar} and the argument is {@code /home}, the assertion will * <em>fail</em> since the parent of the tested path is not {@code /home} but... {@code /home/foo/..}. * </p> * * <p> * While this may seem counterintuitive, it has to be recalled here that it is not required for a {@link FileSystem} * to consider that {@code .} and {@code ..} are name elements for respectively the current directory and the parent * directory respectively. In fact, it is not even required that a {@link FileSystem} be hierarchical at all. * </p> * * Examples: * <pre><code class="java"> // fs is a Unix filesystem * final Path actual = fs.getPath("/dir1/dir2/file"); * * // the following assertion succeeds: * assertThat(actual).hasParentRaw(fs.getPath("/dir1/dir2")); * * // the following assertions fails: * assertThat(actual).hasParent(fs.getPath("/dir1")); * // ... and this one too as expected path is not canonicalized. * assertThat(actual).hasParentRaw(fs.getPath("/dir1/dir3/../dir2"));</code></pre> * * @param expected the expected parent path * @return self * * @throws NullPointerException if the given parent path is null. * * @see Path#getParent() */ public SELF hasParentRaw(final Path expected) { paths.assertHasParentRaw(info, actual, expected); return myself; } /** * Assert that the tested {@link Path} has no parent. * * <p> * <em>This assertion will first canonicalize the tested path before performing the test; if this is not what you want, use {@link #hasNoParentRaw()} instead.</em> * </p> * * <p> * Check that the tested path, after canonicalization, has no parent. See the
description
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/ProducerTemplate.java
{ "start": 56016, "end": 56363 }
class ____) * @throws java.util.concurrent.TimeoutException if the wait timed out * @throws CamelExecutionException if the processing of the exchange failed */ <T> T extractFutureBody(Future<?> future, long timeout, TimeUnit unit, Class<T> type) throws TimeoutException, CamelExecutionException; }
javadoc
java
quarkusio__quarkus
extensions/smallrye-health/deployment/src/test/java/io/quarkus/smallrye/health/test/ProblemDetailsConfigOverrideTest.java
{ "start": 489, "end": 1723 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(FailingHealthCheck.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")) .overrideConfigKey("quarkus.smallrye-health.include-problem-details", "true"); @Test void testProblemDetailsOverride() { try { RestAssured.defaultParser = Parser.JSON; RestAssured.when().get("/q/health/live").then() .contentType("application/problem+json") .body("type", is("about:blank"), "status", is(503), "title", is("Health Check Failed: /q/health/live"), "detail", containsString("/q/health/live, invoked at"), "instance", notNullValue(), "health.checks.size()", is(1), "health.checks.status", contains("DOWN"), "health.checks.name", contains("failing")); } finally { RestAssured.reset(); } } }
ProblemDetailsConfigOverrideTest
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/routebuilder/CamelRouteBuilderTest.java
{ "start": 1092, "end": 1711 }
class ____ extends SpringTestSupport { @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/spring/routebuilder/camelRouteBuilder.xml"); } @Test public void testShouldProcessAnnotatedFields() throws Exception { getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:b").expectedMessageCount(1); template.sendBody("direct:a", "Hello World"); template.sendBody("direct:b", "Bye World"); assertMockEndpointsSatisfied(); } }
CamelRouteBuilderTest
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/JobInProgress.java
{ "start": 1073, "end": 1210 }
class ____ { /** * @deprecated Provided for compatibility. Use {@link JobCounter} instead. */ @Deprecated public
JobInProgress
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcPressureGenerator.java
{ "start": 1188, "end": 2880 }
class ____ implements AutoCloseable { private final AtomicInteger sink = new AtomicInteger(0); private final AtomicBoolean running = new AtomicBoolean(true); private final CountDownLatch stopLatch = new CountDownLatch(1); private GcPressureGenerator() { startGeneratorThread(); } private void startGeneratorThread() { final String threadName = GcPressureGenerator.class.getSimpleName(); final Thread thread = new Thread(this::generateGarbage, threadName); thread.setDaemon(true); // Avoid blocking JVM exit thread.start(); } private void generateGarbage() { try { while (running.get()) { final Object object = new byte[1024 * 1024]; int positiveValue = Math.abs(object.hashCode()); sink.set(positiveValue); System.gc(); System.runFinalization(); } } finally { stopLatch.countDown(); } } static GcPressureGenerator ofStarted() { return new GcPressureGenerator(); } @Override public void close() { final boolean signalled = running.compareAndSet(true, false); if (signalled) { try { final boolean stopped = stopLatch.await(10, TimeUnit.SECONDS); assertThat(stopped).isTrue(); assertThat(sink.get()).isPositive(); } catch (final InterruptedException error) { // Restore the `interrupted` flag Thread.currentThread().interrupt(); throw new RuntimeException(error); } } } }
GcPressureGenerator
java
apache__hadoop
hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestFileSignerSecretProvider.java
{ "start": 1119, "end": 2834 }
class ____ { @Test public void testGetSecrets() throws Exception { File testDir = new File(System.getProperty("test.build.data", "target/test-dir")); testDir.mkdirs(); String secretValue = "hadoop"; File secretFile = new File(testDir, "http-secret.txt"); Writer writer = new FileWriter(secretFile); writer.write(secretValue); writer.close(); FileSignerSecretProvider secretProvider = new FileSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty( AuthenticationFilter.SIGNATURE_SECRET_FILE, secretFile.getAbsolutePath()); secretProvider.init(secretProviderProps, null, -1); assertArrayEquals(secretValue.getBytes(), secretProvider.getCurrentSecret()); byte[][] allSecrets = secretProvider.getAllSecrets(); assertEquals(1, allSecrets.length); assertArrayEquals(secretValue.getBytes(), allSecrets[0]); } @Test public void testEmptySecretFileThrows() throws Exception { File secretFile = File.createTempFile("test_empty_secret", ".txt"); assertTrue(secretFile.exists()); FileSignerSecretProvider secretProvider = new FileSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty( AuthenticationFilter.SIGNATURE_SECRET_FILE, secretFile.getAbsolutePath()); Exception exception = assertThrows(RuntimeException.class, () -> { secretProvider.init(secretProviderProps, null, -1); }); assertTrue(exception.getMessage().startsWith( "No secret in signature secret file:")); } }
TestFileSignerSecretProvider
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureOutputsImpl.java
{ "start": 3443, "end": 4982 }
class ____ extends CurrentReturnState { private final int refCursorParamIndex; private ProcedureCurrentReturnState(boolean isResultSet, int updateCount, int refCursorParamIndex) { super( isResultSet, updateCount ); this.refCursorParamIndex = refCursorParamIndex; } @Override public boolean indicatesMoreOutputs() { return super.indicatesMoreOutputs() || ProcedureOutputsImpl.this.refCursorParamIndex < refCursorParameters.length; } @Override protected boolean hasExtendedReturns() { return refCursorParamIndex < refCursorParameters.length; } @Override protected Output buildExtendedReturn() { final JdbcCallRefCursorExtractor refCursorParam = refCursorParameters[ProcedureOutputsImpl.this.refCursorParamIndex++]; final ResultSet resultSet = refCursorParam.extractResultSet( callableStatement, procedureCall.getSession() ); return buildResultSetOutput( () -> extractResults( resultSet ) ); } @Override protected boolean hasFunctionReturns() { return parameterRegistrations.get( procedureCall.getFunctionReturn() ) != null; } @Override protected Output buildFunctionReturn() { final Object result = parameterRegistrations.get( procedureCall.getFunctionReturn() ) .getParameterExtractor() .extractValue( callableStatement, false, procedureCall.getSession() ); final List<Object> results = new ArrayList<>( 1 ); results.add( result ); return buildResultSetOutput( () -> results ); } } }
ProcedureCurrentReturnState
java
grpc__grpc-java
opentelemetry/src/main/java/io/grpc/opentelemetry/MetadataSetter.java
{ "start": 1215, "end": 2664 }
class ____ implements TextMapSetter<Metadata> { private static final Logger logger = Logger.getLogger(MetadataSetter.class.getName()); private static final MetadataSetter INSTANCE = new MetadataSetter(); public static MetadataSetter getInstance() { return INSTANCE; } @Override public void set(@Nullable Metadata carrier, String key, String value) { if (carrier == null) { logger.log(Level.FINE, "Carrier is null, setting no data"); return; } try { if (key.equals("grpc-trace-bin")) { carrier.put(Metadata.Key.of(key, Metadata.BINARY_BYTE_MARSHALLER), BaseEncoding.base64().decode(value)); } else { carrier.put(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER), value); } } catch (Exception e) { logger.log(Level.INFO, String.format("Failed to set metadata, key=%s", key), e); } } void set(@Nullable Metadata carrier, String key, byte[] value) { if (carrier == null) { logger.log(Level.FINE, "Carrier is null, setting no data"); return; } if (!key.equals("grpc-trace-bin")) { logger.log(Level.INFO, "Only support 'grpc-trace-bin' binary header. Set no data"); return; } try { carrier.put(Metadata.Key.of(key, Metadata.BINARY_BYTE_MARSHALLER), value); } catch (Exception e) { logger.log(Level.INFO, String.format("Failed to set metadata key=%s", key), e); } } }
MetadataSetter
java
elastic__elasticsearch
modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/RankEvalSpec.java
{ "start": 1522, "end": 1660 }
class ____ the queries to evaluate, including their document ratings, * and the evaluation metric including its parameters. */ public
groups
java
hibernate__hibernate-orm
hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/mysql/MySqlNativeSqlTemplates.java
{ "start": 1362, "end": 3139 }
class ____ extends NativeSQLTemplates { public MySqlNativeSqlTemplates() { super(); sqls.put( ST_OVERLAPS, "select id, st_overlaps(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_INTERSECTS, "select id, st_intersects(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_CROSSES, "select id, st_crosses(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_CONTAINS, "select id, st_contains(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_DISJOINT, "select id, st_disjoint(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_RELATE, "select id, st_relate(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_TOUCHES, "select id, st_touches(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_WITHIN, "select id, st_within(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_EQUALS, "select id, st_equals(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_DISTANCE, "select id, st_distance(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_BUFFER, "select id, st_buffer(geom, 2) as result from %s" ); sqls.put( ST_CONVEXHULL, "select id, st_convexhull(geom) as result from %s" ); sqls.put( ST_DIFFERENCE, "select id, st_difference(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_INTERSECTION, "select id, st_intersection(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_SYMDIFFERENCE, "select id, st_symdifference(geom, st_geomfromtext(:filter, 0)) as result from %s" ); sqls.put( ST_UNION, "select id, st_union(geom, st_geomfromtext(:filter, 0)) as result from %s" ); } }
MySqlNativeSqlTemplates
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Owner.java
{ "start": 435, "end": 815 }
class ____ { @Id @GeneratedValue private Integer id; @OneToOne(cascade = CascadeType.ALL) @PrimaryKeyJoinColumn private OwnerAddress address; public OwnerAddress getAddress() { return address; } public void setAddress(OwnerAddress address) { this.address = address; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
Owner
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/inject/annotation/EvaluatedAnnotationMetadata.java
{ "start": 1487, "end": 4036 }
class ____ extends MappingAnnotationMetadataDelegate implements BeanContextConfigurable, BeanDefinitionAware { private final AnnotationMetadata delegateAnnotationMetadata; private ConfigurableExpressionEvaluationContext evaluationContext; private EvaluatedAnnotationMetadata(AnnotationMetadata targetMetadata, ConfigurableExpressionEvaluationContext evaluationContext) { this.delegateAnnotationMetadata = targetMetadata; this.evaluationContext = evaluationContext; } /** * @return The evaluation context. * @since 4.1.0 */ public @NonNull ConfigurableExpressionEvaluationContext getEvaluationContext() { return evaluationContext; } /** * Provide a copy of this annotation metadata with passed method arguments. * * @param thisObject The object that represent this object * @param args arguments passed to method * @return copy of annotation metadata */ public EvaluatedAnnotationMetadata withArguments(@Nullable Object thisObject, Object[] args) { return new EvaluatedAnnotationMetadata( delegateAnnotationMetadata, evaluationContext.withArguments(thisObject, args) ); } @Override public void configure(BeanContext context) { evaluationContext = evaluationContext.withBeanContext(context); } @Override public void setBeanDefinition(BeanDefinition<?> beanDefinition) { evaluationContext = evaluationContext.withOwningBean(beanDefinition); } public static AnnotationMetadata wrapIfNecessary(AnnotationMetadata targetMetadata) { if (targetMetadata == null) { return null; } else if (targetMetadata instanceof EvaluatedAnnotationMetadata) { return targetMetadata; } else if (targetMetadata.hasEvaluatedExpressions()) { return new EvaluatedAnnotationMetadata(targetMetadata, new DefaultExpressionEvaluationContext()); } return targetMetadata; } @Override public boolean hasEvaluatedExpressions() { // this type of metadata always has evaluated expressions return true; } @Override public AnnotationMetadata getAnnotationMetadata() { return delegateAnnotationMetadata; } @Override public <T extends Annotation> AnnotationValue<T> mapAnnotationValue(AnnotationValue<T> av) { return new EvaluatedAnnotationValue<>(av, evaluationContext); } }
EvaluatedAnnotationMetadata
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/StructuredLogLayoutTests.java
{ "start": 1597, "end": 5696 }
class ____ extends AbstractStructuredLoggingTests { private MockEnvironment environment; private LoggerContext loggerContext; @BeforeEach void setup() { this.environment = new MockEnvironment(); this.environment.setProperty("logging.structured.json.stacktrace.printer", SimpleStackTracePrinter.class.getName()); this.loggerContext = (LoggerContext) LogManager.getContext(false); this.loggerContext.putObject(Log4J2LoggingSystem.ENVIRONMENT_KEY, this.environment); } @AfterEach void cleanup() { this.loggerContext.removeObject(Log4J2LoggingSystem.ENVIRONMENT_KEY); } @Test @SuppressWarnings("unchecked") void shouldSupportEcsCommonFormat() { StructuredLogLayout layout = newBuilder().setFormat("ecs").build(); String json = layout.toSerializable(createEvent(new RuntimeException("Boom!"))); Map<String, Object> deserialized = deserialize(json); assertThat(deserialized).containsEntry("ecs", Map.of("version", "8.11")); Map<String, Object> error = (Map<String, Object>) deserialized.get("error"); assertThat(error).isNotNull(); assertThat(error.get("stack_trace")).isEqualTo("stacktrace:RuntimeException"); } @Test @SuppressWarnings("unchecked") void shouldOutputNestedAdditionalEcsJson() { this.environment.setProperty("logging.structured.json.add.extra.value", "test"); StructuredLogLayout layout = newBuilder().setFormat("ecs").build(); String json = layout.toSerializable(createEvent(new RuntimeException("Boom!"))); Map<String, Object> deserialized = deserialize(json); assertThat(deserialized).containsKey("extra"); assertThat((Map<String, Object>) deserialized.get("extra")).containsEntry("value", "test"); System.out.println(deserialized); } @Test void shouldSupportLogstashCommonFormat() { StructuredLogLayout layout = newBuilder().setFormat("logstash").build(); String json = layout.toSerializable(createEvent(new RuntimeException("Boom!"))); Map<String, Object> deserialized = deserialize(json); assertThat(deserialized).containsKey("@version"); assertThat(deserialized.get("stack_trace")).isEqualTo("stacktrace:RuntimeException"); } @Test void shouldSupportGelfCommonFormat() { StructuredLogLayout layout = newBuilder().setFormat("gelf").build(); String json = layout.toSerializable(createEvent(new RuntimeException("Boom!"))); Map<String, Object> deserialized = deserialize(json); assertThat(deserialized).containsKey("version"); assertThat(deserialized.get("_error_stack_trace")).isEqualTo("stacktrace:RuntimeException"); } @Test void shouldSupportCustomFormat() { StructuredLogLayout layout = newBuilder().setFormat(CustomLog4j2StructuredLoggingFormatter.class.getName()) .build(); String format = layout.toSerializable(createEvent()); assertThat(format).isEqualTo("custom-format"); } @Test void shouldInjectCustomFormatConstructorParameters() { this.environment.setProperty("spring.application.pid", "42"); StructuredLogLayout layout = newBuilder() .setFormat(CustomLog4j2StructuredLoggingFormatterWithInjection.class.getName()) .build(); String format = layout.toSerializable(createEvent()); assertThat(format).isEqualTo("custom-format-with-injection pid=42"); } @Test void shouldCheckTypeArgument() { assertThatIllegalStateException().isThrownBy( () -> newBuilder().setFormat(CustomLog4j2StructuredLoggingFormatterWrongType.class.getName()).build()) .withMessageContaining("must be org.apache.logging.log4j.core.LogEvent but was java.lang.String"); } @Test void shouldCheckTypeArgumentWithRawType() { assertThatIllegalStateException() .isThrownBy( () -> newBuilder().setFormat(CustomLog4j2StructuredLoggingFormatterRawType.class.getName()).build()) .withMessageContaining("must be org.apache.logging.log4j.core.LogEvent but was null"); } @Test void shouldFailIfNoCommonOrCustomFormatIsSet() { assertThatIllegalArgumentException().isThrownBy(() -> newBuilder().setFormat("does-not-exist").build()) .withMessageContaining("Unknown format 'does-not-exist'. " + "Values can be a valid fully-qualified
StructuredLogLayoutTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/HighlightingFormatter.java
{ "start": 580, "end": 3073 }
class ____ implements Formatter { private static final Set<String> KEYWORDS_LOWERCASED = new HashSet<>( new AnsiSqlKeywords().sql2003() ); static { // additional keywords not reserved by ANSI SQL 2003 KEYWORDS_LOWERCASED.addAll( Arrays.asList( "key", "sequence", "cascade", "increment", "boolean", "offset", "first", "next", "returning" ) ); } public static final Formatter INSTANCE = new HighlightingFormatter( "34", // blue "36", // cyan "32" ); private static final String SYMBOLS_AND_WS = "=><!+-*/()',.|&`\"?" + WHITESPACE; private static String escape(String code) { return "\u001b[" + code + "m"; } private final String keywordEscape; private final String stringEscape; private final String quotedEscape; private final String normalEscape; /** * @param keywordCode the ANSI escape code to use for highlighting SQL keywords * @param stringCode the ANSI escape code to use for highlighting SQL strings */ public HighlightingFormatter(String keywordCode, String stringCode, String quotedCode) { keywordEscape = escape( keywordCode ); stringEscape = escape( stringCode ); quotedEscape = escape( quotedCode ); normalEscape = escape( "0" ); } @Override public String format(String sql) { if ( isEmpty( sql ) ) { return sql; } StringBuilder result = new StringBuilder(); boolean inString = false; boolean inQuoted = false; for ( StringTokenizer tokenizer = new StringTokenizer( sql, SYMBOLS_AND_WS, true ); tokenizer.hasMoreTokens(); ) { String token = tokenizer.nextToken(); switch ( token ) { case "\"": case "`": // for MySQL if ( inString ) { result.append( token ); } else if ( inQuoted ) { inQuoted = false; result.append( token ).append( normalEscape ); } else { inQuoted = true; result.append( quotedEscape ).append( token ); } break; case "'": if ( inQuoted ) { result.append( '\'' ); } else if ( inString ) { inString = false; result.append( '\'' ).append( normalEscape ); } else { inString = true; result.append( stringEscape ).append( '\'' ); } break; default: if ( !inQuoted && KEYWORDS_LOWERCASED.contains( token.toLowerCase( Locale.ROOT ) ) ) { result.append( keywordEscape ).append( token ).append( normalEscape ); } else { result.append( token ); } } } return result.toString(); } }
HighlightingFormatter
java
google__guice
core/test/com/google/inject/BinderTestSuite.java
{ "start": 23358, "end": 23534 }
class ____ extends Injectable { @Inject public void inject(A a, Provider<A> aProvider) { this.value = a; this.provider = aProvider; } } static
InjectsA
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/over/NonTimeOverWindowTestBase.java
{ "start": 4322, "end": 5434 }
class ____ implements RecordComparator { private int pos; private boolean isAscending; public LongRecordComparator(int pos, boolean isAscending) { this.pos = pos; this.isAscending = isAscending; } @Override public int compare(RowData o1, RowData o2) { boolean null0At1 = o1.isNullAt(pos); boolean null0At2 = o2.isNullAt(pos); int cmp0 = null0At1 && null0At2 ? 0 : (null0At1 ? -1 : (null0At2 ? 1 : Long.compare(o1.getLong(pos), o2.getLong(pos)))); if (cmp0 != 0) { if (isAscending) { return cmp0; } else { return -cmp0; } } return 0; } } /** Custom test row equaliser for comparing rows. */ public static
LongRecordComparator
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/license/GetFeatureUsageRequest.java
{ "start": 501, "end": 798 }
class ____ extends LegacyActionRequest { public GetFeatureUsageRequest() {} public GetFeatureUsageRequest(StreamInput in) throws IOException { super(in); } @Override public ActionRequestValidationException validate() { return null; } }
GetFeatureUsageRequest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/jdk/MapKeySerializationTest.java
{ "start": 1996, "end": 2026 }
enum ____ { } static
ABCMixin
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemamanager/SchemaManagerResyncSequencesPooledLoTest.java
{ "start": 952, "end": 1552 }
class ____ { @Test void test(SessionFactoryScope scope) { var schemaManager = scope.getSessionFactory().getSchemaManager(); scope.inStatelessTransaction( ss -> { ss.upsert( new EntityWithSequence(50L, "x") ); ss.upsert( new EntityWithSequence(100L, "y") ); ss.upsert( new EntityWithSequence(200L, "z") ); } ); schemaManager.resynchronizeGenerators(); scope.inStatelessTransaction( ss -> { var entity = new EntityWithSequence(); ss.insert( entity ); assertEquals(201L, entity.id); }); } @Entity(name = "EntityWithSequence") static
SchemaManagerResyncSequencesPooledLoTest
java
alibaba__druid
core/src/main/java/com/alibaba/druid/mock/handler/MockExecuteHandler.java
{ "start": 772, "end": 894 }
interface ____ { ResultSet executeQuery(MockStatementBase statement, String sql) throws SQLException; }
MockExecuteHandler
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/jdbc/AbstractSQL.java
{ "start": 12769, "end": 12869 }
enum ____ { DELETE, INSERT, SELECT, UPDATE } private
StatementType
java
elastic__elasticsearch
x-pack/plugin/security/qa/multi-cluster/src/javaRestTest/java/org/elasticsearch/xpack/remotecluster/RemoteClusterSecurityWithMixedModelRemotesRestIT.java
{ "start": 609, "end": 4996 }
class ____ extends AbstractRemoteClusterSecurityWithMultipleRemotesRestIT { private static final AtomicReference<Map<String, Object>> API_KEY_MAP_REF = new AtomicReference<>(); static { fulfillingCluster = ElasticsearchCluster.local() .name("fulfilling-cluster") .apply(commonClusterConfig) .setting("remote_cluster_server.enabled", "true") .setting("remote_cluster.port", "0") .setting("xpack.security.remote_cluster_server.ssl.enabled", "true") .setting("xpack.security.remote_cluster_server.ssl.key", "remote-cluster.key") .setting("xpack.security.remote_cluster_server.ssl.certificate", "remote-cluster.crt") .keystore("xpack.security.remote_cluster_server.ssl.secure_key_passphrase", "remote-cluster-password") .build(); otherFulfillingCluster = ElasticsearchCluster.local().name("fulfilling-cluster-2").apply(commonClusterConfig).build(); queryCluster = ElasticsearchCluster.local() .name("query-cluster") .apply(commonClusterConfig) .setting("xpack.security.remote_cluster_client.ssl.enabled", "true") .setting("xpack.security.remote_cluster_client.ssl.certificate_authorities", "remote-cluster-ca.crt") .keystore("cluster.remote.my_remote_cluster.credentials", () -> { if (API_KEY_MAP_REF.get() == null) { final Map<String, Object> apiKeyMap = createCrossClusterAccessApiKey(""" { "search": [ { "names": ["cluster1_index*"] } ] }"""); API_KEY_MAP_REF.set(apiKeyMap); } return (String) API_KEY_MAP_REF.get().get("encoded"); }) .build(); } @ClassRule // Use a RuleChain to ensure that fulfilling cluster is started before query cluster public static TestRule clusterRule = RuleChain.outerRule(fulfillingCluster).around(otherFulfillingCluster).around(queryCluster); @Override protected void configureRolesOnClusters() throws IOException { // Other fulfilling cluster { // In the basic model, we need to set up the role on the FC final var putRoleRequest = new Request("PUT", "/_security/role/" + REMOTE_SEARCH_ROLE); putRoleRequest.setJsonEntity(""" { "indices": [ { "names": ["cluster2_index1"], "privileges": ["read", "read_cross_cluster"] } ] }"""); assertOK(performRequestAgainstOtherFulfillingCluster(putRoleRequest)); } // Query cluster { // Create user role with privileges for remote and local indices final var putRoleRequest = new Request("PUT", "/_security/role/" + REMOTE_SEARCH_ROLE); putRoleRequest.setJsonEntity(""" { "indices": [ { "names": ["local_index"], "privileges": ["read"] } ], "remote_indices": [ { "names": ["cluster1_index1"], "privileges": ["read", "read_cross_cluster"], "clusters": ["my_remote_cluster"] } ] }"""); assertOK(adminClient().performRequest(putRoleRequest)); final var putUserRequest = new Request("PUT", "/_security/user/" + REMOTE_SEARCH_USER); putUserRequest.setJsonEntity(""" { "password": "x-pack-test-password", "roles" : ["remote_search"] }"""); assertOK(adminClient().performRequest(putUserRequest)); } } @Override protected void configureRemoteCluster() throws Exception { super.configureRemoteCluster(); configureRemoteCluster("my_remote_cluster_2", otherFulfillingCluster, true, randomBoolean(), randomBoolean()); } }
RemoteClusterSecurityWithMixedModelRemotesRestIT
java
netty__netty
handler/src/main/java/io/netty/handler/ipfilter/IpSubnetFilter.java
{ "start": 1855, "end": 8981 }
class ____ extends AbstractRemoteAddressFilter<InetSocketAddress> { private final boolean acceptIfNotFound; private final IpSubnetFilterRule[] ipv4Rules; private final IpSubnetFilterRule[] ipv6Rules; private final IpFilterRuleType ipFilterRuleTypeIPv4; private final IpFilterRuleType ipFilterRuleTypeIPv6; /** * <p> Create new {@link IpSubnetFilter} Instance with specified {@link IpSubnetFilterRule} as array. </p> * <p> {@code acceptIfNotFound} is set to {@code true}. </p> * * @param rules {@link IpSubnetFilterRule} as an array */ public IpSubnetFilter(IpSubnetFilterRule... rules) { this(true, Arrays.asList(ObjectUtil.checkNotNull(rules, "rules"))); } /** * <p> Create new {@link IpSubnetFilter} Instance with specified {@link IpSubnetFilterRule} as array * and specify if we'll accept a connection if we don't find it in the rule(s). </p> * * @param acceptIfNotFound {@code true} if we'll accept connection if not found in rule(s). * @param rules {@link IpSubnetFilterRule} as an array */ public IpSubnetFilter(boolean acceptIfNotFound, IpSubnetFilterRule... rules) { this(acceptIfNotFound, Arrays.asList(ObjectUtil.checkNotNull(rules, "rules"))); } /** * <p> Create new {@link IpSubnetFilter} Instance with specified {@link IpSubnetFilterRule} as {@link List}. </p> * <p> {@code acceptIfNotFound} is set to {@code true}. </p> * * @param rules {@link IpSubnetFilterRule} as a {@link List} */ public IpSubnetFilter(List<IpSubnetFilterRule> rules) { this(true, rules); } /** * <p> Create new {@link IpSubnetFilter} Instance with specified {@link IpSubnetFilterRule} as {@link List} * and specify if we'll accept a connection if we don't find it in the rule(s). </p> * * @param acceptIfNotFound {@code true} if we'll accept connection if not found in rule(s). * @param rules {@link IpSubnetFilterRule} as a {@link List} */ public IpSubnetFilter(boolean acceptIfNotFound, List<IpSubnetFilterRule> rules) { ObjectUtil.checkNotNull(rules, "rules"); this.acceptIfNotFound = acceptIfNotFound; int numAcceptIPv4 = 0; int numRejectIPv4 = 0; int numAcceptIPv6 = 0; int numRejectIPv6 = 0; List<IpSubnetFilterRule> unsortedIPv4Rules = new ArrayList<IpSubnetFilterRule>(); List<IpSubnetFilterRule> unsortedIPv6Rules = new ArrayList<IpSubnetFilterRule>(); // Iterate over rules and check for `null` rule. for (IpSubnetFilterRule ipSubnetFilterRule : rules) { ObjectUtil.checkNotNull(ipSubnetFilterRule, "rule"); if (ipSubnetFilterRule.getFilterRule() instanceof IpSubnetFilterRule.Ip4SubnetFilterRule) { unsortedIPv4Rules.add(ipSubnetFilterRule); if (ipSubnetFilterRule.ruleType() == IpFilterRuleType.ACCEPT) { numAcceptIPv4++; } else { numRejectIPv4++; } } else { unsortedIPv6Rules.add(ipSubnetFilterRule); if (ipSubnetFilterRule.ruleType() == IpFilterRuleType.ACCEPT) { numAcceptIPv6++; } else { numRejectIPv6++; } } } /* * If Number of ACCEPT rule is 0 and number of REJECT rules is more than 0, * then all rules are of "REJECT" type. * * In this case, we'll set `ipFilterRuleTypeIPv4` to `IpFilterRuleType.REJECT`. * * If Number of ACCEPT rules are more than 0 and number of REJECT rules is 0, * then all rules are of "ACCEPT" type. * * In this case, we'll set `ipFilterRuleTypeIPv4` to `IpFilterRuleType.ACCEPT`. */ if (numAcceptIPv4 == 0 && numRejectIPv4 > 0) { ipFilterRuleTypeIPv4 = IpFilterRuleType.REJECT; } else if (numAcceptIPv4 > 0 && numRejectIPv4 == 0) { ipFilterRuleTypeIPv4 = IpFilterRuleType.ACCEPT; } else { ipFilterRuleTypeIPv4 = null; } if (numAcceptIPv6 == 0 && numRejectIPv6 > 0) { ipFilterRuleTypeIPv6 = IpFilterRuleType.REJECT; } else if (numAcceptIPv6 > 0 && numRejectIPv6 == 0) { ipFilterRuleTypeIPv6 = IpFilterRuleType.ACCEPT; } else { ipFilterRuleTypeIPv6 = null; } this.ipv4Rules = unsortedIPv4Rules.isEmpty() ? null : sortAndFilter(unsortedIPv4Rules); this.ipv6Rules = unsortedIPv6Rules.isEmpty() ? null : sortAndFilter(unsortedIPv6Rules); } @Override protected boolean accept(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) { if (ipv4Rules != null && remoteAddress.getAddress() instanceof Inet4Address) { int indexOf = Arrays.binarySearch(ipv4Rules, remoteAddress, IpSubnetFilterRuleComparator.INSTANCE); if (indexOf >= 0) { if (ipFilterRuleTypeIPv4 == null) { return ipv4Rules[indexOf].ruleType() == IpFilterRuleType.ACCEPT; } else { return ipFilterRuleTypeIPv4 == IpFilterRuleType.ACCEPT; } } } else if (ipv6Rules != null) { int indexOf = Arrays.binarySearch(ipv6Rules, remoteAddress, IpSubnetFilterRuleComparator.INSTANCE); if (indexOf >= 0) { if (ipFilterRuleTypeIPv6 == null) { return ipv6Rules[indexOf].ruleType() == IpFilterRuleType.ACCEPT; } else { return ipFilterRuleTypeIPv6 == IpFilterRuleType.ACCEPT; } } } return acceptIfNotFound; } /** * <ol> * <li> Sort the list </li> * <li> Remove over-lapping subnet </li> * <li> Sort the list again </li> * </ol> */ @SuppressWarnings("ZeroLengthArrayAllocation") private static IpSubnetFilterRule[] sortAndFilter(List<IpSubnetFilterRule> rules) { Collections.sort(rules); Iterator<IpSubnetFilterRule> iterator = rules.iterator(); List<IpSubnetFilterRule> toKeep = new ArrayList<IpSubnetFilterRule>(); IpSubnetFilterRule parentRule = iterator.hasNext() ? iterator.next() : null; if (parentRule != null) { toKeep.add(parentRule); } while (iterator.hasNext()) { // Grab a potential child rule. IpSubnetFilterRule childRule = iterator.next(); // If parentRule matches childRule, then there's no need to keep the child rule. // Otherwise, the rules are distinct and we need both. if (!parentRule.matches(new InetSocketAddress(childRule.getIpAddress(), 1))) { toKeep.add(childRule); // Then we'll keep the child rule around as the parent for the next round. parentRule = childRule; } } return toKeep.toArray(new IpSubnetFilterRule[0]); } }
IpSubnetFilter
java
google__auto
value/src/main/java/com/google/auto/value/processor/BuilderMethodClassifierForAutoBuilder.java
{ "start": 1568, "end": 2946 }
class ____ extends BuilderMethodClassifier<VariableElement> { private final Executable executable; private final ImmutableBiMap<VariableElement, String> paramToPropertyName; private BuilderMethodClassifierForAutoBuilder( ErrorReporter errorReporter, ProcessingEnvironment processingEnv, Executable executable, TypeMirror builtType, TypeElement builderType, ImmutableBiMap<VariableElement, String> paramToPropertyName, ImmutableMap<String, AnnotatedTypeMirror> rewrittenPropertyTypes, ImmutableSet<String> propertiesWithDefaults, Nullables nullables) { super( errorReporter, processingEnv, builtType, builderType, rewrittenPropertyTypes, propertiesWithDefaults, nullables); this.executable = executable; this.paramToPropertyName = paramToPropertyName; } /** * Classifies the given methods from a builder type and its ancestors. * * @param methods the abstract methods in {@code builderType} and its ancestors. * @param errorReporter where to report errors. * @param processingEnv the ProcessingEnvironment for annotation processing. * @param executable the constructor or static method that AutoBuilder will call. * @param builtType the type to be built. * @param builderType the builder
BuilderMethodClassifierForAutoBuilder
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/resolution/broken/FieldProducerBean.java
{ "start": 195, "end": 357 }
class ____ { @Produces @Typed(value = MyOtherBean.class) public ProducedBean produceBean() { return new ProducedBean(); } }
FieldProducerBean
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/testing/envers/EntityManagerFactoryAccess.java
{ "start": 381, "end": 578 }
interface ____ extends DialectAccess { EntityManagerFactory getEntityManagerFactory(); @Override default Dialect getDialect() { return DialectContext.getDialect(); } }
EntityManagerFactoryAccess
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTablePartitionSetProperties.java
{ "start": 435, "end": 1422 }
class ____ extends SQLObjectImpl implements SQLAlterTableItem { private final List<SQLAssignItem> partition = new ArrayList<SQLAssignItem>(4); private final List<SQLAssignItem> partitionProperties = new ArrayList<SQLAssignItem>(4); private SQLExpr location; public List<SQLAssignItem> getPartitionProperties() { return partitionProperties; } public List<SQLAssignItem> getPartition() { return partition; } public SQLExpr getLocation() { return location; } public void setLocation(SQLExpr x) { if (x != null) { x.setParent(this); } this.location = x; } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, partition); acceptChild(visitor, partitionProperties); acceptChild(visitor, location); } visitor.endVisit(this); } }
SQLAlterTablePartitionSetProperties
java
elastic__elasticsearch
x-pack/plugin/old-lucene-versions/src/main/java/org/elasticsearch/xpack/lucene/bwc/codecs/lucene70/fst/ReverseRandomAccessReader.java
{ "start": 1079, "end": 1923 }
class ____ extends FST.BytesReader { private final RandomAccessInput in; private long pos; ReverseRandomAccessReader(RandomAccessInput in) { this.in = in; } @Override public byte readByte() throws IOException { return in.readByte(pos--); } @Override public void readBytes(byte[] b, int offset, int len) throws IOException { int i = offset, end = offset + len; while (i < end) { b[i++] = in.readByte(pos--); } } @Override public void skipBytes(long count) { pos -= count; } @Override public long getPosition() { return pos; } @Override public void setPosition(long pos) { this.pos = pos; } @Override public boolean reversed() { return true; } }
ReverseRandomAccessReader
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/operators/base/DeltaIterationBase.java
{ "start": 3039, "end": 11026 }
class ____<ST, WT> extends DualInputOperator<ST, WT, ST, AbstractRichFunction> implements IterationOperator { private final Operator<ST> solutionSetPlaceholder; private final Operator<WT> worksetPlaceholder; private Operator<ST> solutionSetDelta; private Operator<WT> nextWorkset; /** The positions of the keys in the solution tuple. */ private final int[] solutionSetKeyFields; /** The maximum number of iterations. Possibly used only as a safeguard. */ private int maxNumberOfIterations = -1; private final AggregatorRegistry aggregators = new AggregatorRegistry(); private boolean solutionSetUnManaged; // -------------------------------------------------------------------------------------------- public DeltaIterationBase(BinaryOperatorInformation<ST, WT, ST> operatorInfo, int keyPosition) { this(operatorInfo, new int[] {keyPosition}); } public DeltaIterationBase( BinaryOperatorInformation<ST, WT, ST> operatorInfo, int[] keyPositions) { this(operatorInfo, keyPositions, "<Unnamed Delta Iteration>"); } public DeltaIterationBase( BinaryOperatorInformation<ST, WT, ST> operatorInfo, int keyPosition, String name) { this(operatorInfo, new int[] {keyPosition}, name); } public DeltaIterationBase( BinaryOperatorInformation<ST, WT, ST> operatorInfo, int[] keyPositions, String name) { super( new UserCodeClassWrapper<AbstractRichFunction>(AbstractRichFunction.class), operatorInfo, name); this.solutionSetKeyFields = keyPositions; solutionSetPlaceholder = new SolutionSetPlaceHolder<ST>( this, new OperatorInformation<ST>(operatorInfo.getFirstInputType())); worksetPlaceholder = new WorksetPlaceHolder<WT>( this, new OperatorInformation<WT>(operatorInfo.getSecondInputType())); } // -------------------------------------------------------------------------------------------- public int[] getSolutionSetKeyFields() { return this.solutionSetKeyFields; } public void setMaximumNumberOfIterations(int maxIterations) { this.maxNumberOfIterations = maxIterations; } public int getMaximumNumberOfIterations() { return this.maxNumberOfIterations; } @Override public AggregatorRegistry getAggregators() { return this.aggregators; } // -------------------------------------------------------------------------------------------- // Getting / Setting of the step function input place-holders // -------------------------------------------------------------------------------------------- /** * Gets the contract that represents the solution set for the step function. * * @return The solution set for the step function. */ public Operator<ST> getSolutionSet() { return this.solutionSetPlaceholder; } /** * Gets the contract that represents the workset for the step function. * * @return The workset for the step function. */ public Operator<WT> getWorkset() { return this.worksetPlaceholder; } /** * Sets the contract of the step function that represents the next workset. This contract is * considered one of the two sinks of the step function (the other one being the solution set * delta). * * @param result The contract representing the next workset. */ public void setNextWorkset(Operator<WT> result) { this.nextWorkset = result; } /** * Gets the contract that has been set as the next workset. * * @return The contract that has been set as the next workset. */ public Operator<WT> getNextWorkset() { return this.nextWorkset; } /** * Sets the contract of the step function that represents the solution set delta. This contract * is considered one of the two sinks of the step function (the other one being the next * workset). * * @param delta The contract representing the solution set delta. */ public void setSolutionSetDelta(Operator<ST> delta) { this.solutionSetDelta = delta; } /** * Gets the contract that has been set as the solution set delta. * * @return The contract that has been set as the solution set delta. */ public Operator<ST> getSolutionSetDelta() { return this.solutionSetDelta; } // -------------------------------------------------------------------------------------------- // Getting / Setting the Inputs // -------------------------------------------------------------------------------------------- /** * Returns the initial solution set input, or null, if none is set. * * @return The iteration's initial solution set input. */ public Operator<ST> getInitialSolutionSet() { return getFirstInput(); } /** * Returns the initial workset input, or null, if none is set. * * @return The iteration's workset input. */ public Operator<WT> getInitialWorkset() { return getSecondInput(); } /** * Sets the given input as the initial solution set. * * @param input The contract to set the initial solution set. */ public void setInitialSolutionSet(Operator<ST> input) { setFirstInput(input); } /** * Sets the given input as the initial workset. * * @param input The contract to set as the initial workset. */ public void setInitialWorkset(Operator<WT> input) { setSecondInput(input); } /** * DeltaIteration meta operator cannot have broadcast inputs. * * @return An empty map. */ public Map<String, Operator<?>> getBroadcastInputs() { return Collections.emptyMap(); } /** * The DeltaIteration meta operator cannot have broadcast inputs. This method always throws an * exception. * * @param name Ignored. * @param root Ignored. */ public void setBroadcastVariable(String name, Operator<?> root) { throw new UnsupportedOperationException( "The DeltaIteration meta operator cannot have broadcast inputs."); } /** * The DeltaIteration meta operator cannot have broadcast inputs. This method always throws an * exception. * * @param inputs Ignored */ public <X> void setBroadcastVariables(Map<String, Operator<X>> inputs) { throw new UnsupportedOperationException( "The DeltaIteration meta operator cannot have broadcast inputs."); } /** * Sets whether to keep the solution set in managed memory (safe against heap exhaustion) or * unmanaged memory (objects on heap). * * @param solutionSetUnManaged True to keep the solution set in unmanaged memory, false to keep * it in managed memory. * @see #isSolutionSetUnManaged() */ public void setSolutionSetUnManaged(boolean solutionSetUnManaged) { this.solutionSetUnManaged = solutionSetUnManaged; } /** * gets whether the solution set is in managed or unmanaged memory. * * @return True, if the solution set is in unmanaged memory (object heap), false if in managed * memory. * @see #setSolutionSetUnManaged(boolean) */ public boolean isSolutionSetUnManaged() { return solutionSetUnManaged; } // -------------------------------------------------------------------------------------------- // Place-holder Operators // -------------------------------------------------------------------------------------------- /** * Specialized operator to use as a recognizable place-holder for the working set input to the * step function. */ public static
DeltaIterationBase
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanSupport.java
{ "start": 2334, "end": 2811 }
class ____ { private static final List<String> IGNORED_ATTRS = Arrays.asList( ReferenceAttributes.ID, ReferenceAttributes.GROUP, ReferenceAttributes.VERSION, ReferenceAttributes.INTERFACE, ReferenceAttributes.INTERFACE_NAME, ReferenceAttributes.INTERFACE_CLASS); public static void convertReferenceProps(Map<String, Object> attributes, Class defaultInterfaceClass) { //
ReferenceBeanSupport
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/StateLocalitySlotAssigner.java
{ "start": 2296, "end": 2374 }
class ____ implements SlotAssigner { private static
StateLocalitySlotAssigner
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NanoTimePatternConverterTest.java
{ "start": 1053, "end": 1533 }
class ____ { @Test void testConverterAppendsLogEventNanoTimeToStringBuilder() { final LogEvent event = Log4jLogEvent.newBuilder() // .setNanoTime(1234567) .build(); final StringBuilder sb = new StringBuilder(); final NanoTimePatternConverter converter = NanoTimePatternConverter.newInstance(null); converter.format(event, sb); assertEquals("1234567", sb.toString()); } }
NanoTimePatternConverterTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/aot/AbstractAotTests.java
{ "start": 878, "end": 11512 }
class ____ { static final String[] expectedSourceFilesForBasicSpringTests = { // BasicSpringJupiterSharedConfigTests -- not generated b/c already generated for AbstractSpringJupiterParameterizedClassTests.InheritedNestedTests. // BasicSpringJupiterTests -- not generated b/c already generated for AbstractSpringJupiterParameterizedClassTests.InheritedNestedTests. // BasicSpringJupiterTests.NestedTests -- not generated b/c already generated for BasicSpringJupiterParameterizedClassTests.NestedTests. // Global "org/springframework/test/context/aot/AotTestContextInitializers__Generated.java", "org/springframework/test/context/aot/AotTestAttributes__Generated.java", // AbstractSpringJupiterParameterizedClassTests.InheritedNestedTests "org/springframework/context/event/DefaultEventListenerFactory__TestContext001_BeanDefinitions.java", "org/springframework/context/event/EventListenerMethodProcessor__TestContext001_BeanDefinitions.java", "org/springframework/test/context/aot/samples/basic/AbstractSpringJupiterParameterizedClassTests_InheritedNestedTests__TestContext001_ApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/AbstractSpringJupiterParameterizedClassTests_InheritedNestedTests__TestContext001_BeanFactoryRegistrations.java", "org/springframework/test/context/aot/samples/basic/AbstractSpringJupiterParameterizedClassTests_InheritedNestedTests__TestContext001_ManagementApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/AbstractSpringJupiterParameterizedClassTests_InheritedNestedTests__TestContext001_ManagementBeanFactoryRegistrations.java", "org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext001_BeanDefinitions.java", "org/springframework/test/context/aot/samples/management/ManagementConfiguration__TestContext001_BeanDefinitions.java", "org/springframework/test/context/aot/samples/management/ManagementMessageService__TestContext001_ManagementBeanDefinitions.java", "org/springframework/test/context/support/DynamicPropertyRegistrarBeanInitializer__TestContext001_BeanDefinitions.java", // AbstractSpringJupiterParameterizedClassTests.InheritedNestedTests.InheritedDoublyNestedTests "org/springframework/context/event/DefaultEventListenerFactory__TestContext002_BeanDefinitions.java", "org/springframework/context/event/EventListenerMethodProcessor__TestContext002_BeanDefinitions.java", "org/springframework/test/context/aot/samples/basic/AbstractSpringJupiterParameterizedClassTests_InheritedNestedTests_InheritedDoublyNestedTests__TestContext002_ApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/AbstractSpringJupiterParameterizedClassTests_InheritedNestedTests_InheritedDoublyNestedTests__TestContext002_BeanFactoryRegistrations.java", "org/springframework/test/context/aot/samples/basic/AbstractSpringJupiterParameterizedClassTests_InheritedNestedTests_InheritedDoublyNestedTests__TestContext002_ManagementApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/AbstractSpringJupiterParameterizedClassTests_InheritedNestedTests_InheritedDoublyNestedTests__TestContext002_ManagementBeanFactoryRegistrations.java", "org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext002_BeanDefinitions.java", "org/springframework/test/context/aot/samples/management/ManagementConfiguration__TestContext002_BeanDefinitions.java", "org/springframework/test/context/aot/samples/management/ManagementMessageService__TestContext002_ManagementBeanDefinitions.java", "org/springframework/test/context/support/DynamicPropertyRegistrarBeanInitializer__TestContext002_BeanDefinitions.java", // BasicSpringJupiterImportedConfigTests "org/springframework/context/event/DefaultEventListenerFactory__TestContext003_BeanDefinitions.java", "org/springframework/context/event/EventListenerMethodProcessor__TestContext003_BeanDefinitions.java", "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterImportedConfigTests__TestContext003_ApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterImportedConfigTests__TestContext003_BeanDefinitions.java", "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterImportedConfigTests__TestContext003_BeanFactoryRegistrations.java", "org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext003_BeanDefinitions.java", "org/springframework/test/context/support/DynamicPropertyRegistrarBeanInitializer__TestContext003_BeanDefinitions.java", // BasicSpringJupiterParameterizedClassTests.NestedTests "org/springframework/context/event/DefaultEventListenerFactory__TestContext004_BeanDefinitions.java", "org/springframework/context/event/EventListenerMethodProcessor__TestContext004_BeanDefinitions.java", "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterParameterizedClassTests_NestedTests__TestContext004_ApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterParameterizedClassTests_NestedTests__TestContext004_BeanFactoryRegistrations.java", "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterParameterizedClassTests_NestedTests__TestContext004_ManagementApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterParameterizedClassTests_NestedTests__TestContext004_ManagementBeanFactoryRegistrations.java", "org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext004_BeanDefinitions.java", "org/springframework/test/context/aot/samples/management/ManagementConfiguration__TestContext004_BeanDefinitions.java", "org/springframework/test/context/aot/samples/management/ManagementMessageService__TestContext004_ManagementBeanDefinitions.java", "org/springframework/test/context/support/DynamicPropertyRegistrarBeanInitializer__TestContext004_BeanDefinitions.java", // BasicSpringJupiterParameterizedClassTests.NestedTests.DoublyNestedTests "org/springframework/context/event/DefaultEventListenerFactory__TestContext005_BeanDefinitions.java", "org/springframework/context/event/EventListenerMethodProcessor__TestContext005_BeanDefinitions.java", "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterParameterizedClassTests_NestedTests_DoublyNestedTests__TestContext005_ApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterParameterizedClassTests_NestedTests_DoublyNestedTests__TestContext005_BeanFactoryRegistrations.java", "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterParameterizedClassTests_NestedTests_DoublyNestedTests__TestContext005_ManagementApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterParameterizedClassTests_NestedTests_DoublyNestedTests__TestContext005_ManagementBeanFactoryRegistrations.java", "org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext005_BeanDefinitions.java", "org/springframework/test/context/aot/samples/management/ManagementConfiguration__TestContext005_BeanDefinitions.java", "org/springframework/test/context/aot/samples/management/ManagementMessageService__TestContext005_ManagementBeanDefinitions.java", "org/springframework/test/context/support/DynamicPropertyRegistrarBeanInitializer__TestContext005_BeanDefinitions.java", // BasicSpringTestNGTests "org/springframework/context/event/DefaultEventListenerFactory__TestContext006_BeanDefinitions.java", "org/springframework/context/event/EventListenerMethodProcessor__TestContext006_BeanDefinitions.java", "org/springframework/test/context/aot/samples/basic/BasicSpringTestNGTests__TestContext006_ApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/BasicSpringTestNGTests__TestContext006_BeanFactoryRegistrations.java", "org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext006_BeanDefinitions.java", "org/springframework/test/context/support/DynamicPropertyRegistrarBeanInitializer__TestContext006_BeanDefinitions.java", // BasicSpringVintageTests "org/springframework/context/event/DefaultEventListenerFactory__TestContext007_BeanDefinitions.java", "org/springframework/context/event/EventListenerMethodProcessor__TestContext007_BeanDefinitions.java", "org/springframework/test/context/aot/samples/basic/BasicSpringVintageTests__TestContext007_ApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/BasicSpringVintageTests__TestContext007_BeanFactoryRegistrations.java", "org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext007_BeanDefinitions.java", "org/springframework/test/context/support/DynamicPropertyRegistrarBeanInitializer__TestContext007_BeanDefinitions.java", // DisabledInAotRuntimeMethodLevelTests "org/springframework/context/event/DefaultEventListenerFactory__TestContext008_BeanDefinitions.java", "org/springframework/context/event/EventListenerMethodProcessor__TestContext008_BeanDefinitions.java", "org/springframework/test/context/aot/samples/basic/DisabledInAotRuntimeMethodLevelTests__TestContext008_ApplicationContextInitializer.java", "org/springframework/test/context/aot/samples/basic/DisabledInAotRuntimeMethodLevelTests__TestContext008_BeanDefinitions.java", "org/springframework/test/context/aot/samples/basic/DisabledInAotRuntimeMethodLevelTests__TestContext008_BeanFactoryRegistrations.java", "org/springframework/test/context/support/DynamicPropertyRegistrarBeanInitializer__TestContext008_BeanDefinitions.java" }; Stream<Class<?>> scan() { return new TestClassScanner(classpathRoots()).scan(); } Stream<Class<?>> scan(String... packageNames) { return new TestClassScanner(classpathRoots()).scan(packageNames); } Set<Path> classpathRoots() { try { return Set.of(classpathRoot()); } catch (Exception ex) { throw new RuntimeException(ex); } } Path classpathRoot() { try { return Paths.get(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()); } catch (Exception ex) { throw new RuntimeException(ex); } } Path classpathRoot(Class<?> clazz) { try { return Paths.get(clazz.getProtectionDomain().getCodeSource().getLocation().toURI()); } catch (Exception ex) { throw new RuntimeException(ex); } } }
AbstractAotTests
java
netty__netty
codec-http2/src/main/java/io/netty/handler/codec/http2/StreamBufferingEncoder.java
{ "start": 13924, "end": 15015 }
class ____ extends Frame { final Http2Headers headers; final int streamDependency; final boolean hasPriority; final short weight; final boolean exclusive; final int padding; final boolean endOfStream; HeadersFrame(Http2Headers headers, boolean hasPriority, int streamDependency, short weight, boolean exclusive, int padding, boolean endOfStream, ChannelPromise promise) { super(promise); this.headers = headers; this.hasPriority = hasPriority; this.streamDependency = streamDependency; this.weight = weight; this.exclusive = exclusive; this.padding = padding; this.endOfStream = endOfStream; } @Override void send(ChannelHandlerContext ctx, int streamId) { writeHeaders0(ctx, streamId, headers, hasPriority, streamDependency, weight, exclusive, padding, endOfStream, promise); } } private final
HeadersFrame
java
apache__camel
core/camel-management/src/test/java/org/apache/camel/management/JmxInstrumentationDisableOnCamelContextTest.java
{ "start": 1381, "end": 2926 }
class ____ extends JmxInstrumentationUsingPropertiesTest { @Override protected boolean useJmx() { return false; } @Override protected MBeanServerConnection getMBeanConnection() { return ManagementFactory.getPlatformMBeanServer(); } @Override protected CamelContext createCamelContext() throws Exception { CamelContext camel = super.createCamelContext(); camel.disableJMX(); return camel; } @Override @Test public void testMBeansRegistered() throws Exception { resolveMandatoryEndpoint("mock:end", MockEndpoint.class); Set<ObjectName> s = mbsc.queryNames(new ObjectName(domainName + ":type=endpoints,*"), null); assertEquals(0, s.size(), "Could not find 0 endpoints: " + s); s = mbsc.queryNames(new ObjectName(domainName + ":type=contexts,*"), null); assertEquals(0, s.size(), "Could not find 0 context: " + s); s = mbsc.queryNames(new ObjectName(domainName + ":type=processors,*"), null); assertEquals(0, s.size(), "Could not find 0 processor: " + s); s = mbsc.queryNames(new ObjectName(domainName + ":type=routes,*"), null); assertEquals(0, s.size(), "Could not find 0 route: " + s); } @Override protected void verifyCounter(MBeanServerConnection beanServer, ObjectName name) throws Exception { Set<ObjectName> s = beanServer.queryNames(name, null); assertEquals(0, s.size(), "Found mbeans: " + s); } }
JmxInstrumentationDisableOnCamelContextTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/ParameterMissingNullableTest.java
{ "start": 11779, "end": 12125 }
class ____ { Foo next; void foo(Foo foo) { for (; foo != null; foo = foo.next) {} } } """) .doTest(); } @Test public void negativeCallArgNotNull() { conservativeHelper .addSourceLines( "Foo.java", """
Foo
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/dynamic/batch/BatchSize.java
{ "start": 1961, "end": 2138 }
interface ____ { /** * Declares the batch size for the command method. * * @return a positive, non-zero number of commands. */ int value(); }
BatchSize
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestWorkPreservingUnmanagedAM.java
{ "start": 2157, "end": 12864 }
class ____ extends ParameterizedSchedulerTestBase { private YarnConfiguration conf; public void initTestWorkPreservingUnmanagedAM(SchedulerType type) throws IOException { initParameterizedSchedulerTestBase(type); setup(); } public void setup() { GenericTestUtils.setRootLogLevel(Level.DEBUG); conf = getConf(); UserGroupInformation.setConfiguration(conf); DefaultMetricsSystem.setMiniClusterMode(true); } /** * Test UAM work preserving restart. When the keepContainersAcrossAttempt flag * is on, we allow UAM to directly register again and move on without getting * the applicationAlreadyRegistered exception. */ protected void testUAMRestart(boolean keepContainers) throws Exception { // start RM MockRM rm = new MockRM(); rm.start(); MockNM nm = new MockNM("127.0.0.1:1234", 15120, rm.getResourceTrackerService()); nm.registerNode(); Set<NodeId> tokenCacheClientSide = new HashSet(); // create app and launch the UAM boolean unamanged = true; int maxAttempts = 1; boolean waitForAccepted = true; MockRMAppSubmissionData data = MockRMAppSubmissionData.Builder.createWithMemory(200, rm) .withAppName("") .withUser(UserGroupInformation.getCurrentUser().getShortUserName()) .withAcls(null) .withUnmanagedAM(unamanged) .withQueue(null) .withMaxAppAttempts(maxAttempts) .withCredentials(null) .withAppType(null) .withWaitForAppAcceptedState(waitForAccepted) .withKeepContainers(keepContainers) .build(); RMApp app = MockRMAppSubmitter.submit(rm, data); MockAM am = MockRM.launchUAM(app, rm, nm); // Register for the first time am.registerAppAttempt(); // Allocate two containers to UAM int numContainers = 3; AllocateResponse allocateResponse = am.allocate("127.0.0.1", 1000, numContainers, new ArrayList<ContainerId>()); allocateResponse.getNMTokens().forEach(token -> tokenCacheClientSide.add(token.getNodeId())); List<Container> conts = allocateResponse.getAllocatedContainers(); while (conts.size() < numContainers) { nm.nodeHeartbeat(true); allocateResponse = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()); allocateResponse.getNMTokens().forEach(token -> tokenCacheClientSide.add(token.getNodeId())); conts.addAll(allocateResponse.getAllocatedContainers()); Thread.sleep(100); } checkNMTokenForContainer(tokenCacheClientSide, conts); // Release one container List<ContainerId> releaseList = Collections.singletonList(conts.get(0).getId()); List<ContainerStatus> finishedConts = am.allocate(new ArrayList<ResourceRequest>(), releaseList) .getCompletedContainersStatuses(); while (finishedConts.size() < releaseList.size()) { nm.nodeHeartbeat(true); finishedConts .addAll(am .allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()) .getCompletedContainersStatuses()); Thread.sleep(100); } // Register for the second time RegisterApplicationMasterResponse response = null; try { response = am.registerAppAttempt(false); // When AM restart, it means nmToken in client side should be missing tokenCacheClientSide.clear(); response.getNMTokensFromPreviousAttempts() .forEach(token -> tokenCacheClientSide.add(token.getNodeId())); } catch (InvalidApplicationMasterRequestException e) { assertEquals(false, keepContainers); return; } assertEquals(true, keepContainers, "RM should not allow second register" + " for UAM without keep container flag "); // Expecting the two running containers previously assertEquals(2, response.getContainersFromPreviousAttempts().size()); assertEquals(1, response.getNMTokensFromPreviousAttempts().size()); // Allocate one more containers to UAM, just to be safe numContainers = 1; am.allocate("127.0.0.1", 1000, numContainers, new ArrayList<ContainerId>()); nm.nodeHeartbeat(true); allocateResponse = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()); allocateResponse.getNMTokens().forEach(token -> tokenCacheClientSide.add(token.getNodeId())); conts = allocateResponse.getAllocatedContainers(); while (conts.size() < numContainers) { nm.nodeHeartbeat(true); allocateResponse = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()); allocateResponse.getNMTokens().forEach(token -> tokenCacheClientSide.add(token.getNodeId())); conts.addAll(allocateResponse.getAllocatedContainers()); Thread.sleep(100); } checkNMTokenForContainer(tokenCacheClientSide, conts); rm.stop(); } protected void testUAMRestartWithoutTransferContainer(boolean keepContainers) throws Exception { // start RM MockRM rm = new MockRM(); rm.start(); MockNM nm = new MockNM("127.0.0.1:1234", 15120, rm.getResourceTrackerService()); nm.registerNode(); Set<NodeId> tokenCacheClientSide = new HashSet(); // create app and launch the UAM boolean unamanged = true; int maxAttempts = 1; boolean waitForAccepted = true; MockRMAppSubmissionData data = MockRMAppSubmissionData.Builder.createWithMemory(200, rm) .withAppName("") .withUser(UserGroupInformation.getCurrentUser().getShortUserName()) .withAcls(null) .withUnmanagedAM(unamanged) .withQueue(null) .withMaxAppAttempts(maxAttempts) .withCredentials(null) .withAppType(null) .withWaitForAppAcceptedState(waitForAccepted) .withKeepContainers(keepContainers) .build(); RMApp app = MockRMAppSubmitter.submit(rm, data); MockAM am = MockRM.launchUAM(app, rm, nm); // Register for the first time am.registerAppAttempt(); // Allocate two containers to UAM int numContainers = 3; AllocateResponse allocateResponse = am.allocate("127.0.0.1", 1000, numContainers, new ArrayList<ContainerId>()); allocateResponse.getNMTokens().forEach(token -> tokenCacheClientSide.add(token.getNodeId())); List<Container> conts = allocateResponse.getAllocatedContainers(); while (conts.size() < numContainers) { nm.nodeHeartbeat(true); allocateResponse = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()); allocateResponse.getNMTokens().forEach(token -> tokenCacheClientSide.add(token.getNodeId())); conts.addAll(allocateResponse.getAllocatedContainers()); Thread.sleep(100); } checkNMTokenForContainer(tokenCacheClientSide, conts); // Release all containers, then there are no transfer containfer app attempt List<ContainerId> releaseList = new ArrayList(); releaseList.add(conts.get(0).getId()); releaseList.add(conts.get(1).getId()); releaseList.add(conts.get(2).getId()); List<ContainerStatus> finishedConts = am.allocate(new ArrayList<ResourceRequest>(), releaseList) .getCompletedContainersStatuses(); while (finishedConts.size() < releaseList.size()) { nm.nodeHeartbeat(true); finishedConts .addAll(am .allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()) .getCompletedContainersStatuses()); Thread.sleep(100); } // Register for the second time RegisterApplicationMasterResponse response = null; try { response = am.registerAppAttempt(false); // When AM restart, it means nmToken in client side should be missing tokenCacheClientSide.clear(); response.getNMTokensFromPreviousAttempts() .forEach(token -> tokenCacheClientSide.add(token.getNodeId())); } catch (InvalidApplicationMasterRequestException e) { assertEquals(false, keepContainers); return; } assertEquals(true, keepContainers, "RM should not allow second register" + " for UAM without keep container flag "); // Expecting the zero running containers previously assertEquals(0, response.getContainersFromPreviousAttempts().size()); assertEquals(0, response.getNMTokensFromPreviousAttempts().size()); // Allocate one more containers to UAM, just to be safe numContainers = 1; am.allocate("127.0.0.1", 1000, numContainers, new ArrayList<ContainerId>()); nm.nodeHeartbeat(true); allocateResponse = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()); allocateResponse.getNMTokens().forEach(token -> tokenCacheClientSide.add(token.getNodeId())); conts = allocateResponse.getAllocatedContainers(); while (conts.size() < numContainers) { nm.nodeHeartbeat(true); allocateResponse = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()); allocateResponse.getNMTokens().forEach(token -> tokenCacheClientSide.add(token.getNodeId())); conts.addAll(allocateResponse.getAllocatedContainers()); Thread.sleep(100); } checkNMTokenForContainer(tokenCacheClientSide, conts); rm.stop(); } @Timeout(value = 600) @ParameterizedTest(name = "{0}") @MethodSource("getParameters") public void testUAMRestartKeepContainers(SchedulerType type) throws Exception { initTestWorkPreservingUnmanagedAM(type); testUAMRestart(true); } @Timeout(value = 600) @ParameterizedTest(name = "{0}") @MethodSource("getParameters") public void testUAMRestartNoKeepContainers(SchedulerType type) throws Exception { initTestWorkPreservingUnmanagedAM(type); testUAMRestart(false); } @Timeout(value = 600) @ParameterizedTest(name = "{0}") @MethodSource("getParameters") public void testUAMRestartKeepContainersWithoutTransferContainer( SchedulerType type) throws Exception { initTestWorkPreservingUnmanagedAM(type); testUAMRestartWithoutTransferContainer(true); } @Timeout(value = 600) @ParameterizedTest(name = "{0}") @MethodSource("getParameters") public void testUAMRestartNoKeepContainersWithoutTransferContainer( SchedulerType type) throws Exception { initTestWorkPreservingUnmanagedAM(type); testUAMRestartWithoutTransferContainer(false); } private void checkNMTokenForContainer(Set<NodeId> cacheToken, List<Container> containers) { for (Container container : containers) { assertTrue(cacheToken.contains(container.getNodeId())); } } }
TestWorkPreservingUnmanagedAM
java
apache__camel
components/camel-pqc/src/main/java/org/apache/camel/component/pqc/crypto/PQCDefaultMLDSAMaterial.java
{ "start": 1130, "end": 2397 }
class ____ { public static final KeyPair keyPair; public static final Signature signer; static { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastlePQCProvider()); } KeyPairGenerator generator; try { generator = prepareKeyPair(); keyPair = generator.generateKeyPair(); signer = Signature.getInstance(PQCSignatureAlgorithms.MLDSA.getAlgorithm(), PQCSignatureAlgorithms.MLDSA.getBcProvider()); } catch (Exception e) { throw new RuntimeException(e); } } protected static KeyPairGenerator prepareKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { KeyPairGenerator kpGen = KeyPairGenerator.getInstance(PQCSignatureAlgorithms.MLDSA.getAlgorithm(), PQCSignatureAlgorithms.MLDSA.getBcProvider()); kpGen.initialize(MLDSAParameterSpec.ml_dsa_65, new SecureRandom()); return kpGen; } }
PQCDefaultMLDSAMaterial
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/JacksonSerializable.java
{ "start": 337, "end": 453 }
interface ____ implementing object * closely to Jackson API, and that it is often not necessary to do * so -- if
binds
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/interfaces/hbm/allAudited/NonAuditedImplementor.java
{ "start": 217, "end": 809 }
class ____ implements SimpleInterface { private long id; private String data; private String nonAuditedImplementorData; protected NonAuditedImplementor() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getNonAuditedImplementorData() { return nonAuditedImplementorData; } public void setNonAuditedImplementorData(String implementorData) { this.nonAuditedImplementorData = implementorData; } }
NonAuditedImplementor
java
apache__camel
components/camel-rocketmq/src/main/java/org/apache/camel/component/rocketmq/RocketMQComponent.java
{ "start": 1043, "end": 8524 }
class ____ extends DefaultComponent { @Metadata(label = "producer") private String producerGroup; @Metadata(label = "consumer") private String consumerGroup; @Metadata(label = "consumer", defaultValue = "tag") private String messageSelectorType = "tag"; @Metadata(label = "consumer", defaultValue = "*") private String subscribeTags = "*"; @Metadata(label = "consumer", defaultValue = "1 = 1") private String subscribeSql = "1 = 1"; @Metadata(label = "common") private String sendTag = ""; @Metadata(label = "common", defaultValue = "localhost:9876") private String namesrvAddr = "localhost:9876"; @Metadata(label = "common") private String namespace; @Metadata(label = "common", defaultValue = "false") private boolean enableTrace = false; @Metadata(label = "common", defaultValue = "LOCAL") private String accessChannel = "LOCAL"; @Metadata(label = "producer") private String replyToTopic; @Metadata(label = "producer") private String replyToConsumerGroup; @Metadata(label = "advanced", defaultValue = "10000") private long requestTimeoutMillis = 10000L; @Metadata(label = "advanced", defaultValue = "1000") private long requestTimeoutCheckerIntervalMillis = 1000L; @Metadata(label = "producer", defaultValue = "false") private boolean waitForSendResult; @Metadata(label = "secret", secret = true) private String accessKey; @Metadata(label = "secret", secret = true) private String secretKey; @Override protected RocketMQEndpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { RocketMQEndpoint endpoint = new RocketMQEndpoint(uri, this); endpoint.setProducerGroup(getProducerGroup()); endpoint.setConsumerGroup(getConsumerGroup()); endpoint.setMessageSelectorType(getMessageSelectorType()); endpoint.setSubscribeSql(getSubscribeSql()); endpoint.setSubscribeTags(getSubscribeTags()); endpoint.setNamesrvAddr(getNamesrvAddr()); endpoint.setNamespace(getNamespace()); endpoint.setEnableTrace(isEnableTrace()); endpoint.setAccessChannel(getAccessChannel()); endpoint.setSendTag(getSendTag()); endpoint.setReplyToTopic(getReplyToTopic()); endpoint.setReplyToConsumerGroup(getReplyToConsumerGroup()); endpoint.setRequestTimeoutMillis(getRequestTimeoutMillis()); endpoint.setRequestTimeoutCheckerIntervalMillis(getRequestTimeoutCheckerIntervalMillis()); endpoint.setWaitForSendResult(isWaitForSendResult()); endpoint.setAccessKey(getAccessKey()); endpoint.setSecretKey(getSecretKey()); setProperties(endpoint, parameters); endpoint.setTopicName(remaining); return endpoint; } public String getMessageSelectorType() { return messageSelectorType; } /** * Message Selector Type, TAG or SQL [TAG] by default */ public void setMessageSelectorType(String messageSelectorType) { this.messageSelectorType = messageSelectorType; } public String getSubscribeSql() { return subscribeSql; } /** * Subscribe SQL of consumer. See * https://rocketmq.apache.org/docs/featureBehavior/07messagefilter/#attribute-based-sql-filtering for more details. */ public void setSubscribeSql(String subscribeSql) { this.subscribeSql = subscribeSql; } public String getSubscribeTags() { return subscribeTags; } /** * Subscribe tags of consumer. Multiple tags could be split by "||", such as "TagA||TagB" */ public void setSubscribeTags(String subscribeTags) { this.subscribeTags = subscribeTags; } public String getSendTag() { return sendTag; } /** * Each message would be sent with this tag. */ public void setSendTag(String sendTag) { this.sendTag = sendTag; } public String getNamesrvAddr() { return namesrvAddr; } /** * Name server address of RocketMQ cluster. */ public void setNamesrvAddr(String namesrvAddr) { this.namesrvAddr = namesrvAddr; } public String getNamespace() { return namespace; } /** * Namespace of RocketMQ cluster. You need to specify this if you are using serverless version of RocketMQ. */ public void setNamespace(String namespace) { this.namespace = namespace; } public boolean isEnableTrace() { return enableTrace; } /** * Whether to enable trace. */ public void setEnableTrace(boolean enableTrace) { this.enableTrace = enableTrace; } public String getAccessChannel() { return accessChannel; } /** * Access channel of RocketMQ cluster. LOCAL or CLOUD, [LOCAL] by default */ public void setAccessChannel(String accessChannel) { this.accessChannel = accessChannel; } public String getProducerGroup() { return producerGroup; } /** * Producer group name. */ public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } public String getConsumerGroup() { return consumerGroup; } /** * Consumer group name. */ public void setConsumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; } public String getReplyToTopic() { return replyToTopic; } /** * Topic used for receiving response when using in-out pattern. */ public void setReplyToTopic(String replyToTopic) { this.replyToTopic = replyToTopic; } public String getReplyToConsumerGroup() { return replyToConsumerGroup; } /** * Consumer group name used for receiving response. */ public void setReplyToConsumerGroup(String replyToConsumerGroup) { this.replyToConsumerGroup = replyToConsumerGroup; } public long getRequestTimeoutMillis() { return requestTimeoutMillis; } /** * Timeout milliseconds of receiving response when using in-out pattern. */ public void setRequestTimeoutMillis(long requestTimeoutMillis) { this.requestTimeoutMillis = requestTimeoutMillis; } public long getRequestTimeoutCheckerIntervalMillis() { return requestTimeoutCheckerIntervalMillis; } /** * Check interval milliseconds of request timeout. */ public void setRequestTimeoutCheckerIntervalMillis(long requestTimeoutCheckerIntervalMillis) { this.requestTimeoutCheckerIntervalMillis = requestTimeoutCheckerIntervalMillis; } public boolean isWaitForSendResult() { return waitForSendResult; } /** * Whether waiting for send result before routing to next endpoint. */ public void setWaitForSendResult(boolean waitForSendResult) { this.waitForSendResult = waitForSendResult; } public String getAccessKey() { return accessKey; } /** * Access key for RocketMQ ACL. */ public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } /** * Secret key for RocketMQ ACL. */ public void setSecretKey(String secretKey) { this.secretKey = secretKey; } }
RocketMQComponent
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/taskmanager/TaskTest.java
{ "start": 57059, "end": 57259 }
class ____ extends AbstractInvokable { public InvokableNonInstantiable(Environment environment) { super(environment); } } private static final
InvokableNonInstantiable
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/file/tfile/CompareUtils.java
{ "start": 992, "end": 1259 }
class ____ { /** * Prevent the instantiation of class. */ private CompareUtils() { // nothing } /** * A comparator to compare anything that implements {@link RawComparable} * using a customized comparator. */ public static final
CompareUtils
java
apache__camel
tooling/camel-tooling-model/src/main/java/org/apache/camel/tooling/model/ApiModel.java
{ "start": 964, "end": 2461 }
class ____ { private String name; private String description; private boolean consumerOnly; private boolean producerOnly; private final List<String> aliases = new ArrayList<>(); // lets sort api methods A..Z so they are always in the same order private final Collection<ApiMethodModel> methods = new TreeSet<>(Comparators.apiMethodModelModelComparator()); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isConsumerOnly() { return consumerOnly; } public void setConsumerOnly(boolean consumerOnly) { this.consumerOnly = consumerOnly; } public boolean isProducerOnly() { return producerOnly; } public void setProducerOnly(boolean producerOnly) { this.producerOnly = producerOnly; } public List<String> getAliases() { return aliases; } public void addAlias(String alias) { this.aliases.add(alias); } public Collection<ApiMethodModel> getMethods() { return methods; } public ApiMethodModel newMethod(String methodName) { ApiMethodModel method = new ApiMethodModel(); method.setName(methodName); this.methods.add(method); return method; } }
ApiModel
java
google__dagger
javatests/dagger/functional/builder/BuilderTest.java
{ "start": 10908, "end": 11076 }
interface ____ { OtherMiddleChild build(); Builder set(StringModule stringModule); } } @Component(modules = StringModule.class) @Singleton
Builder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/write/DynamicUpdateTests.java
{ "start": 1159, "end": 6244 }
class ____ { @Test public void testAttachableLocking(SessionFactoryScope scope) { scope.inTransaction( (session) -> { session.persist( new AttachableJob( 1, "job", "controller-1" ) ); } ); final SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); scope.inTransaction( (session) -> { final AttachableJob job1 = session.get( AttachableJob.class, 1 ); statementInspector.clear(); job1.setCode( "job-1" ); } ); assertThat( statementInspector.getSqlQueries() ).hasSize( 1 ); // the first should look like // ``` // update AttachableJob set code = ? where id = ? // ``` assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 0 ), "code" ) ).isEqualTo( 1 ); assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 0 ), "id" ) ).isEqualTo( 1 ); assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 0 ), "controller" ) ).isEqualTo( 0 ); } @Test public void testVersionedAttachableLocking(SessionFactoryScope scope) { scope.inTransaction( (session) -> { session.persist( new VersionedJob( 1, "job", "controller-1" ) ); } ); final SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); scope.inTransaction( (session) -> { final VersionedJob job1 = session.get( VersionedJob.class, 1 ); statementInspector.clear(); job1.setCode( "job-1" ); } ); assertThat( statementInspector.getSqlQueries() ).hasSize( 1 ); // the first should look like // ``` // update VersionedJob set code = ?, version = ? where id = ? and version = ? // ``` assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 0 ), "code" ) ).isEqualTo( 1 ); assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 0 ), "id" ) ).isEqualTo( 1 ); assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 0 ), "version" ) ).isEqualTo( 2 ); } @Test public void testDirtyLocking(SessionFactoryScope scope) { scope.inTransaction( (session) -> { session.persist( new DirtyJob( 1, "job", "controller-1" ) ); session.persist( new DirtyJob( 2, null, "controller-1" ) ); } ); final SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); scope.inTransaction( (session) -> { final DirtyJob job1 = session.get( DirtyJob.class, 1 ); final DirtyJob job2 = session.get( DirtyJob.class, 2 ); statementInspector.clear(); job1.setCode( "job-1" ); job2.setCode( "job-2" ); } ); assertThat( statementInspector.getSqlQueries() ).hasSize( 2 ); // the first should look like // ``` // update DirtyJob set code = ? where code = ? and id = ? // ``` assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 0 ), "code" ) ).isEqualTo( 2 ); assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 0 ), "id" ) ).isEqualTo( 1 ); // the second should look like // ``` // update DirtyJob set code = ? where code is null and id = ? // ``` assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 1 ), "code" ) ).isEqualTo( 2 ); assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 1 ), "id" ) ).isEqualTo( 1 ); } @Test public void testAllLocking(SessionFactoryScope scope) { scope.inTransaction( (session) -> { session.persist( new AllJob( 1, "job", "controller-1" ) ); session.persist( new AllJob( 2, null, "controller-1" ) ); } ); final SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); scope.inTransaction( (session) -> { final AllJob job1 = session.get( AllJob.class, 1 ); final AllJob job2 = session.get( AllJob.class, 2 ); statementInspector.clear(); job1.setCode( "job-1" ); job2.setCode( "job-2" ); } ); assertThat( statementInspector.getSqlQueries() ).hasSize( 2 ); // the first should look like // ``` // update AllJob set code = ? where code = ? and controller = ? and id = ? // ``` assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 0 ), "code" ) ).isEqualTo( 2 ); assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 0 ), "controller" ) ).isEqualTo( 1 ); assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 0 ), "id" ) ).isEqualTo( 1 ); // the second should look like // ``` // update AllJob set code = ? where code is null and controller = ? and id = ? // ``` assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 1 ), "code" ) ).isEqualTo( 2 ); assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 1 ), "controller" ) ).isEqualTo( 1 ); assertThat( StringHelper.count( statementInspector.getSqlQueries().get( 1 ), "id" ) ).isEqualTo( 1 ); } @AfterEach public void dropTestData(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Entity( name = "DirtyJob" ) @Table( name = "DirtyJob" ) @DynamicUpdate @OptimisticLocking( type = OptimisticLockType.DIRTY ) public static
DynamicUpdateTests
java
elastic__elasticsearch
modules/ingest-common/src/internalClusterTest/java/org/elasticsearch/ingest/common/IngestRestartIT.java
{ "start": 3213, "end": 18517 }
class ____ extends MockScriptPlugin { @Override protected Map<String, Function<Map<String, Object>, Object>> pluginScripts() { return Map.of("my_script", ctx -> { ctx.put("z", 0); return null; }, "throwing_script", ctx -> { throw new RuntimeException("this script always fails"); }); } } public void testFailureInConditionalProcessor() { internalCluster().ensureAtLeastNumDataNodes(1); internalCluster().startMasterOnlyNode(); final String pipelineId = "foo"; putJsonPipeline(pipelineId, Strings.format(""" { "processors": [ { "set": { "field": "any_field", "value": "any_value" } }, { "set": { "if": { "lang": "%s", "source": "throwing_script" }, "field": "any_field2", "value": "any_value2" } } ] }""", MockScriptEngine.NAME)); Exception e = expectThrows( Exception.class, () -> prepareIndex("index").setId("1") .setSource("x", 0) .setPipeline(pipelineId) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .get() ); assertTrue(e.getMessage().contains("this script always fails")); NodesStatsResponse r = clusterAdmin().prepareNodesStats(internalCluster().getNodeNames()).setIngest(true).get(); int nodeCount = r.getNodes().size(); for (int k = 0; k < nodeCount; k++) { List<IngestStats.ProcessorStat> stats = r.getNodes() .get(k) .getIngestStats() .processorStats() .get(ProjectId.DEFAULT) .get(pipelineId); for (IngestStats.ProcessorStat st : stats) { assertThat(st.stats().ingestCurrent(), greaterThanOrEqualTo(0L)); } } } public void testScriptDisabled() throws Exception { String pipelineIdWithoutScript = randomAlphaOfLengthBetween(5, 10); String pipelineIdWithScript = pipelineIdWithoutScript + "_script"; internalCluster().startNode(); putJsonPipeline(pipelineIdWithScript, Strings.format(""" { "processors": [ { "script": { "lang": "%s", "source": "my_script" } } ] }""", MockScriptEngine.NAME)); putJsonPipeline(pipelineIdWithoutScript, """ { "processors": [ { "set": { "field": "y", "value": 0 } } ] }"""); Consumer<String> checkPipelineExists = (id) -> assertThat(getPipelines(id).pipelines().get(0).getId(), equalTo(id)); checkPipelineExists.accept(pipelineIdWithScript); checkPipelineExists.accept(pipelineIdWithoutScript); internalCluster().restartNode(internalCluster().getMasterName(), new InternalTestCluster.RestartCallback() { @Override public Settings onNodeStopped(String nodeName) { return Settings.builder().put("script.allowed_types", "none").build(); } }); checkPipelineExists.accept(pipelineIdWithoutScript); checkPipelineExists.accept(pipelineIdWithScript); prepareIndex("index").setId("1") .setSource("x", 0) .setPipeline(pipelineIdWithoutScript) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .get(); IllegalStateException exception = expectThrows( IllegalStateException.class, () -> prepareIndex("index").setId("2") .setSource("x", 0) .setPipeline(pipelineIdWithScript) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .get() ); assertThat( exception.getMessage(), equalTo( "pipeline with id [" + pipelineIdWithScript + "] could not be loaded, caused by " + "[org.elasticsearch.ElasticsearchParseException: Error updating pipeline with id [" + pipelineIdWithScript + "]; " + "org.elasticsearch.ElasticsearchException: java.lang.IllegalArgumentException: cannot execute [inline] scripts; " + "java.lang.IllegalArgumentException: cannot execute [inline] scripts]" ) ); Map<String, Object> source = client().prepareGet("index", "1").get().getSource(); assertThat(source.get("x"), equalTo(0)); assertThat(source.get("y"), equalTo(0)); } public void testPipelineWithScriptProcessorThatHasStoredScript() throws Exception { internalCluster().startNode(); putJsonStoredScript("1", Strings.format(""" {"script": {"lang": "%s", "source": "my_script"} } """, MockScriptEngine.NAME)); putJsonPipeline("_id", """ { "processors" : [ {"set" : {"field": "y", "value": 0}}, {"script" : {"id": "1"}} ] }"""); prepareIndex("index").setId("1").setSource("x", 0).setPipeline("_id").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); Map<String, Object> source = client().prepareGet("index", "1").get().getSource(); assertThat(source.get("x"), equalTo(0)); assertThat(source.get("y"), equalTo(0)); assertThat(source.get("z"), equalTo(0)); // Prior to making this ScriptService implement ClusterStateApplier instead of ClusterStateListener, // pipelines with a script processor failed to load causing these pipelines and pipelines that were // supposed to load after these pipelines to not be available during ingestion, which then causes // the next index request in this test to fail. internalCluster().fullRestart(); ensureYellow("index"); prepareIndex("index").setId("2").setSource("x", 0).setPipeline("_id").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); source = client().prepareGet("index", "2").get().getSource(); assertThat(source.get("x"), equalTo(0)); assertThat(source.get("y"), equalTo(0)); assertThat(source.get("z"), equalTo(0)); } public void testWithDedicatedIngestNode() throws Exception { String node = internalCluster().startNode(); String ingestNode = internalCluster().startNode(onlyRole(DiscoveryNodeRole.INGEST_ROLE)); putJsonPipeline("_id", """ { "processors" : [ {"set" : {"field": "y", "value": 0}} ] }"""); prepareIndex("index").setId("1").setSource("x", 0).setPipeline("_id").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); Map<String, Object> source = client().prepareGet("index", "1").get().getSource(); assertThat(source.get("x"), equalTo(0)); assertThat(source.get("y"), equalTo(0)); logger.info("Stopping"); internalCluster().restartNode(node, new InternalTestCluster.RestartCallback()); client(ingestNode).prepareIndex("index") .setId("2") .setSource("x", 0) .setPipeline("_id") .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .get(); source = client(ingestNode).prepareGet("index", "2").get().getSource(); assertThat(source.get("x"), equalTo(0)); assertThat(source.get("y"), equalTo(0)); } public void testDefaultPipelineWaitForClusterStateRecovered() throws Exception { internalCluster().startNode(); putJsonPipeline("test_pipeline", """ { "processors" : [ { "set": { "field": "value", "value": 42 } } ] }"""); final TimeValue timeout = TimeValue.timeValueSeconds(10); client().admin().indices().preparePutTemplate("pipeline_template").setPatterns(Collections.singletonList("*")).setSettings(""" { "index" : { "default_pipeline" : "test_pipeline" } } """, XContentType.JSON).get(timeout); internalCluster().fullRestart(new InternalTestCluster.RestartCallback() { @Override public Settings onNodeStopped(String nodeName) { return Settings.builder().put(GatewayService.RECOVER_AFTER_DATA_NODES_SETTING.getKey(), "2").build(); } @Override public boolean validateClusterForming() { return randomBoolean(); } }); // this one should fail assertThat( expectThrows( ClusterBlockException.class, () -> prepareIndex("index").setId("fails") .setSource("x", 1) .setTimeout(TimeValue.timeValueMillis(100)) // 100ms, to fail quickly .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .get(timeout) ).getMessage(), equalTo("blocked by: [SERVICE_UNAVAILABLE/1/state not recovered / initialized];") ); // but this one should pass since it has a longer timeout final PlainActionFuture<DocWriteResponse> future = new PlainActionFuture<>(); prepareIndex("index").setId("passes1") .setSource("x", 2) .setTimeout(TimeValue.timeValueSeconds(60)) // wait for second node to start in below .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .execute(future); // so the cluster state can be recovered internalCluster().startNode(Settings.builder().put(GatewayService.RECOVER_AFTER_DATA_NODES_SETTING.getKey(), "1")); ensureYellow("index"); final DocWriteResponse indexResponse = future.actionGet(timeout); assertThat(indexResponse.status(), equalTo(RestStatus.CREATED)); assertThat(indexResponse.getResult(), equalTo(DocWriteResponse.Result.CREATED)); prepareIndex("index").setId("passes2").setSource("x", 3).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); // successfully indexed documents should have the value field set by the pipeline Map<String, Object> source = client().prepareGet("index", "passes1").get(timeout).getSource(); assertThat(source.get("x"), equalTo(2)); assertThat(source.get("value"), equalTo(42)); source = client().prepareGet("index", "passes2").get(timeout).getSource(); assertThat(source.get("x"), equalTo(3)); assertThat(source.get("value"), equalTo(42)); // and make sure this failed doc didn't get through source = client().prepareGet("index", "fails").get(timeout).getSource(); assertNull(source); } /** * This test is for confirming that forwarded bulk requests do not use system_write thread pool * for non-system indexes. Before this fix, we were using system_write thread pool for all forwarded * bulk requests causing the system_write thread pool to get overloaded. */ public void testForwardBulkWithSystemWritePoolDisabled() throws Exception { // Create a node with master only role and a node with ingest role final String masterOnlyNode = internalCluster().startMasterOnlyNode(); final String ingestNode = internalCluster().startNode(); ensureStableCluster(2); // Create Bulk Request createIndex("index"); putJsonPipeline("_id", """ { "processors" : [ {"set" : {"field": "y", "value": 0}} ] }"""); int numRequests = scaledRandomIntBetween(32, 128); BulkRequest bulkRequest = new BulkRequest(); BulkResponse response; for (int i = 0; i < numRequests; i++) { IndexRequest indexRequest = new IndexRequest("index").id(Integer.toString(i)).setPipeline("_id"); indexRequest.source(Requests.INDEX_CONTENT_TYPE, "x", 1); bulkRequest.add(indexRequest); } assertThat(numRequests, equalTo(bulkRequest.requests().size())); // Block system_write thread pool on the ingest node final ThreadPool ingestNodeThreadPool = internalCluster().getInstance(ThreadPool.class, ingestNode); final var blockingLatch = new CountDownLatch(1); try { blockSystemWriteThreadPool(blockingLatch, ingestNodeThreadPool); // Send bulk request to master only node, so it will forward it to the ingest node. response = safeGet(client(masterOnlyNode).bulk(bulkRequest)); } finally { blockingLatch.countDown(); } // Make sure the requests are processed (even though we blocked system_write thread pool above). assertThat(response.getItems().length, equalTo(numRequests)); assertFalse(response.hasFailures()); // Check Node Ingest stats NodesStatsResponse nodesStatsResponse = clusterAdmin().nodesStats(new NodesStatsRequest(ingestNode).addMetric(INGEST)).actionGet(); assertThat(nodesStatsResponse.getNodes().size(), equalTo(1)); NodeStats stats = nodesStatsResponse.getNodes().get(0); assertThat(stats.getIngestStats().totalStats().ingestCount(), equalTo((long) numRequests)); assertThat(stats.getIngestStats().totalStats().ingestFailedCount(), equalTo(0L)); final var pipelineStats = stats.getIngestStats().pipelineStats().get(0); assertThat(pipelineStats.pipelineId(), equalTo("_id")); assertThat(pipelineStats.stats().ingestCount(), equalTo((long) numRequests)); MultiGetResponse docListResponse = safeGet( client().prepareMultiGet().addIds("index", IntStream.range(0, numRequests).mapToObj(String::valueOf).toList()).execute() ); assertThat(docListResponse.getResponses().length, equalTo(numRequests)); Map<String, Object> document; for (int i = 0; i < numRequests; i++) { document = docListResponse.getResponses()[i].getResponse().getSourceAsMap(); assertThat(document.get("y"), equalTo(0)); } } private void blockSystemWriteThreadPool(CountDownLatch blockingLatch, ThreadPool threadPool) { assertThat(blockingLatch.getCount(), greaterThan(0L)); final var executor = threadPool.executor(ThreadPool.Names.SYSTEM_WRITE_COORDINATION); // Add tasks repeatedly until we get an EsRejectedExecutionException which indicates that the threadpool and its queue are full. expectThrows(EsRejectedExecutionException.class, () -> { // noinspection InfiniteLoopStatement while (true) { executor.execute(() -> safeAwait(blockingLatch)); } }); } }
CustomScriptPlugin
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/multipart/MultipartCleanupTest.java
{ "start": 2717, "end": 2940 }
interface ____ { @POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Path("/multipart") String send(Form collectorDto); } @Path("/multipart") @ApplicationScoped public static
Client
java
spring-projects__spring-boot
module/spring-boot-elasticsearch/src/test/java/org/springframework/boot/elasticsearch/autoconfigure/ElasticsearchClientAutoConfigurationTests.java
{ "start": 7247, "end": 7420 }
class ____ { @Bean ElasticsearchTransport customElasticsearchTransport(JsonpMapper mapper) { return mock(ElasticsearchTransport.class); } } }
TransportConfiguration
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/AbstractTypeNamesTest.java
{ "start": 643, "end": 740 }
class ____ extends DatabindTestUtil { @JsonTypeName("Employee") public
AbstractTypeNamesTest
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/HourlySchedule.java
{ "start": 2574, "end": 5645 }
class ____ implements Schedule.Parser<HourlySchedule> { static final ParseField MINUTE_FIELD = new ParseField("minute"); @Override public String type() { return TYPE; } @Override public HourlySchedule parse(XContentParser parser) throws IOException { List<Integer> minutes = new ArrayList<>(); String currentFieldName = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (currentFieldName == null) { throw new ElasticsearchParseException("could not parse [{}] schedule. unexpected token [{}]", TYPE, token); } else if (MINUTE_FIELD.match(currentFieldName, parser.getDeprecationHandler())) { if (token.isValue()) { try { minutes.add(DayTimes.parseMinuteValue(parser, token)); } catch (ElasticsearchParseException pe) { throw new ElasticsearchParseException( "could not parse [{}] schedule. invalid value for [{}]", pe, TYPE, currentFieldName ); } } else if (token == XContentParser.Token.START_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { try { minutes.add(DayTimes.parseMinuteValue(parser, token)); } catch (ElasticsearchParseException pe) { throw new ElasticsearchParseException( "could not parse [{}] schedule. invalid value for [{}]", pe, TYPE, currentFieldName ); } } } else { throw new ElasticsearchParseException( "could not parse [{}] schedule. invalid value for [{}]. " + "expected either string/value or an array of string/number values, but found [{}]", TYPE, currentFieldName, token ); } } else { throw new ElasticsearchParseException("could not parse [{}] schedule. unexpected field [{}]", TYPE, currentFieldName); } } return minutes.isEmpty() ? new HourlySchedule() : new HourlySchedule(CollectionUtils.toArray(minutes)); } } public static
Parser
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/resource/ConstantDelayUnitTests.java
{ "start": 388, "end": 1135 }
class ____ { @Test void shouldNotCreateIfDelayIsNegative() { assertThatThrownBy(() -> Delay.constant(-1, TimeUnit.MILLISECONDS)).isInstanceOf(IllegalArgumentException.class); } @Test void shouldCreateZeroDelay() { Delay delay = Delay.constant(0, TimeUnit.MILLISECONDS); assertThat(delay.createDelay(0)).isEqualTo(Duration.ZERO); assertThat(delay.createDelay(5)).isEqualTo(Duration.ZERO); } @Test void shouldCreateConstantDelay() { Delay delay = Delay.constant(100, TimeUnit.MILLISECONDS); assertThat(delay.createDelay(0)).isEqualTo(Duration.ofMillis(100)); assertThat(delay.createDelay(5)).isEqualTo(Duration.ofMillis(100)); } }
ConstantDelayUnitTests
java
elastic__elasticsearch
build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/info/GitInfoValueSource.java
{ "start": 282, "end": 540 }
class ____ implements ValueSource<GitInfo, GitInfoValueSource.Parameters> { @Nullable @Override public GitInfo obtain() { File path = getParameters().getPath().get(); return GitInfo.gitInfo(path); } public
GitInfoValueSource
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/profile/IfBuildProfileTest.java
{ "start": 2962, "end": 3050 }
interface ____ { String foo(); } @IfBuildProfile("dev") static
FooBean
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/session/SqlSession.java
{ "start": 947, "end": 1062 }
interface ____ can execute commands, get mappers and * manage transactions. * * @author Clinton Begin */ public
you
java
apache__maven
compat/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/ArtifactDescriptorReaderDelegate.java
{ "start": 2256, "end": 6186 }
class ____ { public void populateResult(RepositorySystemSession session, ArtifactDescriptorResult result, Model model) { ArtifactTypeRegistry stereotypes = session.getArtifactTypeRegistry(); for (Repository r : model.getRepositories()) { result.addRepository(ArtifactDescriptorUtils.toRemoteRepository(r)); } for (org.apache.maven.model.Dependency dependency : model.getDependencies()) { result.addDependency(convert(dependency, stereotypes)); } DependencyManagement mgmt = model.getDependencyManagement(); if (mgmt != null) { for (org.apache.maven.model.Dependency dependency : mgmt.getDependencies()) { result.addManagedDependency(convert(dependency, stereotypes)); } } Map<String, Object> properties = new LinkedHashMap<>(); Prerequisites prerequisites = model.getPrerequisites(); if (prerequisites != null) { properties.put("prerequisites.maven", prerequisites.getMaven()); } List<License> licenses = model.getLicenses(); properties.put("license.count", licenses.size()); for (int i = 0; i < licenses.size(); i++) { License license = licenses.get(i); properties.put("license." + i + ".name", license.getName()); properties.put("license." + i + ".url", license.getUrl()); properties.put("license." + i + ".comments", license.getComments()); properties.put("license." + i + ".distribution", license.getDistribution()); } result.setProperties(properties); setArtifactProperties(result, model); } private Dependency convert(org.apache.maven.model.Dependency dependency, ArtifactTypeRegistry stereotypes) { ArtifactType stereotype = stereotypes.get(dependency.getType()); if (stereotype == null) { stereotype = new DefaultType(dependency.getType(), Language.NONE, dependency.getType(), null, false); } boolean system = dependency.getSystemPath() != null && !dependency.getSystemPath().isEmpty(); Map<String, String> props = null; if (system) { props = Collections.singletonMap(MavenArtifactProperties.LOCAL_PATH, dependency.getSystemPath()); } Artifact artifact = new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), null, dependency.getVersion(), props, stereotype); List<Exclusion> exclusions = new ArrayList<>(dependency.getExclusions().size()); for (org.apache.maven.model.Exclusion exclusion : dependency.getExclusions()) { exclusions.add(convert(exclusion)); } return new Dependency( artifact, dependency.getScope(), dependency.getOptional() != null ? dependency.isOptional() : null, exclusions); } private Exclusion convert(org.apache.maven.model.Exclusion exclusion) { return new Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*"); } private void setArtifactProperties(ArtifactDescriptorResult result, Model model) { String downloadUrl = null; DistributionManagement distMgmt = model.getDistributionManagement(); if (distMgmt != null) { downloadUrl = distMgmt.getDownloadUrl(); } if (downloadUrl != null && !downloadUrl.isEmpty()) { Artifact artifact = result.getArtifact(); Map<String, String> props = new HashMap<>(artifact.getProperties()); props.put(ArtifactProperties.DOWNLOAD_URL, downloadUrl); result.setArtifact(artifact.setProperties(props)); } } }
ArtifactDescriptorReaderDelegate
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/Assertions_assertThat_with_OptionalDouble_Test.java
{ "start": 949, "end": 1220 }
class ____ { private OptionalDouble actual; @BeforeEach void before() { actual = OptionalDouble.of(10.0); } @Test void should_create_Assert() { assertThat(Assertions.assertThat(actual)).isNotNull(); } }
Assertions_assertThat_with_OptionalDouble_Test
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/core/Observable.java
{ "start": 4466, "end": 8603 }
class ____<@NonNull T> implements ObservableSource<T> { /** * Mirrors the one {@link ObservableSource} in an {@link Iterable} of several {@code ObservableSource}s that first either emits an item or sends * a termination notification. * <p> * <img width="640" height="505" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.amb.png" alt=""> * <p> * When one of the {@code ObservableSource}s signal an item or terminates first, all subscriptions to the other * {@code ObservableSource}s are disposed. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd> * If any of the losing {@code ObservableSource}s signals an error, the error is routed to the global * error handler via {@link RxJavaPlugins#onError(Throwable)}. * </dd> * </dl> * * @param <T> the common element type * @param sources * an {@code Iterable} of {@code ObservableSource} sources competing to react first. A subscription to each source will * occur in the same order as in the {@code Iterable}. * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> amb(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources) { Objects.requireNonNull(sources, "sources is null"); return RxJavaPlugins.onAssembly(new ObservableAmb<>(null, sources)); } /** * Mirrors the one {@link ObservableSource} in an array of several {@code ObservableSource}s that first either emits an item or sends * a termination notification. * <p> * <img width="640" height="505" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.ambArray.png" alt=""> * <p> * When one of the {@code ObservableSource}s signal an item or terminates first, all subscriptions to the other * {@code ObservableSource}s are disposed. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ambArray} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd> * If any of the losing {@code ObservableSource}s signals an error, the error is routed to the global * error handler via {@link RxJavaPlugins#onError(Throwable)}. * </dd> * </dl> * * @param <T> the common element type * @param sources * an array of {@code ObservableSource} sources competing to react first. A subscription to each source will * occur in the same order as in the array. * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ @SuppressWarnings("unchecked") @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SafeVarargs public static <@NonNull T> Observable<T> ambArray(@NonNull ObservableSource<? extends T>... sources) { Objects.requireNonNull(sources, "sources is null"); int len = sources.length; if (len == 0) { return empty(); } if (len == 1) { return (Observable<T>)wrap(sources[0]); } return RxJavaPlugins.onAssembly(new ObservableAmb<>(sources, null)); } /** * Returns the default 'island' size or capacity-increment hint for unbounded buffers. * <p>Delegates to {@link Flowable#bufferSize} but is public for convenience. * <p>The value can be overridden via system parameter {@code rx3.buffer-size} * <em>before</em> the {@link Flowable}
Observable
java
elastic__elasticsearch
x-pack/plugin/esql/qa/testFixtures/src/main/java/org/elasticsearch/xpack/esql/generator/command/pipe/EnrichGenerator.java
{ "start": 684, "end": 2272 }
class ____ implements CommandGenerator { public static final String ENRICH = "enrich"; public static final CommandGenerator INSTANCE = new EnrichGenerator(); @Override public CommandDescription generate( List<CommandDescription> previousCommands, List<Column> previousOutput, QuerySchema schema, QueryExecutor executor ) { String field = EsqlQueryGenerator.randomKeywordField(previousOutput); if (field == null || schema.enrichPolicies().isEmpty()) { return EMPTY_DESCRIPTION; } // TODO add WITH String cmdString = " | enrich " + randomFrom(EsqlQueryGenerator.policiesOnKeyword(schema.enrichPolicies())).policyName() + " on " + field; return new CommandDescription(ENRICH, this, cmdString, Map.of()); } @Override public ValidationResult validateOutput( List<CommandDescription> previousCommands, CommandDescription commandDescription, List<Column> previousColumns, List<List<Object>> previousOutput, List<Column> columns, List<List<Object>> output ) { if (commandDescription == EMPTY_DESCRIPTION) { return VALIDATION_OK; } if (previousColumns.size() > columns.size()) { return new ValidationResult(false, "Expecting at least [" + previousColumns.size() + "] columns, got [" + columns.size() + "]"); } return CommandGenerator.expectSameRowCount(previousCommands, previousOutput, output); } }
EnrichGenerator
java
apache__camel
test-infra/camel-test-infra-aws-common/src/main/java/org/apache/camel/test/infra/aws/common/AWSConfigs.java
{ "start": 865, "end": 1217 }
class ____ { public static final String ACCESS_KEY = "aws.access.key"; public static final String SECRET_KEY = "aws.secret.key"; public static final String REGION = "aws.region"; public static final String AMAZON_AWS_HOST = "aws.host"; public static final String PROTOCOL = "aws.protocol"; private AWSConfigs() { } }
AWSConfigs
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolutionIntegrationTests.java
{ "start": 5115, "end": 5544 }
class ____ extends AbstractWebConfig { @Bean public FreeMarkerViewResolver freeMarkerViewResolver() { return new FreeMarkerViewResolver("", ".ftl"); } @Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPath("/WEB-INF/"); return configurer; } } @Configuration static
ExistingViewResolverConfig
java
netty__netty
example/src/main/java/io/netty/example/telnet/TelnetServerHandler.java
{ "start": 1018, "end": 2573 }
class ____ extends SimpleChannelInboundHandler<String> { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // Send greeting for a new connection. ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n"); ctx.write("It is " + new Date() + " now.\r\n"); ctx.flush(); } @Override public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception { // Generate and write a response. String response; boolean close = false; if (request.isEmpty()) { response = "Please type something.\r\n"; } else if ("bye".equals(request.toLowerCase())) { response = "Have a good day!\r\n"; close = true; } else { response = "Did you say '" + request + "'?\r\n"; } // We do not need to write a ChannelBuffer here. // We know the encoder inserted at TelnetPipelineFactory will do the conversion. ChannelFuture future = ctx.write(response); // Close the connection after sending 'Have a good day!' // if the client has sent 'bye'. if (close) { future.addListener(ChannelFutureListener.CLOSE); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
TelnetServerHandler
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/appender/AsyncAppender.java
{ "start": 3187, "end": 13327 }
class ____ extends AbstractAppender { private static final int DEFAULT_QUEUE_SIZE = 1024; private final BlockingQueue<LogEvent> queue; private final int queueSize; private final boolean blocking; private final long shutdownTimeout; private final Configuration config; private final AppenderRef[] appenderRefs; private final String errorRef; private final boolean includeLocation; private AppenderControl errorAppender; private AsyncAppenderEventDispatcher dispatcher; private AsyncQueueFullPolicy asyncQueueFullPolicy; private AsyncAppender( final String name, final Filter filter, final AppenderRef[] appenderRefs, final String errorRef, final int queueSize, final boolean blocking, final boolean ignoreExceptions, final long shutdownTimeout, final Configuration config, final boolean includeLocation, final BlockingQueueFactory<LogEvent> blockingQueueFactory, final Property[] properties) { super(name, filter, null, ignoreExceptions, properties); this.queue = blockingQueueFactory.create(queueSize); this.queueSize = queueSize; this.blocking = blocking; this.shutdownTimeout = shutdownTimeout; this.config = config; this.appenderRefs = appenderRefs; this.errorRef = errorRef; this.includeLocation = includeLocation; } @Override public void start() { final Map<String, Appender> map = config.getAppenders(); final List<AppenderControl> appenders = new ArrayList<>(); for (final AppenderRef appenderRef : appenderRefs) { final Appender appender = map.get(appenderRef.getRef()); if (appender != null) { appenders.add(new AppenderControl(appender, appenderRef.getLevel(), appenderRef.getFilter())); } else { LOGGER.error("No appender named {} was configured", appenderRef); } } if (errorRef != null) { final Appender appender = map.get(errorRef); if (appender != null) { errorAppender = new AppenderControl(appender, null, null); } else { LOGGER.error("Unable to set up error Appender. No appender named {} was configured", errorRef); } } if (appenders.size() > 0) { dispatcher = new AsyncAppenderEventDispatcher(getName(), errorAppender, appenders, queue); } else if (errorRef == null) { throw new ConfigurationException("No appenders are available for AsyncAppender " + getName()); } asyncQueueFullPolicy = AsyncQueueFullPolicyFactory.create(); dispatcher.start(); super.start(); } @Override public boolean stop(final long timeout, final TimeUnit timeUnit) { setStopping(); super.stop(timeout, timeUnit, false); LOGGER.trace("AsyncAppender stopping. Queue still has {} events.", queue.size()); try { dispatcher.stop(shutdownTimeout); } catch (final InterruptedException ignored) { // Restore the interrupted flag cleared when the exception is caught. Thread.currentThread().interrupt(); LOGGER.warn("Interrupted while stopping AsyncAppender {}", getName()); } LOGGER.trace("AsyncAppender stopped. Queue has {} events.", queue.size()); if (DiscardingAsyncQueueFullPolicy.getDiscardCount(asyncQueueFullPolicy) > 0) { LOGGER.trace( "AsyncAppender: {} discarded {} events.", asyncQueueFullPolicy, DiscardingAsyncQueueFullPolicy.getDiscardCount(asyncQueueFullPolicy)); } setStopped(); return true; } /** * Actual writing occurs here. * * @param logEvent The LogEvent. */ @Override public void append(final LogEvent logEvent) { if (!isStarted()) { throw new IllegalStateException("AsyncAppender " + getName() + " is not active"); } final Log4jLogEvent memento = Log4jLogEvent.createMemento(logEvent, includeLocation); InternalAsyncUtil.makeMessageImmutable(logEvent.getMessage()); if (!transfer(memento)) { if (blocking) { if (AbstractLogger.getRecursionDepth() > 1) { // LOG4J2-1518, LOG4J2-2031 // If queue is full AND we are in a recursive call, call appender directly to prevent deadlock AsyncQueueFullMessageUtil.logWarningToStatusLogger(); logMessageInCurrentThread(logEvent); } else { // delegate to the event router (which may discard, enqueue and block, or log in current thread) final EventRoute route = asyncQueueFullPolicy.getRoute(dispatcher.getId(), memento.getLevel()); route.logMessage(this, memento); } } else { error("Appender " + getName() + " is unable to write primary appenders. queue is full"); logToErrorAppenderIfNecessary(false, memento); } } } private boolean transfer(final LogEvent memento) { return queue instanceof TransferQueue ? ((TransferQueue<LogEvent>) queue).tryTransfer(memento) : queue.offer(memento); } /** * FOR INTERNAL USE ONLY. * * @param logEvent the event to log */ public void logMessageInCurrentThread(final LogEvent logEvent) { logEvent.setEndOfBatch(queue.isEmpty()); dispatcher.dispatch(logEvent); } /** * FOR INTERNAL USE ONLY. * * @param logEvent the event to log */ public void logMessageInBackgroundThread(final LogEvent logEvent) { try { // wait for free slots in the queue queue.put(logEvent); } catch (final InterruptedException ignored) { final boolean appendSuccessful = handleInterruptedException(logEvent); logToErrorAppenderIfNecessary(appendSuccessful, logEvent); } } // LOG4J2-1049: Some applications use Thread.interrupt() to send // messages between application threads. This does not necessarily // mean that the queue is full. To prevent dropping a log message, // quickly try to offer the event to the queue again. // (Yes, this means there is a possibility the same event is logged twice.) // // Finally, catching the InterruptedException means the // interrupted flag has been cleared on the current thread. // This may interfere with the application's expectation of // being interrupted, so when we are done, we set the interrupted // flag again. private boolean handleInterruptedException(final LogEvent memento) { final boolean appendSuccessful = queue.offer(memento); if (!appendSuccessful) { LOGGER.warn("Interrupted while waiting for a free slot in the AsyncAppender LogEvent-queue {}", getName()); } // set the interrupted flag again. Thread.currentThread().interrupt(); return appendSuccessful; } private void logToErrorAppenderIfNecessary(final boolean appendSuccessful, final LogEvent logEvent) { if (!appendSuccessful && errorAppender != null) { errorAppender.callAppender(logEvent); } } /** * Create an AsyncAppender. This method is retained for backwards compatibility. New code should use the * {@link Builder} instead. This factory will use {@link ArrayBlockingQueueFactory} by default as was the behavior * pre-2.7. * * @param appenderRefs The Appenders to reference. * @param errorRef An optional Appender to write to if the queue is full or other errors occur. * @param blocking True if the Appender should wait when the queue is full. The default is true. * @param shutdownTimeout How many milliseconds the Appender should wait to flush outstanding log events * in the queue on shutdown. The default is zero which means to wait forever. * @param size The size of the event queue. The default is 128. * @param name The name of the Appender. * @param includeLocation whether to include location information. The default is false. * @param filter The Filter or null. * @param config The Configuration. * @param ignoreExceptions If {@code "true"} (default) exceptions encountered when appending events are logged; * otherwise they are propagated to the caller. * @return The AsyncAppender. * @deprecated use {@link Builder} instead */ @Deprecated public static AsyncAppender createAppender( final AppenderRef[] appenderRefs, final String errorRef, final boolean blocking, final long shutdownTimeout, final int size, final String name, final boolean includeLocation, final Filter filter, final Configuration config, final boolean ignoreExceptions) { if (name == null) { LOGGER.error("No name provided for AsyncAppender"); return null; } if (appenderRefs == null) { LOGGER.error("No appender references provided to AsyncAppender {}", name); } return new AsyncAppender( name, filter, appenderRefs, errorRef, size, blocking, ignoreExceptions, shutdownTimeout, config, includeLocation, new ArrayBlockingQueueFactory<LogEvent>(), null); } @PluginBuilderFactory public static Builder newBuilder() { return new Builder(); } public static
AsyncAppender
java
spring-projects__spring-boot
module/spring-boot-validation/src/main/java/org/springframework/boot/validation/autoconfigure/ValidatorAdapter.java
{ "start": 1759, "end": 1962 }
interface ____ does * not implement the JSR-303 {@code jakarta.validator.Validator} interface. * * @author Stephane Nicoll * @author Phillip Webb * @author Zisis Pavloudis * @since 4.0.0 */ public
but
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ErrorMessageFactory.java
{ "start": 997, "end": 1584 }
interface ____ { /** * Creates a new error message as a result of a failed assertion. * @param description the description of the failed assertion. * @param representation the representation used * @return the created error message. */ String create(Description description, Representation representation); /** * {@inheritDoc} */ default String create(Description d) { return create(d, CONFIGURATION_PROVIDER.representation()); } /** * {@inheritDoc} */ default String create() { return create(emptyDescription()); } }
ErrorMessageFactory
java
apache__flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/experimental/SocketStreamIterator.java
{ "start": 1807, "end": 7170 }
class ____<T> implements Iterator<T> { /** Server socket to listen at. */ private final ServerSocket socket; /** Serializer to deserialize stream. */ private final TypeSerializer<T> serializer; /** Set by the same thread that reads it. */ private DataInputViewStreamWrapper inStream; /** Next element, handover from hasNext() to next(). */ private T next; /** The socket for the specific stream. */ private Socket connectedSocket; /** Async error, for example by the executor of the program that produces the stream. */ private volatile Throwable error; /** * Creates an iterator that returns the data from a socket stream with automatic port and bind * address. * * @param serializer serializer used for deserializing incoming records * @throws IOException thrown if socket cannot be opened */ public SocketStreamIterator(TypeSerializer<T> serializer) throws IOException { this(0, null, serializer); } /** * Creates an iterator that returns the data from a socket stream with custom port and bind * address. * * @param port port for the socket connection (0 means automatic port selection) * @param address address for the socket connection * @param serializer serializer used for deserializing incoming records * @throws IOException thrown if socket cannot be opened */ public SocketStreamIterator(int port, InetAddress address, TypeSerializer<T> serializer) throws IOException { this.serializer = serializer; try { socket = new ServerSocket(port, 1, address); } catch (IOException e) { throw new RuntimeException("Could not open socket to receive back stream results"); } } // ------------------------------------------------------------------------ // properties // ------------------------------------------------------------------------ /** * Returns the port on which the iterator is getting the data. (Used internally.) * * @return The port */ public int getPort() { return socket.getLocalPort(); } public InetAddress getBindAddress() { return socket.getInetAddress(); } public void close() { if (connectedSocket != null) { try { connectedSocket.close(); } catch (Throwable ignored) { } } try { socket.close(); } catch (Throwable ignored) { } } // ------------------------------------------------------------------------ // iterator semantics // ------------------------------------------------------------------------ /** * Returns true if the DataStream has more elements. (Note: blocks if there will be more * elements, but they are not available yet.) * * @return true if the DataStream has more elements */ @Override public boolean hasNext() { if (next == null) { try { next = readNextFromStream(); } catch (Exception e) { throw new RuntimeException("Failed to receive next element: " + e.getMessage(), e); } } return next != null; } /** * Returns the next element of the DataStream. (Blocks if it is not available yet.) * * @return The element * @throws NoSuchElementException if the stream has already ended */ @Override public T next() { if (hasNext()) { T current = next; next = null; return current; } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException(); } private T readNextFromStream() throws Exception { try { if (inStream == null) { connectedSocket = NetUtils.acceptWithoutTimeout(socket); inStream = new DataInputViewStreamWrapper(connectedSocket.getInputStream()); } return serializer.deserialize(inStream); } catch (EOFException e) { try { connectedSocket.close(); } catch (Throwable ignored) { } try { socket.close(); } catch (Throwable ignored) { } return null; } catch (Exception e) { if (error == null) { throw e; } else { // throw the root cause error throw new Exception("Receiving stream failed: " + error.getMessage(), error); } } } // ------------------------------------------------------------------------ // errors // ------------------------------------------------------------------------ public void notifyOfError(Throwable error) { if (error != null && this.error == null) { this.error = error; // this should wake up any blocking calls try { connectedSocket.close(); } catch (Throwable ignored) { } try { socket.close(); } catch (Throwable ignored) { } } } }
SocketStreamIterator
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest5.java
{ "start": 144, "end": 494 }
class ____ extends TestCase { public void test_jsonField() throws Exception { VO vo = new VO(); vo.setID(123); String text = JSON.toJSONString(vo); Assert.assertEquals("{\"iD\":123}", text); Assert.assertEquals(123, JSON.parseObject(text, VO.class).getID()); } public static
JSONFieldTest5
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng6223FindBasedir.java
{ "start": 1242, "end": 4111 }
class ____ extends AbstractMavenIntegrationTestCase { /** * check that <code>path/to/.mvn/</code> is found when path to POM set by <code>--file path/to/dir</code> * * @throws Exception in case of failure */ @Test public void testMvnFileLongOptionToDir() throws Exception { runCoreExtensionWithOptionToDir("--file", null); } /** * check that <code>path/to/.mvn/</code> is found when path to POM set by <code>-f path/to/dir</code> * * @throws Exception in case of failure */ @Test public void testMvnFileShortOptionToDir() throws Exception { runCoreExtensionWithOptionToDir("-f", null); } /** * check that <code>path/to/.mvn/</code> is found when path to POM set by <code>--file path/to/module</code> * * @throws Exception in case of failure */ @Test public void testMvnFileLongOptionModuleToDir() throws Exception { runCoreExtensionWithOptionToDir("--file", "module"); } /** * check that <code>path/to/.mvn/</code> is found when path to POM set by <code>-f path/to/module</code> * * @throws Exception in case of failure */ @Test public void testMvnFileShortOptionModuleToDir() throws Exception { runCoreExtensionWithOptionToDir("-f", "module"); } private void runCoreExtensionWithOptionToDir(String option, String subdir) throws Exception { runCoreExtensionWithOption(option, subdir, false); } protected void runCoreExtensionWithOption(String option, String subdir, boolean pom) throws Exception { File testDir = extractResources("/mng-5889-find.mvn"); File basedir = new File(testDir, "../mng-" + (pom ? "5889" : "6223") + "-find.mvn" + option + (pom ? "Pom" : "Dir")); basedir.mkdir(); if (subdir != null) { testDir = new File(testDir, subdir); basedir = new File(basedir, subdir); basedir.mkdirs(); } Verifier verifier = newVerifier(basedir.getAbsolutePath()); verifier.addCliArgument( "-Dexpression.outputFile=" + new File(basedir, "expression.properties").getAbsolutePath()); verifier.addCliArgument(option); // -f/--file client/pom.xml verifier.addCliArgument((pom ? new File(testDir, "pom.xml") : testDir).getAbsolutePath()); verifier.setForkJvm(true); // force forked JVM since we need the shell script to detect .mvn/ location verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); Properties props = verifier.loadProperties("expression.properties"); assertEquals("ok", props.getProperty("project.properties.jvm-config")); assertEquals("ok", props.getProperty("project.properties.maven-config")); } }
MavenITmng6223FindBasedir
java
apache__camel
components/camel-bindy/src/main/java/org/apache/camel/dataformat/bindy/format/factories/ShortFormatFactory.java
{ "start": 1659, "end": 1986 }
class ____ extends AbstractNumberFormat<Short> { @Override public String format(Short object) throws Exception { return object.toString(); } @Override public Short parse(String string) throws Exception { return Short.valueOf(string); } } }
ShortFormat
java
apache__hadoop
hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/mapreduce/StreamXmlRecordReader.java
{ "start": 1981, "end": 10123 }
class ____ extends StreamBaseRecordReader { private Text key; private Text value; public StreamXmlRecordReader(FSDataInputStream in, FileSplit split, TaskAttemptContext context, Configuration conf, FileSystem fs) throws IOException { super(in, split, context, conf, fs); beginMark_ = checkJobGet(CONF_NS + "begin"); endMark_ = checkJobGet(CONF_NS + "end"); maxRecSize_ = conf_.getInt(CONF_NS + "maxrec", 50 * 1000); lookAhead_ = conf_.getInt(CONF_NS + "lookahead", 2 * maxRecSize_); synched_ = false; slowMatch_ = conf_.getBoolean(CONF_NS + "slowmatch", false); if (slowMatch_) { beginPat_ = makePatternCDataOrMark(beginMark_); endPat_ = makePatternCDataOrMark(endMark_); } init(); } public final void init() throws IOException { LOG.info("StreamBaseRecordReader.init: " + " start_=" + start_ + " end_=" + end_ + " length_=" + length_ + " start_ > in_.getPos() =" + (start_ > in_.getPos()) + " " + start_ + " > " + in_.getPos()); if (start_ > in_.getPos()) { in_.seek(start_); } pos_ = start_; bin_ = new BufferedInputStream(in_); seekNextRecordBoundary(); } int numNext = 0; public synchronized boolean next(Text key, Text value) throws IOException { numNext++; if (pos_ >= end_) { return false; } DataOutputBuffer buf = new DataOutputBuffer(); if (!readUntilMatchBegin()) { return false; } if (pos_ >= end_ || !readUntilMatchEnd(buf)) { return false; } // There is only one elem..key/value splitting is not done here. byte[] record = new byte[buf.getLength()]; System.arraycopy(buf.getData(), 0, record, 0, record.length); numRecStats(record, 0, record.length); key.set(record); value.set(""); return true; } public void seekNextRecordBoundary() throws IOException { readUntilMatchBegin(); } boolean readUntilMatchBegin() throws IOException { if (slowMatch_) { return slowReadUntilMatch(beginPat_, false, null); } else { return fastReadUntilMatch(beginMark_, false, null); } } private boolean readUntilMatchEnd(DataOutputBuffer buf) throws IOException { if (slowMatch_) { return slowReadUntilMatch(endPat_, true, buf); } else { return fastReadUntilMatch(endMark_, true, buf); } } private boolean slowReadUntilMatch(Pattern markPattern, boolean includePat, DataOutputBuffer outBufOrNull) throws IOException { byte[] buf = new byte[Math.max(lookAhead_, maxRecSize_)]; int read = 0; bin_.mark(Math.max(lookAhead_, maxRecSize_) + 2); // mark to invalidate if // we read more read = bin_.read(buf); if (read == -1) return false; String sbuf = new String(buf, 0, read, StandardCharsets.UTF_8); Matcher match = markPattern.matcher(sbuf); firstMatchStart_ = NA; firstMatchEnd_ = NA; int bufPos = 0; int state = synched_ ? CDATA_OUT : CDATA_UNK; int s = 0; while (match.find(bufPos)) { int input; if (match.group(1) != null) { input = CDATA_BEGIN; } else if (match.group(2) != null) { input = CDATA_END; firstMatchStart_ = NA; // |<DOC CDATA[ </DOC> ]]> should keep it } else { input = RECORD_MAYBE; } if (input == RECORD_MAYBE) { if (firstMatchStart_ == NA) { firstMatchStart_ = match.start(); firstMatchEnd_ = match.end(); } } state = nextState(state, input, match.start()); if (state == RECORD_ACCEPT) { break; } bufPos = match.end(); s++; } if (state != CDATA_UNK) { synched_ = true; } boolean matched = (firstMatchStart_ != NA) && (state == RECORD_ACCEPT || state == CDATA_UNK); if (matched) { int endPos = includePat ? firstMatchEnd_ : firstMatchStart_; bin_.reset(); for (long skiplen = endPos; skiplen > 0;) { skiplen -= bin_.skip(skiplen); // Skip succeeds as we have read this // buffer } pos_ += endPos; if (outBufOrNull != null) { outBufOrNull.writeBytes(sbuf.substring(0, endPos)); } } return matched; } // states private final static int CDATA_IN = 10; private final static int CDATA_OUT = 11; private final static int CDATA_UNK = 12; private final static int RECORD_ACCEPT = 13; // inputs private final static int CDATA_BEGIN = 20; private final static int CDATA_END = 21; private final static int RECORD_MAYBE = 22; /* also updates firstMatchStart_; */ int nextState(int state, int input, int bufPos) { switch (state) { case CDATA_UNK: case CDATA_OUT: switch (input) { case CDATA_BEGIN: return CDATA_IN; case CDATA_END: if (state == CDATA_OUT) { // System.out.println("buggy XML " + bufPos); } return CDATA_OUT; case RECORD_MAYBE: return (state == CDATA_UNK) ? CDATA_UNK : RECORD_ACCEPT; } break; case CDATA_IN: return (input == CDATA_END) ? CDATA_OUT : CDATA_IN; } throw new IllegalStateException(state + " " + input + " " + bufPos + " " + splitName_); } Pattern makePatternCDataOrMark(String escapedMark) { StringBuffer pat = new StringBuffer(); addGroup(pat, StreamUtil.regexpEscape("CDATA[")); // CDATA_BEGIN addGroup(pat, StreamUtil.regexpEscape("]]>")); // CDATA_END addGroup(pat, escapedMark); // RECORD_MAYBE return Pattern.compile(pat.toString()); } void addGroup(StringBuffer pat, String escapedGroup) { if (pat.length() > 0) { pat.append("|"); } pat.append("("); pat.append(escapedGroup); pat.append(")"); } boolean fastReadUntilMatch(String textPat, boolean includePat, DataOutputBuffer outBufOrNull) throws IOException { byte[] cpat = textPat.getBytes(StandardCharsets.UTF_8); int m = 0; boolean match = false; int msup = cpat.length; int LL = 120000 * 10; bin_.mark(LL); // large number to invalidate mark while (true) { int b = bin_.read(); if (b == -1) break; byte c = (byte) b; // this assumes eight-bit matching. OK with UTF-8 if (c == cpat[m]) { m++; if (m == msup) { match = true; break; } } else { bin_.mark(LL); // rest mark so we could jump back if we found a match if (outBufOrNull != null) { outBufOrNull.write(cpat, 0, m); outBufOrNull.write(c); } pos_ += m + 1; // skip m chars, +1 for 'c' m = 0; } } if (!includePat && match) { bin_.reset(); } else if (outBufOrNull != null) { outBufOrNull.write(cpat); pos_ += msup; } return match; } String checkJobGet(String prop) throws IOException { String val = conf_.get(prop); if (val == null) { throw new IOException("JobConf: missing required property: " + prop); } return val; } String beginMark_; String endMark_; Pattern beginPat_; Pattern endPat_; boolean slowMatch_; int lookAhead_; // bytes to read to try to synch CDATA/non-CDATA. Should be // more than max record size int maxRecSize_; BufferedInputStream bin_; // Wrap FSDataInputStream for efficient backward // seeks long pos_; // Keep track on position with respect encapsulated // FSDataInputStream private final static int NA = -1; int firstMatchStart_ = 0; // candidate record boundary. Might just be CDATA. int firstMatchEnd_ = 0; boolean synched_; @Override public Text getCurrentKey() throws IOException, InterruptedException { return key; } @Override public Text getCurrentValue() throws IOException, InterruptedException { return value; } @Override public void initialize(InputSplit arg0, TaskAttemptContext arg1) throws IOException, InterruptedException { } @Override public boolean nextKeyValue() throws IOException, InterruptedException { key = createKey(); value = createValue(); return next(key, value); } }
StreamXmlRecordReader
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/mapper/BooleanScriptMapperTests.java
{ "start": 802, "end": 3525 }
class ____ extends MapperScriptTestCase<BooleanFieldScript.Factory> { private static BooleanFieldScript.Factory factory(Consumer<BooleanFieldScript> executor) { return new BooleanFieldScript.Factory() { @Override public BooleanFieldScript.LeafFactory newFactory( String fieldName, Map<String, Object> params, SearchLookup searchLookup, OnScriptError onScriptError ) { return new BooleanFieldScript.LeafFactory() { @Override public BooleanFieldScript newInstance(LeafReaderContext ctx) { return new BooleanFieldScript(fieldName, params, searchLookup, OnScriptError.FAIL, ctx) { @Override public void execute() { executor.accept(this); } }; } }; } }; } @Override protected String type() { return BooleanFieldMapper.CONTENT_TYPE; } @Override protected BooleanFieldScript.Factory serializableScript() { return factory(s -> {}); } @Override protected BooleanFieldScript.Factory errorThrowingScript() { return factory(s -> { throw new UnsupportedOperationException("Oops"); }); } @Override protected BooleanFieldScript.Factory singleValueScript() { return factory(s -> s.emit(true)); } @Override protected BooleanFieldScript.Factory multipleValuesScript() { return factory(s -> { s.emit(true); s.emit(false); }); } @Override protected void assertMultipleValues(List<IndexableField> fields) { assertEquals(4, fields.size()); assertEquals("indexed,omitNorms,indexOptions=DOCS<field:[46]>", fields.get(0).toString()); assertEquals("docValuesType=SORTED_NUMERIC<field:0>", fields.get(1).toString()); assertEquals("indexed,omitNorms,indexOptions=DOCS<field:[54]>", fields.get(2).toString()); assertEquals("docValuesType=SORTED_NUMERIC<field:1>", fields.get(3).toString()); } @Override protected void assertDocValuesDisabled(List<IndexableField> fields) { assertEquals(1, fields.size()); assertEquals("indexed,omitNorms,indexOptions=DOCS<field:[54]>", fields.get(0).toString()); } @Override protected void assertIndexDisabled(List<IndexableField> fields) { assertEquals(1, fields.size()); assertEquals("docValuesType=SORTED_NUMERIC<field:1>", fields.get(0).toString()); } }
BooleanScriptMapperTests
java
google__guice
core/src/com/google/inject/internal/InternalProviderInstanceBindingImpl.java
{ "start": 2725, "end": 3344 }
class ____<T> extends InternalFactory<T> implements Provider<T>, HasDependencies, ProvisionListenerStackCallback.ProvisionCallback<T> { private final InitializationTiming initializationTiming; private Object source; private InjectorImpl injector; private Dependency<?> dependency; ProvisionListenerStackCallback<T> provisionCallback; Factory(InitializationTiming initializationTiming) { this.initializationTiming = initializationTiming; } /** * Exclusively binds this factory to the given injector. * * <p>This is needed since the implementations of this
Factory
java
junit-team__junit5
junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/JupiterTestEngine.java
{ "start": 1863, "end": 4286 }
class ____ extends HierarchicalTestEngine<JupiterEngineExecutionContext> { @Override public String getId() { return JupiterEngineDescriptor.ENGINE_ID; } /** * Returns {@code org.junit.jupiter} as the group ID. */ @Override public Optional<String> getGroupId() { return Optional.of("org.junit.jupiter"); } /** * Returns {@code junit-jupiter-engine} as the artifact ID. */ @Override public Optional<String> getArtifactId() { return Optional.of("junit-jupiter-engine"); } @Override public TestDescriptor discover(EngineDiscoveryRequest discoveryRequest, UniqueId uniqueId) { DiscoveryIssueReporter issueReporter = DiscoveryIssueReporter.deduplicating( DiscoveryIssueReporter.forwarding(discoveryRequest.getDiscoveryListener(), uniqueId)); JupiterConfiguration configuration = new CachingJupiterConfiguration( new DefaultJupiterConfiguration(discoveryRequest.getConfigurationParameters(), discoveryRequest.getOutputDirectoryCreator(), issueReporter)); JupiterEngineDescriptor engineDescriptor = new JupiterEngineDescriptor(uniqueId, configuration); DiscoverySelectorResolver.resolveSelectors(discoveryRequest, engineDescriptor, issueReporter); return engineDescriptor; } @Override protected HierarchicalTestExecutorService createExecutorService(ExecutionRequest request) { JupiterConfiguration configuration = getJupiterConfiguration(request); if (configuration.isParallelExecutionEnabled()) { return ParallelHierarchicalTestExecutorServiceFactory.create(new PrefixedConfigurationParameters( request.getConfigurationParameters(), JupiterConfiguration.PARALLEL_CONFIG_PREFIX)); } return super.createExecutorService(request); } @Override protected JupiterEngineExecutionContext createExecutionContext(ExecutionRequest request) { return new JupiterEngineExecutionContext(request.getEngineExecutionListener(), getJupiterConfiguration(request), new LauncherStoreFacade(request.getStore())); } /** * @since 5.4 */ @Override protected ThrowableCollector.Factory createThrowableCollectorFactory(ExecutionRequest request) { return JupiterThrowableCollectorFactory::createThrowableCollector; } private JupiterConfiguration getJupiterConfiguration(ExecutionRequest request) { JupiterEngineDescriptor engineDescriptor = (JupiterEngineDescriptor) request.getRootTestDescriptor(); return engineDescriptor.getConfiguration(); } }
JupiterTestEngine
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/NullableTypeParameterTest.java
{ "start": 1960, "end": 2534 }
interface ____ {} <X extends @Nullable Object, Y extends @NonNull Object> void f() {} <X extends @Nullable Object> void h() {} <X extends @Nullable I & @Nullable J> void i() {} } """) .doTest(); } @Test public void noFix() { testHelper .addInputLines( "T.java", """ import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable;
J
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/GetContainerStatusesRequest.java
{ "start": 1522, "end": 2579 }
class ____ { @Public @Stable public static GetContainerStatusesRequest newInstance( List<ContainerId> containerIds) { GetContainerStatusesRequest request = Records.newRecord(GetContainerStatusesRequest.class); request.setContainerIds(containerIds); return request; } /** * Get the list of <code>ContainerId</code>s of containers for which to obtain * the <code>ContainerStatus</code>. * * @return the list of <code>ContainerId</code>s of containers for which to * obtain the <code>ContainerStatus</code>. */ @Public @Stable public abstract List<ContainerId> getContainerIds(); /** * Set a list of <code>ContainerId</code>s of containers for which to obtain * the <code>ContainerStatus</code> * * @param containerIds * a list of <code>ContainerId</code>s of containers for which to * obtain the <code>ContainerStatus</code> */ @Public @Stable public abstract void setContainerIds(List<ContainerId> containerIds); }
GetContainerStatusesRequest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/SampleBooleanAggregatorFunction.java
{ "start": 998, "end": 6124 }
class ____ implements AggregatorFunction { private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of( new IntermediateStateDesc("sample", ElementType.BYTES_REF) ); private final DriverContext driverContext; private final SampleBooleanAggregator.SingleState state; private final List<Integer> channels; private final int limit; public SampleBooleanAggregatorFunction(DriverContext driverContext, List<Integer> channels, SampleBooleanAggregator.SingleState state, int limit) { this.driverContext = driverContext; this.channels = channels; this.state = state; this.limit = limit; } public static SampleBooleanAggregatorFunction create(DriverContext driverContext, List<Integer> channels, int limit) { return new SampleBooleanAggregatorFunction(driverContext, channels, SampleBooleanAggregator.initSingle(driverContext.bigArrays(), limit), limit); } public static List<IntermediateStateDesc> intermediateStateDesc() { return INTERMEDIATE_STATE_DESC; } @Override public int intermediateBlockCount() { return INTERMEDIATE_STATE_DESC.size(); } @Override public void addRawInput(Page page, BooleanVector mask) { if (mask.allFalse()) { // Entire page masked away } else if (mask.allTrue()) { addRawInputNotMasked(page); } else { addRawInputMasked(page, mask); } } private void addRawInputMasked(Page page, BooleanVector mask) { BooleanBlock valueBlock = page.getBlock(channels.get(0)); BooleanVector valueVector = valueBlock.asVector(); if (valueVector == null) { addRawBlock(valueBlock, mask); return; } addRawVector(valueVector, mask); } private void addRawInputNotMasked(Page page) { BooleanBlock valueBlock = page.getBlock(channels.get(0)); BooleanVector valueVector = valueBlock.asVector(); if (valueVector == null) { addRawBlock(valueBlock); return; } addRawVector(valueVector); } private void addRawVector(BooleanVector valueVector) { for (int valuesPosition = 0; valuesPosition < valueVector.getPositionCount(); valuesPosition++) { boolean valueValue = valueVector.getBoolean(valuesPosition); SampleBooleanAggregator.combine(state, valueValue); } } private void addRawVector(BooleanVector valueVector, BooleanVector mask) { for (int valuesPosition = 0; valuesPosition < valueVector.getPositionCount(); valuesPosition++) { if (mask.getBoolean(valuesPosition) == false) { continue; } boolean valueValue = valueVector.getBoolean(valuesPosition); SampleBooleanAggregator.combine(state, valueValue); } } private void addRawBlock(BooleanBlock valueBlock) { for (int p = 0; p < valueBlock.getPositionCount(); p++) { int valueValueCount = valueBlock.getValueCount(p); if (valueValueCount == 0) { continue; } int valueStart = valueBlock.getFirstValueIndex(p); int valueEnd = valueStart + valueValueCount; for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) { boolean valueValue = valueBlock.getBoolean(valueOffset); SampleBooleanAggregator.combine(state, valueValue); } } } private void addRawBlock(BooleanBlock valueBlock, BooleanVector mask) { for (int p = 0; p < valueBlock.getPositionCount(); p++) { if (mask.getBoolean(p) == false) { continue; } int valueValueCount = valueBlock.getValueCount(p); if (valueValueCount == 0) { continue; } int valueStart = valueBlock.getFirstValueIndex(p); int valueEnd = valueStart + valueValueCount; for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) { boolean valueValue = valueBlock.getBoolean(valueOffset); SampleBooleanAggregator.combine(state, valueValue); } } } @Override public void addIntermediateInput(Page page) { assert channels.size() == intermediateBlockCount(); assert page.getBlockCount() >= channels.get(0) + intermediateStateDesc().size(); Block sampleUncast = page.getBlock(channels.get(0)); if (sampleUncast.areAllValuesNull()) { return; } BytesRefBlock sample = (BytesRefBlock) sampleUncast; assert sample.getPositionCount() == 1; BytesRef sampleScratch = new BytesRef(); SampleBooleanAggregator.combineIntermediate(state, sample); } @Override public void evaluateIntermediate(Block[] blocks, int offset, DriverContext driverContext) { state.toIntermediate(blocks, offset, driverContext); } @Override public void evaluateFinal(Block[] blocks, int offset, DriverContext driverContext) { blocks[offset] = SampleBooleanAggregator.evaluateFinal(state, driverContext); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("["); sb.append("channels=").append(channels); sb.append("]"); return sb.toString(); } @Override public void close() { state.close(); } }
SampleBooleanAggregatorFunction
java
elastic__elasticsearch
x-pack/plugin/write-load-forecaster/src/internalClusterTest/java/org/elasticsearch/xpack/writeloadforecaster/WriteLoadForecasterIT.java
{ "start": 2524, "end": 12490 }
class ____ extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return List.of(DataStreamsPlugin.class, FakeLicenseWriteLoadForecasterPlugin.class); } @Before public void ensureValidLicense() { setHasValidLicense(true); } public void testWriteLoadForecastGetsPopulatedDuringRollovers() throws Exception { final String dataStreamName = "logs-es"; setUpDataStreamWriteDocsAndRollover(dataStreamName); final ClusterState clusterState = internalCluster().getCurrentMasterNodeInstance(ClusterService.class).state(); final Metadata metadata = clusterState.getMetadata(); final DataStream dataStream = metadata.getProject().dataStreams().get(dataStreamName); final IndexMetadata writeIndexMetadata = metadata.getProject().getIndexSafe(dataStream.getWriteIndex()); final OptionalDouble indexMetadataForecastedWriteLoad = writeIndexMetadata.getForecastedWriteLoad(); assertThat(indexMetadataForecastedWriteLoad.isPresent(), is(equalTo(true))); assertThat(indexMetadataForecastedWriteLoad.getAsDouble(), is(greaterThan(0.0))); final WriteLoadForecaster writeLoadForecaster = internalCluster().getCurrentMasterNodeInstance(WriteLoadForecaster.class); final OptionalDouble forecastedWriteLoad = writeLoadForecaster.getForecastedWriteLoad(writeIndexMetadata); assertThat(forecastedWriteLoad.isPresent(), is(equalTo(true))); assertThat(forecastedWriteLoad.getAsDouble(), is(equalTo(indexMetadataForecastedWriteLoad.getAsDouble()))); assertAllPreviousForecastsAreClearedAfterRollover(dataStream, metadata); setHasValidLicense(false); writeLoadForecaster.refreshLicense(); final OptionalDouble forecastedWriteLoadAfterLicenseChange = writeLoadForecaster.getForecastedWriteLoad(writeIndexMetadata); assertThat(forecastedWriteLoadAfterLicenseChange.isPresent(), is(equalTo(false))); } public void testWriteLoadForecastDoesNotGetPopulatedWithInvalidLicense() throws Exception { setHasValidLicense(false); final String dataStreamName = "logs-es"; setUpDataStreamWriteDocsAndRollover(dataStreamName); final ClusterState clusterState = internalCluster().getCurrentMasterNodeInstance(ClusterService.class).state(); final DataStream dataStream = clusterState.getMetadata().getProject().dataStreams().get(dataStreamName); final IndexMetadata writeIndexMetadata = clusterState.metadata().getProject().getIndexSafe(dataStream.getWriteIndex()); assertThat(writeIndexMetadata.getForecastedWriteLoad().isPresent(), is(equalTo(false))); } public void testWriteLoadForecastIsOverriddenBySetting() throws Exception { final double writeLoadForecastOverride = randomDoubleBetween(64, 128, true); final String dataStreamName = "logs-es"; setUpDataStreamWriteDocsAndRollover( dataStreamName, Settings.builder() .put(WriteLoadForecasterPlugin.OVERRIDE_WRITE_LOAD_FORECAST_SETTING.getKey(), writeLoadForecastOverride) .build() ); final ClusterState clusterState = internalCluster().getCurrentMasterNodeInstance(ClusterService.class).state(); final Metadata metadata = clusterState.metadata(); final DataStream dataStream = metadata.getProject().dataStreams().get(dataStreamName); final IndexMetadata writeIndexMetadata = metadata.getProject().getIndexSafe(dataStream.getWriteIndex()); final OptionalDouble indexMetadataForecastedWriteLoad = writeIndexMetadata.getForecastedWriteLoad(); assertThat(indexMetadataForecastedWriteLoad.isPresent(), is(equalTo(true))); assertThat(indexMetadataForecastedWriteLoad.getAsDouble(), is(greaterThan(0.0))); final WriteLoadForecaster writeLoadForecaster = internalCluster().getCurrentMasterNodeInstance(WriteLoadForecaster.class); final OptionalDouble forecastedWriteLoad = writeLoadForecaster.getForecastedWriteLoad(writeIndexMetadata); assertThat(forecastedWriteLoad.isPresent(), is(equalTo(true))); assertThat(forecastedWriteLoad.getAsDouble(), is(equalTo(writeLoadForecastOverride))); assertThat(forecastedWriteLoad.getAsDouble(), is(not(equalTo(indexMetadataForecastedWriteLoad.getAsDouble())))); assertAllPreviousForecastsAreClearedAfterRollover(dataStream, metadata); setHasValidLicense(false); writeLoadForecaster.refreshLicense(); final OptionalDouble forecastedWriteLoadAfterLicenseChange = writeLoadForecaster.getForecastedWriteLoad(writeIndexMetadata); assertThat(forecastedWriteLoadAfterLicenseChange.isPresent(), is(equalTo(false))); } private void setUpDataStreamWriteDocsAndRollover(String dataStreamName) throws Exception { setUpDataStreamWriteDocsAndRollover(dataStreamName, Settings.EMPTY); } private void setUpDataStreamWriteDocsAndRollover(String dataStreamName, Settings extraIndexTemplateSettings) throws Exception { final int numberOfShards = randomIntBetween(1, 5); final int numberOfReplicas = randomIntBetween(0, 1); internalCluster().ensureAtLeastNumDataNodes(numberOfReplicas + 1); final Settings indexSettings = Settings.builder() .put(extraIndexTemplateSettings) .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, numberOfShards) .put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, numberOfReplicas) .build(); assertAcked( client().execute( TransportPutComposableIndexTemplateAction.TYPE, new TransportPutComposableIndexTemplateAction.Request("my-template").indexTemplate( ComposableIndexTemplate.builder() .indexPatterns(List.of("logs-*")) .template(new Template(indexSettings, null, null)) .dataStreamTemplate(new ComposableIndexTemplate.DataStreamTemplate()) .build() ) ) ); assertAcked( client().execute( CreateDataStreamAction.INSTANCE, new CreateDataStreamAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, dataStreamName) ).actionGet() ); final int numberOfRollovers = randomIntBetween(5, 10); for (int i = 0; i < numberOfRollovers; i++) { assertBusy(() -> { for (int j = 0; j < 10; j++) { indexDocs(dataStreamName, randomIntBetween(100, 200)); } final ClusterState clusterState = internalCluster().getCurrentMasterNodeInstance(ClusterService.class).state(); final DataStream dataStream = clusterState.getMetadata().getProject().dataStreams().get(dataStreamName); final String writeIndex = dataStream.getWriteIndex().getName(); final IndicesStatsResponse indicesStatsResponse = indicesAdmin().prepareStats(writeIndex).get(); for (IndexShardStats indexShardStats : indicesStatsResponse.getIndex(writeIndex).getIndexShards().values()) { for (ShardStats shard : indexShardStats.getShards()) { final IndexingStats.Stats shardIndexingStats = shard.getStats().getIndexing().getTotal(); // Ensure that we have enough clock granularity before rolling over to ensure that we capture _some_ write load assertThat(shardIndexingStats.getTotalActiveTimeInMillis(), is(greaterThan(0L))); assertThat(shardIndexingStats.getWriteLoad(), is(greaterThan(0.0))); } } }); assertAcked(indicesAdmin().rolloverIndex(new RolloverRequest(dataStreamName, null)).actionGet()); } ensureGreen(); } static void indexDocs(String dataStream, int numDocs) { BulkRequest bulkRequest = new BulkRequest(); for (int i = 0; i < numDocs; i++) { String value = DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.formatMillis(System.currentTimeMillis()); bulkRequest.add( new IndexRequest(dataStream).opType(DocWriteRequest.OpType.CREATE) .source(Strings.format("{\"%s\":\"%s\"}", DEFAULT_TIMESTAMP_FIELD, value), XContentType.JSON) ); } client().bulk(bulkRequest).actionGet(); } private void setHasValidLicense(boolean hasValidLicense) { for (PluginsService pluginsService : internalCluster().getInstances(PluginsService.class)) { pluginsService.filterPlugins(FakeLicenseWriteLoadForecasterPlugin.class).forEach(p -> p.setHasValidLicense(hasValidLicense)); } } private void assertAllPreviousForecastsAreClearedAfterRollover(DataStream dataStream, Metadata metadata) { final WriteLoadForecaster writeLoadForecaster = internalCluster().getCurrentMasterNodeInstance(WriteLoadForecaster.class); for (Index index : dataStream.getIndices()) { if (index.equals(dataStream.getWriteIndex())) { continue; } final IndexMetadata backingIndexMetadata = metadata.getProject().getIndexSafe(index); final OptionalDouble backingIndexForecastedWriteLoad = writeLoadForecaster.getForecastedWriteLoad(backingIndexMetadata); assertThat(backingIndexForecastedWriteLoad.isEmpty(), is(equalTo(true))); assertThat(backingIndexMetadata.getForecastedWriteLoad().isEmpty(), is(equalTo(true))); assertThat( backingIndexMetadata.getSettings().hasValue(WriteLoadForecasterPlugin.OVERRIDE_WRITE_LOAD_FORECAST_SETTING.getKey()), is(equalTo(false)) ); } } public static
WriteLoadForecasterIT
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxRepeatWhen.java
{ "start": 5335, "end": 6853 }
class ____ extends Flux<Long> implements InnerConsumer<Object>, OptimizableOperator<Long, Long> { // main initialized upon creation in FluxRepeatWhen.subscribeOrReturn @SuppressWarnings("NotNullFieldNotInitialized") RepeatWhenMainSubscriber<?> main; final Sinks.Many<Long> completionSignal = Sinks.many().multicast().onBackpressureBuffer(); @Override public Context currentContext() { return main.currentContext(); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.PARENT) return main.otherArbiter; if (key == Attr.ACTUAL) return main; if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; if (key == InternalProducerAttr.INSTANCE) return true; return null; } @Override public void onSubscribe(Subscription s) { main.setWhen(s); } @Override public void onNext(Object t) { main.resubscribe(t); } @Override public void onError(Throwable t) { main.whenError(t); } @Override public void onComplete() { main.whenComplete(); } @Override public void subscribe(CoreSubscriber<? super Long> actual) { completionSignal.asFlux().subscribe(actual); } @Override public CoreSubscriber<? super Long> subscribeOrReturn(CoreSubscriber<? super Long> actual) { return actual; } @Override public Flux<Long> source() { return completionSignal.asFlux(); } @Override public @Nullable OptimizableOperator<?, ? extends Long> nextOptimizableSource() { return null; } } }
RepeatWhenOtherSubscriber
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/params/converter/JavaTimeArgumentConverterTests.java
{ "start": 1119, "end": 5087 }
class ____ { @SuppressWarnings("DataFlowIssue") @Test void convertsStringToChronoLocalDate() { assertThat(convert("01.02.2017", "dd.MM.yyyy", ChronoLocalDate.class)) // .isEqualTo(LocalDate.of(2017, 2, 1)); } @SuppressWarnings("DataFlowIssue") @Test void convertsStringToChronoLocalDateTime() { assertThat(convert("01.02.2017 12:34:56.789", "dd.MM.yyyy HH:mm:ss.SSS", ChronoLocalDateTime.class)) // .isEqualTo(LocalDateTime.of(2017, 2, 1, 12, 34, 56, 789_000_000)); } @SuppressWarnings("DataFlowIssue") @Test void convertsStringToChronoZonedDateTime() { assertThat(convert("01.02.2017 12:34:56.789 Z", "dd.MM.yyyy HH:mm:ss.SSS X", ChronoZonedDateTime.class)) // .isEqualTo(ZonedDateTime.of(2017, 2, 1, 12, 34, 56, 789_000_000, UTC)); } @SuppressWarnings("DataFlowIssue") @Test void convertsStringToLocalDate() { assertThat(convert("01.02.2017", "dd.MM.yyyy", LocalDate.class)) // .isEqualTo(LocalDate.of(2017, 2, 1)); } @SuppressWarnings("DataFlowIssue") @Test void convertsStringToLocalDateTime() { assertThat(convert("01.02.2017 12:34:56.789", "dd.MM.yyyy HH:mm:ss.SSS", LocalDateTime.class)) // .isEqualTo(LocalDateTime.of(2017, 2, 1, 12, 34, 56, 789_000_000)); } @SuppressWarnings("DataFlowIssue") @Test void convertsStringToLocalTime() { assertThat(convert("12:34:56.789", "HH:mm:ss.SSS", LocalTime.class)) // .isEqualTo(LocalTime.of(12, 34, 56, 789_000_000)); } @SuppressWarnings("DataFlowIssue") @Test void convertsStringToOffsetDateTime() { assertThat(convert("01.02.2017 12:34:56.789 +02", "dd.MM.yyyy HH:mm:ss.SSS X", OffsetDateTime.class)) // .isEqualTo(OffsetDateTime.of(2017, 2, 1, 12, 34, 56, 789_000_000, ZoneOffset.ofHours(2))); } @SuppressWarnings("DataFlowIssue") @Test void convertsStringToOffsetTime() { assertThat(convert("12:34:56.789 -02", "HH:mm:ss.SSS X", OffsetTime.class)) // .isEqualTo(OffsetTime.of(12, 34, 56, 789_000_000, ZoneOffset.ofHours(-2))); } @SuppressWarnings("DataFlowIssue") @Test void convertsStringToYear() { assertThat(convert("2017", "yyyy", Year.class)) // .isEqualTo(Year.of(2017)); } @SuppressWarnings("DataFlowIssue") @Test void convertsStringToYearMonth() { assertThat(convert("03/2017", "MM/yyyy", YearMonth.class)) // .isEqualTo(YearMonth.of(2017, 3)); } @SuppressWarnings("DataFlowIssue") @Test void convertsStringToZonedDateTime() { assertThat(convert("01.02.2017 12:34:56.789 Europe/Berlin", "dd.MM.yyyy HH:mm:ss.SSS VV", ZonedDateTime.class)) // .isEqualTo(ZonedDateTime.of(2017, 2, 1, 12, 34, 56, 789_000_000, ZoneId.of("Europe/Berlin"))); } @Test void throwsExceptionOnInvalidTargetType() { var exception = assertThrows(ArgumentConversionException.class, () -> convert("2017", "yyyy", Integer.class)); assertThat(exception).hasMessage("Cannot convert to java.lang.Integer: 2017"); } /** * @since 5.12 */ @Test void throwsExceptionOnNullParameterWithoutNullable() { var exception = assertThrows(ArgumentConversionException.class, () -> convert(null, "dd.MM.yyyy", LocalDate.class)); assertThat(exception).hasMessage( "Cannot convert null to java.time.LocalDate; consider setting 'nullable = true'"); } /** * @since 5.12 */ @SuppressWarnings("DataFlowIssue") @Test void convertsNullableParameter() { assertThat(convert(null, "dd.MM.yyyy", true, LocalDate.class)).isNull(); } private @Nullable Object convert(@Nullable Object input, String pattern, Class<?> targetClass) { return convert(input, pattern, false, targetClass); } private @Nullable Object convert(@Nullable Object input, String pattern, boolean nullable, Class<?> targetClass) { var converter = new JavaTimeArgumentConverter(); var annotation = mock(JavaTimeConversionPattern.class); when(annotation.value()).thenReturn(pattern); when(annotation.nullable()).thenReturn(nullable); return converter.convert(input, targetClass, annotation); } }
JavaTimeArgumentConverterTests
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3360/Vehicle.java
{ "start": 241, "end": 660 }
class ____ { private final String name; private final String modelName; protected Vehicle(String name, String modelName) { this.name = name; this.modelName = modelName; } public String getName() { return name; } public String getModelName() { return modelName; } public String getComputedName() { return null; } public static
Vehicle
java
square__retrofit
retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java
{ "start": 31408, "end": 32495 }
class ____ { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping") String ping) { return null; } } assertMalformedRequest(Example.class, "."); assertMalformedRequest(Example.class, ".."); assertThat(buildRequest(Example.class, "./a").url().encodedPath()).isEqualTo("/foo/bar/.%2Fa/"); assertThat(buildRequest(Example.class, "a/.").url().encodedPath()).isEqualTo("/foo/bar/a%2F./"); assertThat(buildRequest(Example.class, "a/..").url().encodedPath()) .isEqualTo("/foo/bar/a%2F../"); assertThat(buildRequest(Example.class, "../a").url().encodedPath()) .isEqualTo("/foo/bar/..%2Fa/"); assertThat(buildRequest(Example.class, "..\\..").url().encodedPath()) .isEqualTo("/foo/bar/..%5C../"); assertThat(buildRequest(Example.class, "%2E").url().encodedPath()).isEqualTo("/foo/bar/%252E/"); assertThat(buildRequest(Example.class, "%2E%2E").url().encodedPath()) .isEqualTo("/foo/bar/%252E%252E/"); } @Test public void encodedPathParametersAndPathTraversal() {
Example
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/RouterFunctionTests.java
{ "start": 2159, "end": 3794 }
class ____ { @Test void completableFuture() { execute("/async/completableFuture", body -> body.json("{\"name\":\"Joe\",\"age\":0}")); } @Test void publisher() { execute("/async/publisher", body -> body.json("{\"name\":\"Joe\",\"age\":0}")); } } private void execute(String uri, Consumer<WebTestClient.BodyContentSpec> assertions) { RouterFunction<?> testRoute = testRoute(); assertions.accept(MockMvcWebTestClient.bindToRouterFunction(testRoute).build() .get() .uri(uri) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody()); } private static RouterFunction<?> testRoute() { return route() .GET("/person/{name}", request -> { Person person = new Person(request.pathVariable("name")); person.setAge(42); return ok().body(person); }) .GET("/search", request -> { String name = request.param("name").orElseThrow(NullPointerException::new); Person person = new Person(name); return ok().body(person); }) .path("/async", b -> b .GET("/completableFuture", request -> { CompletableFuture<Person> future = new CompletableFuture<>(); future.complete(new Person("Joe")); return ok().body(future); }) .GET("/publisher", request -> { Mono<Person> mono = Mono.just(new Person("Joe")); return ok().body(mono); }) ) .route(RequestPredicates.all(), request -> ServerResponse.notFound().build()) .build(); } @SuppressWarnings("unused") private static
AsyncTests