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
netty__netty
handler/src/test/java/io/netty/handler/ssl/SslHandlerCoalescingBufferQueueTest.java
{ "start": 2507, "end": 4921 }
enum ____ { BASIC_NIO_BUFFER(new Supplier() { @Override public ByteBuf get() { return Unpooled.wrappedBuffer(createNioBuffer()); } }, NO_WRAPPER), READ_ONLY_AND_DUPLICATE_NIO_BUFFER(new Supplier() { @Override public ByteBuf get() { return Unpooled.wrappedBuffer(createNioBuffer().asReadOnlyBuffer()); } }, DUPLICATE_WRAPPER), BASIC_DIRECT_BUFFER(BYTEBUF_SUPPLIER, NO_WRAPPER), DUPLICATE_DIRECT_BUFFER(BYTEBUF_SUPPLIER, DUPLICATE_WRAPPER), SLICED_DIRECT_BUFFER(BYTEBUF_SUPPLIER, SLICE_WRAPPER); final Supplier<ByteBuf> bufferSupplier; final Function<ByteBuf, ByteBuf> bufferWrapper; CumulationTestScenario(Supplier<ByteBuf> bufferSupplier, Function<ByteBuf, ByteBuf> bufferWrapper) { this.bufferSupplier = bufferSupplier; this.bufferWrapper = bufferWrapper; } } @ParameterizedTest @EnumSource(CumulationTestScenario.class) public void testCumulation(CumulationTestScenario testScenario) { EmbeddedChannel channel = new EmbeddedChannel(); SslHandlerCoalescingBufferQueue queue = new SslHandlerCoalescingBufferQueue(channel, 16, false) { @Override protected int wrapDataSize() { return 128; } }; ByteBuf original = testScenario.bufferSupplier.get(); original.writerIndex(8); ByteBuf first = testScenario.bufferWrapper.apply(original); first.retain(); queue.add(first); ByteBuf second = Unpooled.copyLong(3); queue.add(second); ChannelPromise promise = channel.newPromise(); assertFalse(queue.isEmpty()); ByteBuf buffer = queue.remove(UnpooledByteBufAllocator.DEFAULT, 128, promise); try { assertEquals(16, buffer.readableBytes()); assertEquals(1, buffer.readLong()); assertEquals(3, buffer.readLong()); } finally { buffer.release(); } assertTrue(queue.isEmpty()); assertEquals(8, original.writerIndex()); original.writerIndex(original.capacity()); assertEquals(2, original.getLong(8)); first.release(); assertEquals(0, first.refCnt()); assertEquals(0, second.refCnt()); } }
CumulationTestScenario
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/LineItem.java
{ "start": 406, "end": 1079 }
class ____ { private String id; private int quantity; private Order order; public LineItem() { } public LineItem(String v1, int v2, Order v3) { id = v1; quantity = v2; order = v3; } public LineItem(String v1, int v2) { id = v1; quantity = v2; } @Id @Column(name = "ID") public String getId() { return id; } public void setId(String v) { id = v; } @Column(name = "QUANTITY") public int getQuantity() { return quantity; } public void setQuantity(int v) { quantity = v; } @ManyToOne @JoinColumn(name = "FK1_FOR_ORDER_TABLE") public Order getOrder() { return order; } public void setOrder(Order v) { order = v; } }
LineItem
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestFsShellList.java
{ "start": 1163, "end": 3234 }
class ____ { private static Configuration conf; private static FsShell shell; private static LocalFileSystem lfs; private static Path testRootDir; @BeforeAll public static void setup() throws Exception { conf = new Configuration(); shell = new FsShell(conf); lfs = FileSystem.getLocal(conf); lfs.setVerifyChecksum(true); lfs.setWriteChecksum(true); String root = System.getProperty("test.build.data", "test/build/data"); testRootDir = lfs.makeQualified(new Path(root, "testFsShellList")); assertThat(lfs.mkdirs(testRootDir)).isTrue(); } @AfterAll public static void teardown() throws Exception { lfs.delete(testRootDir, true); } private void createFile(Path filePath) throws Exception { FSDataOutputStream out = lfs.create(filePath); out.writeChars("I am " + filePath); out.close(); assertThat(lfs.exists(lfs.getChecksumFile(filePath))).isTrue(); } @Test public void testList() throws Exception { createFile(new Path(testRootDir, "abc")); String[] lsArgv = new String[]{"-ls", testRootDir.toString()}; assertThat(shell.run(lsArgv)).isEqualTo(0); if (!Path.WINDOWS) { createFile(new Path(testRootDir, "abc\bd\tef")); createFile(new Path(testRootDir, "qq\r123")); } createFile(new Path(testRootDir, "ghi")); lsArgv = new String[]{"-ls", testRootDir.toString()}; assertThat(shell.run(lsArgv)).isEqualTo(0); lsArgv = new String[]{"-ls", "-q", testRootDir.toString()}; assertThat(shell.run(lsArgv)).isEqualTo(0); } /* UGI params should take effect when we pass. */ @Test public void testListWithUGI() throws Exception { assertThrows(IllegalArgumentException.class, () -> { FsShell fsShell = new FsShell(new Configuration()); //Passing Dummy such that it should through IAE fsShell.getConf().set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "DUMMYAUTH"); String[] lsArgv = new String[]{"-ls", testRootDir.toString()}; fsShell.run(lsArgv); }); } }
TestFsShellList
java
quarkusio__quarkus
integration-tests/openapi/src/test/java/io/quarkus/it/openapi/AbstractInputStreamTest.java
{ "start": 307, "end": 1992 }
class ____ extends AbstractTest { protected static final String APPLICATION_OCTET_STREAM = "application/octet-stream"; protected void testServiceInputStreamRequest(String path, String expectedContentType) throws IOException { File f = tempFile(); byte[] responseFile = RestAssured .with().body(f) .and() .with().contentType(APPLICATION_OCTET_STREAM) .when() .post(path) .then() .header("Content-Type", Matchers.startsWith(APPLICATION_OCTET_STREAM)) .extract().asByteArray(); Assertions.assertEquals(Files.readAllBytes(f.toPath()).length, responseFile.length); } protected void testServiceInputStreamResponse(String path, String expectedResponseType) throws UnsupportedEncodingException, IOException { // Service File f = tempFile(); String filename = URLEncoder.encode(f.getAbsoluteFile().toString(), "UTF-8"); byte[] responseFile = RestAssured .when() .get(path + "/" + filename) .then() .header("Content-Type", Matchers.startsWith(expectedResponseType)) .and() .extract().asByteArray(); Assertions.assertEquals(Files.readAllBytes(f.toPath()).length, responseFile.length); } private File tempFile() { try { java.nio.file.Path createTempFile = Files.createTempFile("", ""); return createTempFile.toFile(); } catch (IOException ex) { throw new RuntimeException(ex); } } }
AbstractInputStreamTest
java
apache__maven
api/maven-api-core/src/main/java/org/apache/maven/api/Toolchain.java
{ "start": 1112, "end": 2623 }
interface ____ users to define and configure various toolchains * that can be utilized by Maven during the build process. Toolchains can * include compilers, interpreters, and other tools that are necessary * for building a project in a specific environment.</p> * * <p>Toolchains are defined in the Maven toolchains.xml file and can be * referenced in the project's POM file. This allows for greater flexibility * and control over the build environment, enabling developers to specify * the exact versions of tools they wish to use.</p> * * <p> * Toolchains can be obtained through the {@link org.apache.maven.api.services.ToolchainManager ToolchainManager} * service. This service provides methods to retrieve and manage toolchains defined * in the Maven configuration. * </p> * * <p> * The following are key functionalities provided by the Toolchain interface:</p><ul> * <li>Access to the type of the toolchain (e.g., JDK, compiler).</li> * <li>Retrieval of the specific version of the toolchain.</li> * <li>Configuration of toolchain properties to match the project's requirements.</li> * </ul> * * <p>Example usage:</p> * <pre> * Toolchain toolchain = ...; // Obtain a Toolchain instance * String type = toolchain.getType(); // Get the type of the toolchain * String version = toolchain.getVersion(); // Get the version of the toolchain * </pre> * * * @since 4.0.0 * @see JavaToolchain * @see org.apache.maven.api.services.ToolchainManager */ @Experimental public
allows
java
google__error-prone
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
{ "start": 47719, "end": 48029 }
class ____ { @SuppressWarnings(value = "KeepMe") int BEST = 42; } """) .doTest(TestMode.AST_MATCH); } /** A {@link BugChecker} for testing. */ @BugPattern(name = "UpdateDoNotCallArgument", summary = "", severity = ERROR) public static final
Test
java
google__guava
guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/ListenableFuture.java
{ "start": 2806, "end": 2944 }
interface ____<T extends @Nullable Object, V extends @Nullable Object> { V onInvoke(T p0); } @JsFunction
IThenOnFulfilledCallbackFn
java
micronaut-projects__micronaut-core
router/src/main/java/io/micronaut/web/router/version/RoutesVersioningConfiguration.java
{ "start": 1193, "end": 2327 }
class ____ implements Toggleable { /** * The configuration property. */ public static final String PREFIX = "micronaut.router.versioning"; private static final boolean DEFAULT_ENABLED = false; private boolean enabled = DEFAULT_ENABLED; private String defaultVersion; /** * @param enabled Enables the version based route matches filtering. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * @return {@code true} if version based matches filtering is enabled. */ @Override public boolean isEnabled() { return enabled; } /** * @return The version to use if none can be resolved */ public Optional<String> getDefaultVersion() { return Optional.ofNullable(defaultVersion); } /** * Sets the version to use if the version cannot be resolved. Default value (null). * * @param defaultVersion The default version */ public void setDefaultVersion(@Nullable String defaultVersion) { this.defaultVersion = defaultVersion; } }
RoutesVersioningConfiguration
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng6090CIFriendlyTest.java
{ "start": 1273, "end": 3719 }
class ____ extends AbstractMavenIntegrationTestCase { public MavenITmng6090CIFriendlyTest() { // The first version which contains the fix for the MNG-issue. // TODO: Think about it! super(); } /** * Check that the resulting run will not fail in case * of defining the property via command line and * install the projects and afterwards just build * a part of the whole reactor. * * @throws Exception in case of failure */ @Test public void testitShouldResolveTheDependenciesWithoutBuildConsumer() throws Exception { File testDir = extractResources("/mng-6090-ci-friendly"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.addCliArgument("-Drevision=1.2"); verifier.addCliArgument("-Dmaven.consumer.pom=false"); verifier.setLogFileName("install-log.txt"); verifier.addCliArguments("clean", "package"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.addCliArgument("-Drevision=1.2"); verifier.addCliArgument("-pl"); verifier.addCliArgument("module-3"); verifier.addCliArgument("package"); verifier.execute(); verifier.verifyErrorFreeLog(); } @Test public void testitShouldResolveTheDependenciesWithBuildConsumer() throws Exception { File testDir = extractResources("/mng-6090-ci-friendly"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.setForkJvm(true); // TODO: why? verifier.addCliArgument("-Drevision=1.2"); verifier.addCliArgument("-Dmaven.consumer.pom=true"); verifier.setLogFileName("install-log.txt"); verifier.addCliArguments("clean", "package"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.setForkJvm(true); // TODO: why? verifier.addCliArgument("-Drevision=1.2"); verifier.addCliArgument("-pl"); verifier.addCliArgument("module-3"); verifier.addCliArgument("package"); verifier.execute(); verifier.verifyErrorFreeLog(); } }
MavenITmng6090CIFriendlyTest
java
apache__rocketmq
proxy/src/main/java/org/apache/rocketmq/proxy/processor/channel/ChannelProtocolType.java
{ "start": 864, "end": 1153 }
enum ____ { UNKNOWN("unknown"), GRPC_V2("grpc_v2"), GRPC_V1("grpc_v1"), REMOTING("remoting"); private final String name; ChannelProtocolType(String name) { this.name = name; } public String getName() { return name; } }
ChannelProtocolType
java
grpc__grpc-java
examples/example-jwt-auth/src/main/java/io/grpc/examples/jwtauth/JwtCredential.java
{ "start": 1024, "end": 2070 }
class ____ extends CallCredentials { private final String subject; JwtCredential(String subject) { this.subject = subject; } @Override public void applyRequestMetadata(final RequestInfo requestInfo, final Executor executor, final MetadataApplier metadataApplier) { // Make a JWT compact serialized string. // This example omits setting the expiration, but a real application should do it. final String jwt = Jwts.builder() .setSubject(subject) .signWith(SignatureAlgorithm.HS256, Constant.JWT_SIGNING_KEY) .compact(); executor.execute(new Runnable() { @Override public void run() { try { Metadata headers = new Metadata(); headers.put(Constant.AUTHORIZATION_METADATA_KEY, String.format("%s %s", Constant.BEARER_TYPE, jwt)); metadataApplier.apply(headers); } catch (Throwable e) { metadataApplier.fail(Status.UNAUTHENTICATED.withCause(e)); } } }); } }
JwtCredential
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/polymorphism/BidirectionalOneToOnePolymorphismTest.java
{ "start": 3491, "end": 3866 }
class ____ { @Id private Integer id; @OneToOne(mappedBy = "level2") private Level3 level3; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Level3 getLevel3() { return level3; } public void setLevel3(Level3 level3) { this.level3 = level3; } } @Entity(name = "DerivedLevel2") static
Level2
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/sql/FunctionITCase.java
{ "start": 79729, "end": 80175 }
class ____ extends TableFunction<Object> { @FunctionHint( input = {@DataTypeHint("STRING"), @DataTypeHint("STRING")}, output = @DataTypeHint("STRING"), argumentNames = {"in1", "in2"}) public void eval(String arg1, String arg2) { collect(arg1 + ", " + arg2); } } /** Function that returns a string or integer. */ public static
NamedArgumentsTableFunction
java
quarkusio__quarkus
devtools/maven/src/main/java/io/quarkus/maven/TrackConfigChangesMojo.java
{ "start": 1742, "end": 9556 }
class ____ extends QuarkusBootstrapMojo { /** * Skip the execution of this mojo */ @Parameter(defaultValue = "false", property = "quarkus.track-config-changes.skip") boolean skip = false; @Parameter(property = "launchMode") String mode; @Parameter(property = "quarkus.track-config-changes.outputDirectory", defaultValue = "${project.build.directory}") File outputDirectory; @Parameter(property = "quarkus.track-config-changes.outputFile", required = false) File outputFile; @Parameter(property = "quarkus.recorded-build-config.directory", defaultValue = "${basedir}/.quarkus") File recordedBuildConfigDirectory; @Parameter(property = "quarkus.recorded-build-config.file", required = false) String recordedBuildConfigFile; /** * Whether to dump the current build configuration in case the configuration from the previous build isn't found */ @Parameter(defaultValue = "false", property = "quarkus.track-config-changes.dump-current-when-recorded-unavailable") boolean dumpCurrentWhenRecordedUnavailable; /** * Whether to dump Quarkus application dependencies along with their checksums */ @Parameter(defaultValue = "true", property = "quarkus.track-config-changes.dump-dependencies") boolean dumpDependencies; /** * Dependency dump file */ @Parameter(property = "quarkus.track-config-changes.dependencies-file") File dependenciesFile; @Override protected boolean beforeExecute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping config dump"); return false; } return true; } @Override protected void doExecute() throws MojoExecutionException, MojoFailureException { final String lifecyclePhase = mojoExecution.getLifecyclePhase(); if (mode == null) { if (lifecyclePhase == null) { mode = "NORMAL"; } else { mode = lifecyclePhase.contains("test") ? "TEST" : "NORMAL"; } } final LaunchMode launchMode = LaunchMode.valueOf(mode); if (getLog().isDebugEnabled()) { getLog().debug("Bootstrapping Quarkus application in mode " + launchMode); } final Path compareFile = resolvePreviousBuildConfigDump(launchMode); final boolean prevConfigExists = Files.exists(compareFile); if (!prevConfigExists && !dumpCurrentWhenRecordedUnavailable && !dumpDependencies) { getLog().info("Config dump from the previous build does not exist at " + compareFile); return; } CuratedApplication curatedApplication = null; QuarkusClassLoader deploymentClassLoader = null; final ClassLoader originalCl = Thread.currentThread().getContextClassLoader(); final boolean clearNativeEnabledSystemProperty = setNativeEnabledIfNativeProfileEnabled(); try { curatedApplication = bootstrapApplication(launchMode); if (prevConfigExists || dumpCurrentWhenRecordedUnavailable) { final Path targetFile = getOutputFile(outputFile, launchMode.getDefaultProfile(), "-config-check"); Properties compareProps = new Properties(); if (prevConfigExists) { try (BufferedReader reader = Files.newBufferedReader(compareFile)) { compareProps.load(reader); } catch (IOException e) { throw new RuntimeException("Failed to read " + compareFile, e); } } deploymentClassLoader = curatedApplication.createDeploymentClassLoader(); Thread.currentThread().setContextClassLoader(deploymentClassLoader); final Class<?> codeGenerator = deploymentClassLoader.loadClass("io.quarkus.deployment.CodeGenerator"); final Method dumpConfig = codeGenerator.getMethod("dumpCurrentConfigValues", ApplicationModel.class, String.class, Properties.class, QuarkusClassLoader.class, Properties.class, Path.class); dumpConfig.invoke(null, curatedApplication.getApplicationModel(), launchMode.name(), getBuildSystemProperties(true), deploymentClassLoader, compareProps, targetFile); } if (dumpDependencies) { final List<Path> deps = new ArrayList<>(); for (var d : curatedApplication.getApplicationModel().getDependencies(DependencyFlags.DEPLOYMENT_CP)) { for (Path resolvedPath : d.getResolvedPaths()) { deps.add(resolvedPath.toAbsolutePath()); } } Collections.sort(deps); final Path targetFile = getOutputFile(dependenciesFile, launchMode.getDefaultProfile(), "-dependencies.txt"); Files.createDirectories(targetFile.getParent()); try (BufferedWriter writer = Files.newBufferedWriter(targetFile)) { for (var dep : deps) { writer.write(dep.toString()); writer.newLine(); } } } } catch (Exception any) { throw new MojoExecutionException("Failed to bootstrap Quarkus application", any); } finally { if (clearNativeEnabledSystemProperty) { System.clearProperty("quarkus.native.enabled"); } Thread.currentThread().setContextClassLoader(originalCl); if (deploymentClassLoader != null) { deploymentClassLoader.close(); } } } private Path resolvePreviousBuildConfigDump(LaunchMode launchMode) { final Path previousBuildConfigDump = this.recordedBuildConfigFile == null ? null : Path.of(this.recordedBuildConfigFile); if (previousBuildConfigDump == null) { return recordedBuildConfigDirectory.toPath() .resolve("quarkus-" + launchMode.getDefaultProfile() + "-config-dump"); } if (previousBuildConfigDump.isAbsolute()) { return previousBuildConfigDump; } return recordedBuildConfigDirectory.toPath().resolve(previousBuildConfigDump); } private Path getOutputFile(File outputFile, String profile, String fileNameSuffix) { if (outputFile == null) { return outputDirectory.toPath().resolve("quarkus-" + profile + fileNameSuffix); } if (outputFile.isAbsolute()) { return outputFile.toPath(); } return outputDirectory.toPath().resolve(outputFile.toPath()); } private static void updateChecksum(Checksum checksum, Iterable<Path> pc) throws IOException { for (var path : sort(pc)) { if (Files.isDirectory(path)) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) { updateChecksum(checksum, stream); } } else { checksum.update(Files.readAllBytes(path)); } } } private static Iterable<Path> sort(Iterable<Path> original) { var i = original.iterator(); if (!i.hasNext()) { return List.of(); } var o = i.next(); if (!i.hasNext()) { return List.of(o); } final List<Path> sorted = new ArrayList<>(); sorted.add(o); while (i.hasNext()) { sorted.add(i.next()); } Collections.sort(sorted); return sorted; } }
TrackConfigChangesMojo
java
apache__maven
compat/maven-model-builder/src/test/java/org/apache/maven/model/interpolation/reflection/ReflectionValueExtractorTest.java
{ "start": 16395, "end": 16657 }
class ____ { private String connection; public void setConnection(String connection) { this.connection = connection; } public String getConnection() { return connection; } } public static
Scm
java
spring-projects__spring-security
oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtEncoder.java
{ "start": 6268, "end": 15619 }
class ____ throw an exception. * @since 6.5 */ public void setJwkSelector(Converter<List<JWK>, JWK> jwkSelector) { Assert.notNull(jwkSelector, "jwkSelector cannot be null"); this.jwkSelector = jwkSelector; } @Override public Jwt encode(JwtEncoderParameters parameters) throws JwtEncodingException { Assert.notNull(parameters, "parameters cannot be null"); JwsHeader headers = parameters.getJwsHeader(); if (headers == null) { headers = this.defaultJwsHeader; } JwtClaimsSet claims = parameters.getClaims(); JWK jwk = selectJwk(headers); headers = addKeyIdentifierHeadersIfNecessary(headers, jwk); String jws = serialize(headers, claims, jwk); return new Jwt(jws, claims.getIssuedAt(), claims.getExpiresAt(), headers.getHeaders(), claims.getClaims()); } private JWK selectJwk(JwsHeader headers) { List<JWK> jwks; try { JWKSelector jwkSelector = new JWKSelector(createJwkMatcher(headers)); jwks = this.jwkSource.get(jwkSelector, null); } catch (Exception ex) { throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key -> " + ex.getMessage()), ex); } if (jwks.isEmpty()) { throw new JwtEncodingException( String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key")); } if (jwks.size() == 1) { return jwks.get(0); } return this.jwkSelector.convert(jwks); } private String serialize(JwsHeader headers, JwtClaimsSet claims, JWK jwk) { JWSHeader jwsHeader = convert(headers); JWTClaimsSet jwtClaimsSet = convert(claims); JWSSigner jwsSigner = this.jwsSigners.computeIfAbsent(jwk, NimbusJwtEncoder::createSigner); SignedJWT signedJwt = new SignedJWT(jwsHeader, jwtClaimsSet); try { signedJwt.sign(jwsSigner); } catch (JOSEException ex) { throw new JwtEncodingException( String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to sign the JWT -> " + ex.getMessage()), ex); } return signedJwt.serialize(); } private static JWKMatcher createJwkMatcher(JwsHeader headers) { JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(headers.getAlgorithm().getName()); if (JWSAlgorithm.Family.RSA.contains(jwsAlgorithm) || JWSAlgorithm.Family.EC.contains(jwsAlgorithm)) { // @formatter:off return new JWKMatcher.Builder() .keyType(KeyType.forAlgorithm(jwsAlgorithm)) .keyID(headers.getKeyId()) .keyUses(KeyUse.SIGNATURE, null) .algorithms(jwsAlgorithm, null) .x509CertSHA256Thumbprint(Base64URL.from(headers.getX509SHA256Thumbprint())) .build(); // @formatter:on } else if (JWSAlgorithm.Family.HMAC_SHA.contains(jwsAlgorithm)) { // @formatter:off return new JWKMatcher.Builder() .keyType(KeyType.forAlgorithm(jwsAlgorithm)) .keyID(headers.getKeyId()) .privateOnly(true) .algorithms(jwsAlgorithm, null) .build(); // @formatter:on } return null; } private static JwsHeader addKeyIdentifierHeadersIfNecessary(JwsHeader headers, JWK jwk) { // Check if headers have already been added if (StringUtils.hasText(headers.getKeyId()) && StringUtils.hasText(headers.getX509SHA256Thumbprint())) { return headers; } // Check if headers can be added from JWK if (!StringUtils.hasText(jwk.getKeyID()) && jwk.getX509CertSHA256Thumbprint() == null) { return headers; } JwsHeader.Builder headersBuilder = JwsHeader.from(headers); if (!StringUtils.hasText(headers.getKeyId()) && StringUtils.hasText(jwk.getKeyID())) { headersBuilder.keyId(jwk.getKeyID()); } if (!StringUtils.hasText(headers.getX509SHA256Thumbprint()) && jwk.getX509CertSHA256Thumbprint() != null) { headersBuilder.x509SHA256Thumbprint(jwk.getX509CertSHA256Thumbprint().toString()); } return headersBuilder.build(); } private static JWSSigner createSigner(JWK jwk) { try { return JWS_SIGNER_FACTORY.createJWSSigner(jwk); } catch (JOSEException ex) { throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to create a JWS Signer -> " + ex.getMessage()), ex); } } private static JWSHeader convert(JwsHeader headers) { JWSHeader.Builder builder = new JWSHeader.Builder(JWSAlgorithm.parse(headers.getAlgorithm().getName())); if (headers.getJwkSetUrl() != null) { builder.jwkURL(convertAsURI(JoseHeaderNames.JKU, headers.getJwkSetUrl())); } Map<String, Object> jwk = headers.getJwk(); if (!CollectionUtils.isEmpty(jwk)) { try { builder.jwk(JWK.parse(jwk)); } catch (Exception ex) { throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Unable to convert '" + JoseHeaderNames.JWK + "' JOSE header"), ex); } } String keyId = headers.getKeyId(); if (StringUtils.hasText(keyId)) { builder.keyID(keyId); } if (headers.getX509Url() != null) { builder.x509CertURL(convertAsURI(JoseHeaderNames.X5U, headers.getX509Url())); } List<String> x509CertificateChain = headers.getX509CertificateChain(); if (!CollectionUtils.isEmpty(x509CertificateChain)) { List<Base64> x5cList = new ArrayList<>(); x509CertificateChain.forEach((x5c) -> x5cList.add(new Base64(x5c))); if (!x5cList.isEmpty()) { builder.x509CertChain(x5cList); } } String x509SHA1Thumbprint = headers.getX509SHA1Thumbprint(); if (StringUtils.hasText(x509SHA1Thumbprint)) { builder.x509CertThumbprint(new Base64URL(x509SHA1Thumbprint)); } String x509SHA256Thumbprint = headers.getX509SHA256Thumbprint(); if (StringUtils.hasText(x509SHA256Thumbprint)) { builder.x509CertSHA256Thumbprint(new Base64URL(x509SHA256Thumbprint)); } String type = headers.getType(); if (StringUtils.hasText(type)) { builder.type(new JOSEObjectType(type)); } String contentType = headers.getContentType(); if (StringUtils.hasText(contentType)) { builder.contentType(contentType); } Set<String> critical = headers.getCritical(); if (!CollectionUtils.isEmpty(critical)) { builder.criticalParams(critical); } Map<String, Object> customHeaders = new HashMap<>(); headers.getHeaders().forEach((name, value) -> { if (!JWSHeader.getRegisteredParameterNames().contains(name)) { customHeaders.put(name, value); } }); if (!customHeaders.isEmpty()) { builder.customParams(customHeaders); } return builder.build(); } private static JWTClaimsSet convert(JwtClaimsSet claims) { JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); // NOTE: The value of the 'iss' claim is a String or URL (StringOrURI). Object issuer = claims.getClaim(JwtClaimNames.ISS); if (issuer != null) { builder.issuer(issuer.toString()); } String subject = claims.getSubject(); if (StringUtils.hasText(subject)) { builder.subject(subject); } List<String> audience = claims.getAudience(); if (!CollectionUtils.isEmpty(audience)) { builder.audience(audience); } Instant expiresAt = claims.getExpiresAt(); if (expiresAt != null) { builder.expirationTime(Date.from(expiresAt)); } Instant notBefore = claims.getNotBefore(); if (notBefore != null) { builder.notBeforeTime(Date.from(notBefore)); } Instant issuedAt = claims.getIssuedAt(); if (issuedAt != null) { builder.issueTime(Date.from(issuedAt)); } String jwtId = claims.getId(); if (StringUtils.hasText(jwtId)) { builder.jwtID(jwtId); } Map<String, Object> customClaims = new HashMap<>(); claims.getClaims().forEach((name, value) -> { if (!JWTClaimsSet.getRegisteredNames().contains(name)) { customClaims.put(name, value); } }); if (!customClaims.isEmpty()) { customClaims.forEach(builder::claim); } return builder.build(); } private static URI convertAsURI(String header, URL url) { try { return url.toURI(); } catch (Exception ex) { throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Unable to convert '" + header + "' JOSE header to a URI"), ex); } } /** * Creates a builder for constructing a {@link NimbusJwtEncoder} using the provided * @param publicKey the {@link RSAPublicKey} and @Param privateKey the * {@link RSAPrivateKey} to use for signing JWTs * @return a {@link RsaKeyPairJwtEncoderBuilder} * @since 7.0 */ public static RsaKeyPairJwtEncoderBuilder withKeyPair(RSAPublicKey publicKey, RSAPrivateKey privateKey) { return new RsaKeyPairJwtEncoderBuilder(publicKey, privateKey); } /** * Creates a builder for constructing a {@link NimbusJwtEncoder} using the provided * @param publicKey the {@link ECPublicKey} and @param privateKey the * {@link ECPrivateKey} to use for signing JWTs * @return a {@link EcKeyPairJwtEncoderBuilder} * @since 7.0 */ public static EcKeyPairJwtEncoderBuilder withKeyPair(ECPublicKey publicKey, ECPrivateKey privateKey) { return new EcKeyPairJwtEncoderBuilder(publicKey, privateKey); } /** * Creates a builder for constructing a {@link NimbusJwtEncoder} using the provided * @param secretKey * @return a {@link SecretKeyJwtEncoderBuilder} for configuring the {@link JWK} * @since 7.0 */ public static SecretKeyJwtEncoderBuilder withSecretKey(SecretKey secretKey) { return new SecretKeyJwtEncoderBuilder(secretKey); } /** * A builder for creating {@link NimbusJwtEncoder} instances configured with a * {@link SecretKey}. * * @since 7.0 */ public static final
with
java
quarkusio__quarkus
extensions/cache/runtime/src/main/java/io/quarkus/cache/runtime/caffeine/CaffeineComputationThrowable.java
{ "start": 56, "end": 133 }
class ____ used to prevent Caffeine from logging unwanted warnings. */ public
is
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/ECAdmin.java
{ "start": 2156, "end": 3558 }
class ____ extends Configured implements Tool { public static final String NAME = "ec"; public static void main(String[] args) throws Exception { final ECAdmin admin = new ECAdmin(new Configuration()); int res = ToolRunner.run(admin, args); System.exit(res); } public ECAdmin(Configuration conf) { super(conf); } @Override public int run(String[] args) throws Exception { if (args.length == 0) { AdminHelper.printUsage(false, NAME, COMMANDS); ToolRunner.printGenericCommandUsage(System.err); return 1; } final AdminHelper.Command command = AdminHelper.determineCommand(args[0], COMMANDS); if (command == null) { System.err.println("Can't understand command '" + args[0] + "'"); if (!args[0].startsWith("-")) { System.err.println("Command names must start with dashes."); } AdminHelper.printUsage(false, NAME, COMMANDS); ToolRunner.printGenericCommandUsage(System.err); return 1; } final List<String> argsList = new LinkedList<>(); argsList.addAll(Arrays.asList(args).subList(1, args.length)); try { return command.run(getConf(), argsList); } catch (IllegalArgumentException e) { System.err.println(AdminHelper.prettifyException(e)); return -1; } } /** Command to list the set of enabled erasure coding policies. */ private static
ECAdmin
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/asyncprocessing/operators/AbstractAsyncRunnableStreamOperatorTest.java
{ "start": 3287, "end": 22180 }
class ____ { protected AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> createTestHarness( int maxParalelism, int numSubtasks, int subtaskIndex, TestOperator testOperator) throws Exception { AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = AsyncOneInputStreamOperatorTestHarness.create( testOperator, maxParalelism, numSubtasks, subtaskIndex); testHarness.setStateBackend(buildAsyncStateBackend(new HashMapStateBackend())); return testHarness; } protected AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> createTestHarness( int maxParalelism, int numSubtasks, int subtaskIndex, ElementOrder elementOrder) throws Exception { TestOperator testOperator = new TestOperator(new TestKeySelector(), elementOrder); AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = AsyncOneInputStreamOperatorTestHarness.create( testOperator, maxParalelism, numSubtasks, subtaskIndex); testHarness.setStateBackend(buildAsyncStateBackend(new HashMapStateBackend())); return testHarness; } @Test void testCreateAsyncExecutionController() throws Exception { try (AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = createTestHarness(128, 1, 0, ElementOrder.RECORD_ORDER)) { testHarness.open(); assertThat(testHarness.getOperator()) .isInstanceOf(AbstractAsyncRunnableStreamOperator.class); AsyncExecutionController<?, ?> aec = ((AbstractAsyncRunnableStreamOperator) testHarness.getOperator()) .getAsyncExecutionController(); assertThat(aec).isNotNull(); assertThat(((MailboxExecutorImpl) aec.getMailboxExecutor()).getPriority()) .isGreaterThan(MIN_PRIORITY); assertThat(aec.getAsyncExecutor()).isNotNull(); } } @Test void testRecordProcessorWithFirstRequestOrder() throws Exception { try (AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = createTestHarness(128, 1, 0, ElementOrder.FIRST_REQUEST_ORDER)) { testHarness.open(); TestOperator testOperator = (TestOperator) testHarness.getOperator(); CompletableFuture<Void> future = testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(5, "5"))); Thread.sleep(1000); assertThat(testOperator.getProcessed()).isEqualTo(1); assertThat(testOperator.getCurrentProcessingContext().getReferenceCount()).isEqualTo(1); // Proceed processing testOperator.proceed(); future.get(); testHarness.drainAsyncRequests(); assertThat(testOperator.getCurrentProcessingContext().getReferenceCount()).isEqualTo(0); } } @Test void testRecordProcessorWithRecordOrder() throws Exception { try (AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = createTestHarness(128, 1, 0, ElementOrder.RECORD_ORDER)) { testHarness.open(); TestOperator testOperator = (TestOperator) testHarness.getOperator(); CompletableFuture<Void> future = testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(5, "5"))); Thread.sleep(1000); assertThat(testOperator.getProcessed()).isEqualTo(1); // Why greater than 1: +1 when enter the processor; +1 when handle the SYNC_POINT assertThat(testOperator.getCurrentProcessingContext().getReferenceCount()) .isGreaterThan(1); // Proceed processing testOperator.proceed(); future.get(); testHarness.drainAsyncRequests(); assertThat(testOperator.getCurrentProcessingContext().getReferenceCount()).isEqualTo(0); } } @Test void testAsyncProcessWithKey() throws Exception { TestOperatorWithAsyncProcessWithKey testOperator = new TestOperatorWithAsyncProcessWithKey( new TestKeySelector(), ElementOrder.RECORD_ORDER); AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = AsyncOneInputStreamOperatorTestHarness.create(testOperator, 128, 1, 0); testHarness.setStateBackend(buildAsyncStateBackend(new HashMapStateBackend())); try { testHarness.open(); CompletableFuture<Void> future = testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(5, "5"))); Thread.sleep(1000); assertThat(testOperator.getProcessed()).isEqualTo(0); // Why greater than 1: +1 when handle the SYNC_POINT; then accept +1 assertThat(testOperator.getCurrentProcessingContext().getReferenceCount()) .isGreaterThan(1); // Proceed processing testOperator.proceed(); future.get(); assertThat(testOperator.getCurrentProcessingContext().getReferenceCount()).isEqualTo(0); // We don't have the mailbox executor actually running, so the new context is blocked // and never triggered. assertThat(testOperator.getProcessed()).isEqualTo(1); } finally { testHarness.close(); } } @Test void testDirectAsyncProcess() throws Exception { TestOperatorWithDirectAsyncProcess testOperator = new TestOperatorWithDirectAsyncProcess( new TestKeySelector(), ElementOrder.RECORD_ORDER); AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = AsyncOneInputStreamOperatorTestHarness.create(testOperator, 128, 1, 0); testHarness.setStateBackend(buildAsyncStateBackend(new HashMapStateBackend())); try { testHarness.open(); CompletableFuture<Void> future = testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(5, "5"))); testHarness.drainAsyncRequests(); assertThat(testOperator.getCurrentProcessingContext().getReferenceCount()).isEqualTo(0); assertThat(testOperator.getProcessed()).isEqualTo(1); } finally { testHarness.close(); } } @Test void testManyAsyncProcessWithKey() throws Exception { // This test is for verifying StateExecutionController could avoid deadlock for derived // processing requests. int requests = ExecutionOptions.ASYNC_STATE_TOTAL_BUFFER_SIZE.defaultValue() + 1; TestOperatorWithMultipleDirectAsyncProcess testOperator = new TestOperatorWithMultipleDirectAsyncProcess( new TestKeySelector(), ElementOrder.RECORD_ORDER, requests); AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = AsyncOneInputStreamOperatorTestHarness.create(testOperator, 128, 1, 0); testHarness.setStateBackend(buildAsyncStateBackend(new HashMapStateBackend())); try { testHarness.open(); // Repeat twice testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(5, "5"))); CompletableFuture<Void> future = testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(5, "5"))); testHarness.drainAsyncRequests(); // If the AEC could avoid deadlock, there should not be any timeout exception. future.get(10000, TimeUnit.MILLISECONDS); testOperator.getLastProcessedFuture().get(10000, TimeUnit.MILLISECONDS); assertThat(testOperator.getProcessed()).isEqualTo(requests * 2); // This ensures the order is correct according to the priority in AEC. assertThat(testOperator.getProcessedOrders()) .isEqualTo(testOperator.getExpectedProcessedOrders()); } finally { testHarness.close(); } } @Test void testCheckpointDrain() throws Exception { try (AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = createTestHarness(128, 1, 0, ElementOrder.RECORD_ORDER)) { testHarness.open(); SimpleAsyncExecutionController<String> asyncExecutionController = (SimpleAsyncExecutionController) ((AbstractAsyncRunnableStreamOperator) testHarness.getOperator()) .getAsyncExecutionController(); ((AbstractAsyncRunnableStreamOperator<String>) testHarness.getOperator()) .setAsyncKeyedContextElement( new StreamRecord<>(Tuple2.of(5, "5")), new TestKeySelector()); ((AbstractAsyncRunnableStreamOperator<String>) testHarness.getOperator()) .asyncProcess( () -> { return null; }); ((AbstractAsyncRunnableStreamOperator<String>) testHarness.getOperator()) .postProcessElement(); assertThat(asyncExecutionController.getInFlightRecordNum()).isEqualTo(1); testHarness.drainAsyncRequests(); assertThat(asyncExecutionController.getInFlightRecordNum()).isEqualTo(0); } } @Test void testNonRecordProcess() throws Exception { try (AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = createTestHarness(128, 1, 0, ElementOrder.RECORD_ORDER)) { testHarness.open(); TestOperator testOperator = (TestOperator) testHarness.getOperator(); testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(5, "5"))); CompletableFuture<Void> future = testHarness.processLatencyMarkerInternal( new LatencyMarker(1234, new OperatorID(), 0)); Thread.sleep(1000); assertThat(testOperator.getProcessed()).isEqualTo(1); assertThat(testOperator.getCurrentProcessingContext().getReferenceCount()) .isGreaterThan(1); assertThat(testOperator.getLatencyProcessed()).isEqualTo(0); // Proceed processing testOperator.proceed(); future.get(); assertThat(testOperator.getCurrentProcessingContext().getReferenceCount()).isEqualTo(0); assertThat(testOperator.getLatencyProcessed()).isEqualTo(1); } } @Test void testWatermark() throws Exception { TestOperatorWithAsyncProcessTimer testOperator = new TestOperatorWithAsyncProcessTimer( new TestKeySelector(), ElementOrder.RECORD_ORDER); try (AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = createTestHarness(128, 1, 0, testOperator)) { testHarness.open(); ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>(); testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(1, "1"))); testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(1, "3"))); testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(1, "6"))); testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(1, "9"))); testHarness.processWatermark(10L); expectedOutput.add(new Watermark(10L)); TestHarnessUtil.assertOutputEquals( "Output was not correct", expectedOutput, testHarness.getOutput()); } } @Test void testWatermarkHooks() throws Exception { KeySelector<Long, Integer> dummyKeySelector = l -> 0; final WatermarkTestingOperator testOperator = new WatermarkTestingOperator(dummyKeySelector, dummyKeySelector); AtomicInteger counter = new AtomicInteger(0); testOperator.setPreProcessFunction( (watermark) -> { testOperator.asyncProcessWithKey( 1L, () -> { assertThat(testOperator.getCurrentKey()).isEqualTo(1L); testOperator.output(watermark.getTimestamp() + 1000L); }); if (counter.incrementAndGet() % 2 == 0) { return null; } else { return new Watermark(watermark.getTimestamp() + 1L); } }); testOperator.setPostProcessFunction( (watermark) -> { testOperator.output(watermark.getTimestamp() + 100L); }); ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>(); try (AsyncKeyedTwoInputStreamOperatorTestHarness<Integer, Long, Long, Long> testHarness = AsyncKeyedTwoInputStreamOperatorTestHarness.create( testOperator, dummyKeySelector, dummyKeySelector, BasicTypeInfo.INT_TYPE_INFO, 1, 1, 0)) { testHarness.setup(); testHarness.open(); testHarness.processElement1(1L, 1L); testHarness.processElement1(3L, 3L); testHarness.processElement1(4L, 4L); testHarness.processWatermark1(new Watermark(2L)); testHarness.processWatermark2(new Watermark(2L)); expectedOutput.add(new StreamRecord<>(1002L)); expectedOutput.add(new StreamRecord<>(1L)); expectedOutput.add(new StreamRecord<>(3L)); expectedOutput.add(new StreamRecord<>(103L)); expectedOutput.add(new Watermark(3L)); testHarness.processWatermark1(new Watermark(4L)); testHarness.processWatermark2(new Watermark(4L)); expectedOutput.add(new StreamRecord<>(1004L)); testHarness.processWatermark1(new Watermark(5L)); testHarness.processWatermark2(new Watermark(5L)); expectedOutput.add(new StreamRecord<>(1005L)); expectedOutput.add(new StreamRecord<>(4L)); expectedOutput.add(new StreamRecord<>(106L)); expectedOutput.add(new Watermark(6L)); TestHarnessUtil.assertOutputEquals( "Output was not correct", expectedOutput, testHarness.getOutput()); } } @Test void testWatermarkStatus() throws Exception { try (AsyncOneInputStreamOperatorTestHarness<Tuple2<Integer, String>, String> testHarness = createTestHarness(128, 1, 0, ElementOrder.RECORD_ORDER)) { testHarness.open(); TestOperator testOperator = (TestOperator) testHarness.getOperator(); ThrowingConsumer<StreamRecord<Tuple2<Integer, String>>, Exception> processor = RecordProcessorUtils.getRecordProcessor(testOperator); testHarness.processElementInternal(new StreamRecord<>(Tuple2.of(5, "5"))); testHarness.processWatermarkInternal(new Watermark(205L)); CompletableFuture<Void> future = testHarness.processWatermarkStatusInternal(WatermarkStatus.IDLE); Thread.sleep(1000); assertThat(testOperator.getProcessed()).isEqualTo(1); assertThat(testOperator.getCurrentProcessingContext().getReferenceCount()) .isGreaterThan(1); assertThat(testOperator.watermarkIndex).isEqualTo(-1); assertThat(testOperator.watermarkStatus.isIdle()).isTrue(); // Proceed processing testOperator.proceed(); future.get(); assertThat(testOperator.getCurrentProcessingContext().getReferenceCount()).isEqualTo(0); assertThat(testOperator.watermarkStatus.isActive()).isFalse(); assertThat(testHarness.getOutput()) .containsExactly(new Watermark(205L), WatermarkStatus.IDLE); } } @Test void testIdleWatermarkHandling() throws Exception { KeySelector<Long, Integer> dummyKeySelector = l -> 0; final WatermarkTestingOperator testOperator = new WatermarkTestingOperator(dummyKeySelector, dummyKeySelector); ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>(); try (AsyncKeyedTwoInputStreamOperatorTestHarness<Integer, Long, Long, Long> testHarness = AsyncKeyedTwoInputStreamOperatorTestHarness.create( testOperator, dummyKeySelector, dummyKeySelector, BasicTypeInfo.INT_TYPE_INFO, 1, 1, 0)) { testHarness.setup(); testHarness.open(); testHarness.processElement1(1L, 1L); testHarness.processElement1(3L, 3L); testHarness.processElement1(4L, 4L); testHarness.processWatermark1(new Watermark(1L)); assertThat(testHarness.getOutput()).isEmpty(); testHarness.processWatermarkStatus2(WatermarkStatus.IDLE); expectedOutput.add(new StreamRecord<>(1L)); expectedOutput.add(new Watermark(1L)); TestHarnessUtil.assertOutputEquals( "Output was not correct", expectedOutput, testHarness.getOutput()); testHarness.processWatermark1(new Watermark(3L)); expectedOutput.add(new StreamRecord<>(3L)); expectedOutput.add(new Watermark(3L)); TestHarnessUtil.assertOutputEquals( "Output was not correct", expectedOutput, testHarness.getOutput()); testHarness.processWatermarkStatus2(WatermarkStatus.ACTIVE); // the other input is active now, we should not emit the watermark testHarness.processWatermark1(new Watermark(4L)); TestHarnessUtil.assertOutputEquals( "Output was not correct", expectedOutput, testHarness.getOutput()); } } /** A simple testing operator. */ private static
AbstractAsyncRunnableStreamOperatorTest
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ShouldNotBeSame.java
{ "start": 836, "end": 1287 }
class ____ extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldNotBeSame}</code>. * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldNotBeSame(Object actual) { return new ShouldNotBeSame(actual); } private ShouldNotBeSame(Object actual) { super("%nExpected not same: %s", actual); } }
ShouldNotBeSame
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/TaskStateManager.java
{ "start": 2438, "end": 2602 }
interface ____ offers the complementary method that provides access to previously saved * state of operator instances in the task for restore purposes. */ public
also
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/service/ServiceAccountToken.java
{ "start": 6113, "end": 7603 }
class ____ { private final ServiceAccountId accountId; private final String tokenName; public ServiceAccountTokenId(ServiceAccountId accountId, String tokenName) { this.accountId = Objects.requireNonNull(accountId, "service account ID cannot be null"); if (false == Validation.isValidServiceAccountTokenName(tokenName)) { throw new IllegalArgumentException(Validation.formatInvalidServiceTokenNameErrorMessage(tokenName)); } this.tokenName = Objects.requireNonNull(tokenName, "service account token name cannot be null"); } public ServiceAccountId getAccountId() { return accountId; } public String getTokenName() { return tokenName; } public String getQualifiedName() { return accountId.asPrincipal() + "/" + tokenName; } @Override public String toString() { return getQualifiedName(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ServiceAccountTokenId that = (ServiceAccountTokenId) o; return accountId.equals(that.accountId) && tokenName.equals(that.tokenName); } @Override public int hashCode() { return Objects.hash(accountId, tokenName); } } }
ServiceAccountTokenId
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerStdoutFileHeaders.java
{ "start": 1228, "end": 2214 }
class ____ implements RuntimeUntypedResponseMessageHeaders< EmptyRequestBody, TaskManagerMessageParameters> { private static final TaskManagerStdoutFileHeaders INSTANCE = new TaskManagerStdoutFileHeaders(); private static final String URL = String.format("/taskmanagers/:%s/stdout", TaskManagerIdPathParameter.KEY); private TaskManagerStdoutFileHeaders() {} @Override public Class<EmptyRequestBody> getRequestClass() { return EmptyRequestBody.class; } @Override public TaskManagerMessageParameters getUnresolvedMessageParameters() { return new TaskManagerMessageParameters(); } @Override public HttpMethodWrapper getHttpMethod() { return HttpMethodWrapper.GET; } @Override public String getTargetRestEndpointURL() { return URL; } public static TaskManagerStdoutFileHeaders getInstance() { return INSTANCE; } }
TaskManagerStdoutFileHeaders
java
apache__dubbo
dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscoveryTest.java
{ "start": 2051, "end": 7364 }
class ____ { private static String zookeeperConnectionAddress1, zookeeperConnectionAddress2; @Test public void testOnEvent() { try { String metadata_111 = "{\"app\":\"app1\",\"revision\":\"111\",\"services\":{" + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + "}}"; MetadataInfo metadataInfo = JsonUtils.toJavaObject(metadata_111, MetadataInfo.class); ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("app2")); zookeeperConnectionAddress1 = "multiple://127.0.0.1:2181?reference-registry=127.0.0.1:2181?enableEmptyProtection=false&child.a1=zookeeper://127.0.0.1:2181"; List<Object> urlsSameRevision = new ArrayList<>(); urlsSameRevision.add("127.0.0.1:20880?revision=111"); urlsSameRevision.add("127.0.0.2:20880?revision=111"); urlsSameRevision.add("127.0.0.3:20880?revision=111"); URL url = URL.valueOf(zookeeperConnectionAddress1); url.setScopeModel(applicationModel); MultipleServiceDiscovery multipleServiceDiscovery = new MultipleServiceDiscovery(url); Class<MultipleServiceDiscovery> multipleServiceDiscoveryClass = MultipleServiceDiscovery.class; Field serviceDiscoveries = multipleServiceDiscoveryClass.getDeclaredField("serviceDiscoveries"); serviceDiscoveries.setAccessible(true); ServiceDiscovery serviceDiscoveryMock = Mockito.mock(ServiceDiscovery.class); Mockito.when(serviceDiscoveryMock.getRemoteMetadata(Mockito.anyString(), Mockito.anyList())) .thenReturn(metadataInfo); serviceDiscoveries.set( multipleServiceDiscovery, Collections.singletonMap("child.a1", serviceDiscoveryMock)); MultipleServiceDiscovery.MultiServiceInstancesChangedListener listener = (MultipleServiceDiscovery.MultiServiceInstancesChangedListener) multipleServiceDiscovery.createListener(Sets.newHashSet("app1")); multipleServiceDiscovery.addServiceInstancesChangedListener(listener); MultipleServiceDiscovery.SingleServiceInstancesChangedListener singleServiceInstancesChangedListener = listener.getAndComputeIfAbsent("child.a1", (a1) -> null); Assert.notNull( singleServiceInstancesChangedListener, "singleServiceInstancesChangedListener can not be null"); singleServiceInstancesChangedListener.onEvent( new ServiceInstancesChangedEvent("app1", buildInstances(urlsSameRevision))); Mockito.verify(serviceDiscoveryMock, Mockito.times(1)) .getRemoteMetadata(Mockito.anyString(), Mockito.anyList()); Field serviceUrlsField = ServiceInstancesChangedListener.class.getDeclaredField("serviceUrls"); serviceUrlsField.setAccessible(true); Map<String, List<ServiceInstancesChangedListener.ProtocolServiceKeyWithUrls>> map = (Map<String, List<ServiceInstancesChangedListener.ProtocolServiceKeyWithUrls>>) serviceUrlsField.get(listener); Assert.assertTrue(!CollectionUtils.isEmptyMap(map), "url can not be empty"); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } static List<ServiceInstance> buildInstances(List<Object> rawURls) { List<ServiceInstance> instances = new ArrayList<>(); for (Object obj : rawURls) { String rawURL = (String) obj; DefaultServiceInstance instance = new DefaultServiceInstance(); final URL dubboUrl = URL.valueOf(rawURL); instance.setRawAddress(rawURL); instance.setHost(dubboUrl.getHost()); instance.setEnabled(true); instance.setHealthy(true); instance.setPort(dubboUrl.getPort()); instance.setRegistryCluster("default"); instance.setApplicationModel(ApplicationModel.defaultModel()); Map<String, String> metadata = new HashMap<>(); if (StringUtils.isNotEmpty(dubboUrl.getParameter(REVISION_KEY))) { metadata.put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, dubboUrl.getParameter(REVISION_KEY)); } instance.setMetadata(metadata); instances.add(instance); } return instances; } }
MultipleServiceDiscoveryTest
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/JHLogAnalyzer.java
{ "start": 18471, "end": 21311 }
class ____ { String TASK_ATTEMPT_ID; String TASK_STATUS; // this task attempt status long START_TIME; long FINISH_TIME; long HDFS_BYTES_READ; long HDFS_BYTES_WRITTEN; long FILE_BYTES_READ; long FILE_BYTES_WRITTEN; /** * Task attempt is considered successful iff all three statuses * of the attempt, the task, and the job equal "SUCCESS". */ boolean isSuccessful() { return (TASK_STATUS != null) && TASK_STATUS.equals("SUCCESS"); } String parse(StringTokenizer tokens) throws IOException { String taskID = null; while(tokens.hasMoreTokens()) { String t = tokens.nextToken(); String[] keyVal = getKeyValue(t); if(keyVal.length < 2) continue; if(keyVal[0].equals("TASKID")) { if(taskID == null) taskID = new String(keyVal[1]); else if(!taskID.equals(keyVal[1])) { LOG.error("Incorrect TASKID: " + keyVal[1] + " expect " + taskID); continue; } } else if(keyVal[0].equals("TASK_ATTEMPT_ID")) { if(TASK_ATTEMPT_ID == null) TASK_ATTEMPT_ID = new String(keyVal[1]); else if(!TASK_ATTEMPT_ID.equals(keyVal[1])) { LOG.error("Incorrect TASKID: " + keyVal[1] + " expect " + taskID); continue; } } else if(keyVal[0].equals("TASK_STATUS")) TASK_STATUS = new String(keyVal[1]); else if(keyVal[0].equals("START_TIME")) START_TIME = Long.parseLong(keyVal[1]); else if(keyVal[0].equals("FINISH_TIME")) FINISH_TIME = Long.parseLong(keyVal[1]); } return taskID; } /** * Update with non-null fields of the same task attempt log record. */ void updateWith(TaskAttemptHistoryLog from) throws IOException { if(TASK_ATTEMPT_ID == null) TASK_ATTEMPT_ID = from.TASK_ATTEMPT_ID; else if(! TASK_ATTEMPT_ID.equals(from.TASK_ATTEMPT_ID)) { throw new IOException( "Incorrect TASK_ATTEMPT_ID: " + from.TASK_ATTEMPT_ID + " expect " + TASK_ATTEMPT_ID); } if(from.TASK_STATUS != null) TASK_STATUS = from.TASK_STATUS; if(from.START_TIME > 0) START_TIME = from.START_TIME; if(from.FINISH_TIME > 0) FINISH_TIME = from.FINISH_TIME; if(from.HDFS_BYTES_READ > 0) HDFS_BYTES_READ = from.HDFS_BYTES_READ; if(from.HDFS_BYTES_WRITTEN > 0) HDFS_BYTES_WRITTEN = from.HDFS_BYTES_WRITTEN; if(from.FILE_BYTES_READ > 0) FILE_BYTES_READ = from.FILE_BYTES_READ; if(from.FILE_BYTES_WRITTEN > 0) FILE_BYTES_WRITTEN = from.FILE_BYTES_WRITTEN; } } /** * Key = statName*date-time*taskType * Value = number of msec for the our */ private static
TaskAttemptHistoryLog
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/common/Type.java
{ "start": 57379, "end": 63668 }
class ____ extends SimpleTypeVisitor8<ResolvedPair, Type> { private final TypeFactory typeFactory; private final Type typeToMatch; private final TypeUtils types; /** * @param typeFactory factory * @param types type utils * @param typeToMatch the typeVar or wildcard with typeVar bound */ TypeVarMatcher(TypeFactory typeFactory, TypeUtils types, Type typeToMatch) { super( new ResolvedPair( typeToMatch, null ) ); this.typeFactory = typeFactory; this.typeToMatch = typeToMatch; this.types = types; } @Override public ResolvedPair visitTypeVariable(TypeVariable parameterized, Type declared) { if ( typeToMatch.isTypeVar() && types.isSameType( parameterized, typeToMatch.getTypeMirror() ) ) { return new ResolvedPair( typeFactory.getType( parameterized ), declared ); } return super.DEFAULT_VALUE; } /** * If ? extends SomeTime equals the boundary set in typeVarToMatch (NOTE: you can't compare the wildcard itself) * then return a result; */ @Override public ResolvedPair visitWildcard(WildcardType parameterized, Type declared) { if ( typeToMatch.hasExtendsBound() && parameterized.getExtendsBound() != null && types.isSameType( typeToMatch.getTypeBound().getTypeMirror(), parameterized.getExtendsBound() ) ) { return new ResolvedPair( typeToMatch, declared); } else if ( typeToMatch.hasSuperBound() && parameterized.getSuperBound() != null && types.isSameType( typeToMatch.getTypeBound().getTypeMirror(), parameterized.getSuperBound() ) ) { return new ResolvedPair( typeToMatch, declared); } if ( parameterized.getExtendsBound() != null ) { ResolvedPair match = visit( parameterized.getExtendsBound(), declared ); if ( match.match != null ) { return new ResolvedPair( typeFactory.getType( parameterized ), declared ); } } else if (parameterized.getSuperBound() != null ) { ResolvedPair match = visit( parameterized.getSuperBound(), declared ); if ( match.match != null ) { return new ResolvedPair( typeFactory.getType( parameterized ), declared ); } } return super.DEFAULT_VALUE; } @Override public ResolvedPair visitArray(ArrayType parameterized, Type declared) { if ( types.isSameType( parameterized.getComponentType(), typeToMatch.getTypeMirror() ) ) { return new ResolvedPair( typeFactory.getType( parameterized ), declared ); } if ( declared.isArrayType() ) { return visit( parameterized.getComponentType(), declared.getComponentType() ); } return super.DEFAULT_VALUE; } @Override public ResolvedPair visitDeclared(DeclaredType parameterized, Type declared) { List<ResolvedPair> results = new ArrayList<>( ); if ( parameterized.getTypeArguments().isEmpty() ) { return super.DEFAULT_VALUE; } else if ( types.isSameType( types.erasure( parameterized ), types.erasure( declared.getTypeMirror() ) ) ) { // We can't assume that the type args are the same // e.g. List<T> is assignable to Object if ( parameterized.getTypeArguments().size() != declared.getTypeParameters().size() ) { return super.visitDeclared( parameterized, declared ); } // only possible to compare parameters when the types are exactly the same for ( int i = 0; i < parameterized.getTypeArguments().size(); i++ ) { TypeMirror parameterizedTypeArg = parameterized.getTypeArguments().get( i ); Type declaredTypeArg = declared.getTypeParameters().get( i ); ResolvedPair result = visit( parameterizedTypeArg, declaredTypeArg ); if ( result != super.DEFAULT_VALUE ) { results.add( result ); } } } else { // Also check whether the implemented interfaces are parameterized for ( Type declaredSuperType : declared.getDirectSuperTypes() ) { if ( Object.class.getName().equals( declaredSuperType.getFullyQualifiedName() ) ) { continue; } ResolvedPair result = visitDeclared( parameterized, declaredSuperType ); if ( result != super.DEFAULT_VALUE ) { results.add( result ); } } for ( TypeMirror parameterizedSuper : types.directSupertypes( parameterized ) ) { if ( isJavaLangObject( parameterizedSuper ) ) { continue; } ResolvedPair result = visitDeclared( (DeclaredType) parameterizedSuper, declared ); if ( result != super.DEFAULT_VALUE ) { results.add( result ); } } } if ( results.isEmpty() ) { return super.DEFAULT_VALUE; } else { return results.stream().allMatch( results.get( 0 )::equals ) ? results.get( 0 ) : super.DEFAULT_VALUE; } } private boolean isJavaLangObject(TypeMirror type) { if ( type instanceof DeclaredType ) { return ( (TypeElement) ( (DeclaredType) type ).asElement() ).getQualifiedName() .contentEquals( Object.class.getName() ); } return false; } } /** * Reflects any Resolved Pair, examples are * T, String * ? extends T, BigDecimal * T[], Integer[] */ public static
TypeVarMatcher
java
spring-projects__spring-boot
module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/autoconfigure/PropertiesRabbitConnectionDetailsTests.java
{ "start": 1165, "end": 3194 }
class ____ { private static final int DEFAULT_PORT = 5672; private DefaultSslBundleRegistry sslBundleRegistry; private RabbitProperties properties; private PropertiesRabbitConnectionDetails propertiesRabbitConnectionDetails; @BeforeEach void setUp() { this.properties = new RabbitProperties(); this.sslBundleRegistry = new DefaultSslBundleRegistry(); this.propertiesRabbitConnectionDetails = new PropertiesRabbitConnectionDetails(this.properties, this.sslBundleRegistry); } @Test void getAddresses() { this.properties.setAddresses(List.of("localhost", "localhost:1234", "[::1]", "[::1]:32863")); List<Address> addresses = this.propertiesRabbitConnectionDetails.getAddresses(); assertThat(addresses.size()).isEqualTo(4); assertThat(addresses.get(0).host()).isEqualTo("localhost"); assertThat(addresses.get(0).port()).isEqualTo(DEFAULT_PORT); assertThat(addresses.get(1).host()).isEqualTo("localhost"); assertThat(addresses.get(1).port()).isEqualTo(1234); assertThat(addresses.get(2).host()).isEqualTo("[::1]"); assertThat(addresses.get(2).port()).isEqualTo(DEFAULT_PORT); assertThat(addresses.get(3).host()).isEqualTo("[::1]"); assertThat(addresses.get(3).port()).isEqualTo(32863); } @Test void shouldReturnSslBundle() { SslBundle bundle1 = mock(SslBundle.class); this.sslBundleRegistry.registerBundle("bundle-1", bundle1); this.properties.getSsl().setBundle("bundle-1"); SslBundle sslBundle = this.propertiesRabbitConnectionDetails.getSslBundle(); assertThat(sslBundle).isSameAs(bundle1); } @Test void shouldReturnNullIfSslIsEnabledButBundleNotSet() { this.properties.getSsl().setEnabled(true); SslBundle sslBundle = this.propertiesRabbitConnectionDetails.getSslBundle(); assertThat(sslBundle).isNull(); } @Test void shouldReturnNullIfSslIsNotEnabled() { this.properties.getSsl().setEnabled(false); SslBundle sslBundle = this.propertiesRabbitConnectionDetails.getSslBundle(); assertThat(sslBundle).isNull(); } }
PropertiesRabbitConnectionDetailsTests
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/hashset/HashSetAssert_endsWith_Test.java
{ "start": 1255, "end": 3015 }
class ____ extends HashSetAssertBaseTest { @Override protected HashSetAssert<Object> invoke_api_method() { return assertions.endsWith(someValues).endsWith(someValues[0], someValues[1]); } @Override protected void verify_internal_effects() { verify(iterables).assertEndsWith(getInfo(assertions), getActual(assertions), someValues); verify(iterables).assertEndsWith(getInfo(assertions), getActual(assertions), someValues[0], new Object[] { someValues[1] }); } @HashSetTest void should_pass(HashSetFactory hashSetFactory) { // GIVEN Date first = Date.from(EPOCH.plusSeconds(1)); Date second = Date.from(EPOCH.plusSeconds(2)); Date third = Date.from(EPOCH.plusSeconds(3)); HashSet<Date> dates = hashSetFactory.createWith(first, second, third); // WHEN Date[] exactElements = dates.toArray(new Date[0]); // THEN then(dates).endsWith(exactElements) .endsWith(exactElements[1], exactElements[2]); } @Test void should_fail_after_hashCode_changed() { // GIVEN Date first = Date.from(EPOCH.plusSeconds(1)); Date second = Date.from(EPOCH.plusSeconds(2)); Date third = Date.from(EPOCH.plusSeconds(3)); HashSet<Date> dates = newLinkedHashSet(first, second, third); second.setTime(4_000); // WHEN var assertionError = expectAssertionError(() -> assertThat(dates).endsWith(second, third)); // THEN then(assertionError).hasMessageContainingAll(STANDARD_REPRESENTATION.toStringOf(second), "(elements were checked as in HashSet, as soon as their hashCode change, the HashSet won't find them anymore - use skippingHashCodeComparison to get a collection like comparison)"); } }
HashSetAssert_endsWith_Test
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/inference/results/DenseEmbeddingByteResultsTests.java
{ "start": 746, "end": 6221 }
class ____ extends AbstractWireSerializingTestCase<DenseEmbeddingByteResults> { public static DenseEmbeddingByteResults createRandomResults() { int embeddings = randomIntBetween(1, 10); List<DenseEmbeddingByteResults.Embedding> embeddingResults = new ArrayList<>(embeddings); for (int i = 0; i < embeddings; i++) { embeddingResults.add(createRandomEmbedding()); } return new DenseEmbeddingByteResults(embeddingResults); } private static DenseEmbeddingByteResults.Embedding createRandomEmbedding() { int columns = randomIntBetween(1, 10); byte[] bytes = new byte[columns]; for (int i = 0; i < columns; i++) { bytes[i] = randomByte(); } return new DenseEmbeddingByteResults.Embedding(bytes); } public void testToXContent_CreatesTheRightFormatForASingleEmbedding() throws IOException { var entity = new DenseEmbeddingByteResults(List.of(new DenseEmbeddingByteResults.Embedding(new byte[] { (byte) 23 }))); String xContentResult = Strings.toString(entity, true, true); assertThat(xContentResult, is(""" { "text_embedding_bytes" : [ { "embedding" : [ 23 ] } ] }""")); } public void testToXContent_CreatesTheRightFormatForMultipleEmbeddings() throws IOException { var entity = new DenseEmbeddingByteResults( List.of( new DenseEmbeddingByteResults.Embedding(new byte[] { (byte) 23 }), new DenseEmbeddingByteResults.Embedding(new byte[] { (byte) 24 }) ) ); String xContentResult = Strings.toString(entity, true, true); assertThat(xContentResult, is(""" { "text_embedding_bytes" : [ { "embedding" : [ 23 ] }, { "embedding" : [ 24 ] } ] }""")); } public void testTransformToCoordinationFormat() { var results = new DenseEmbeddingByteResults( List.of( new DenseEmbeddingByteResults.Embedding(new byte[] { (byte) 23, (byte) 24 }), new DenseEmbeddingByteResults.Embedding(new byte[] { (byte) 25, (byte) 26 }) ) ).transformToCoordinationFormat(); assertThat( results, is( List.of( new MlDenseEmbeddingResults(DenseEmbeddingByteResults.TEXT_EMBEDDING_BYTES, new double[] { 23F, 24F }, false), new MlDenseEmbeddingResults(DenseEmbeddingByteResults.TEXT_EMBEDDING_BYTES, new double[] { 25F, 26F }, false) ) ) ); } public void testGetFirstEmbeddingSize() { var firstEmbeddingSize = new DenseEmbeddingByteResults( List.of( new DenseEmbeddingByteResults.Embedding(new byte[] { (byte) 23, (byte) 24 }), new DenseEmbeddingByteResults.Embedding(new byte[] { (byte) 25, (byte) 26 }) ) ).getFirstEmbeddingSize(); assertThat(firstEmbeddingSize, is(2)); } public void testEmbeddingMerge() { DenseEmbeddingByteResults.Embedding embedding1 = new DenseEmbeddingByteResults.Embedding(new byte[] { 1, 1, -128 }); DenseEmbeddingByteResults.Embedding embedding2 = new DenseEmbeddingByteResults.Embedding(new byte[] { 1, 0, 127 }); DenseEmbeddingByteResults.Embedding embedding3 = new DenseEmbeddingByteResults.Embedding(new byte[] { 0, 0, 100 }); DenseEmbeddingByteResults.Embedding mergedEmbedding = embedding1.merge(embedding2); assertThat(mergedEmbedding, equalTo(new DenseEmbeddingByteResults.Embedding(new byte[] { 1, 1, 0 }))); mergedEmbedding = mergedEmbedding.merge(embedding3); assertThat(mergedEmbedding, equalTo(new DenseEmbeddingByteResults.Embedding(new byte[] { 1, 0, 33 }))); } @Override protected Writeable.Reader<DenseEmbeddingByteResults> instanceReader() { return DenseEmbeddingByteResults::new; } @Override protected DenseEmbeddingByteResults createTestInstance() { return createRandomResults(); } @Override protected DenseEmbeddingByteResults mutateInstance(DenseEmbeddingByteResults instance) throws IOException { // if true we reduce the embeddings list by a random amount, if false we add an embedding to the list if (randomBoolean()) { // -1 to remove at least one item from the list int end = randomInt(instance.embeddings().size() - 1); return new DenseEmbeddingByteResults(instance.embeddings().subList(0, end)); } else { List<DenseEmbeddingByteResults.Embedding> embeddings = new ArrayList<>(instance.embeddings()); embeddings.add(createRandomEmbedding()); return new DenseEmbeddingByteResults(embeddings); } } public static Map<String, Object> buildExpectationByte(List<List<Byte>> embeddings) { return Map.of( DenseEmbeddingByteResults.TEXT_EMBEDDING_BYTES, embeddings.stream().map(embedding -> Map.of(EmbeddingResults.EMBEDDING, embedding)).toList() ); } }
DenseEmbeddingByteResultsTests
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-test/src/main/java/smoketest/test/domain/VehicleIdentificationNumber.java
{ "start": 826, "end": 1466 }
class ____ { private final String vin; public VehicleIdentificationNumber(String vin) { Assert.notNull(vin, "'vin' must not be null"); Assert.isTrue(vin.length() == 17, "'vin' must be exactly 17 characters"); this.vin = vin; } @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } if (obj == null || obj.getClass() != getClass()) { return false; } return this.vin.equals(((VehicleIdentificationNumber) obj).vin); } @Override public int hashCode() { return this.vin.hashCode(); } @Override public String toString() { return this.vin; } }
VehicleIdentificationNumber
java
apache__logging-log4j2
log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/IdleStrategy.java
{ "start": 1692, "end": 1815 }
interface ____ { /** * Perform current idle action (e.g. nothing/yield/sleep). */ void idle(); }
IdleStrategy
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/slot/NoOpSlotAllocationSnapshotPersistenceService.java
{ "start": 1029, "end": 1504 }
enum ____ implements SlotAllocationSnapshotPersistenceService { INSTANCE; @Override public void persistAllocationSnapshot(SlotAllocationSnapshot slotAllocationSnapshot) throws IOException {} @Override public void deleteAllocationSnapshot(int slotIndex) {} @Override public Collection<SlotAllocationSnapshot> loadAllocationSnapshots() { return Collections.emptyList(); } }
NoOpSlotAllocationSnapshotPersistenceService
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/blockhash/TimeSeriesBlockHash.java
{ "start": 1651, "end": 8948 }
class ____ extends BlockHash { private final int tsHashChannel; private final int timestampIntervalChannel; private int lastTsidPosition = 0; private final BytesRefArrayWithSize tsidArray; private long lastTimestamp; private final LongArrayWithSize timestampArray; private int currentTimestampCount; private final IntArrayWithSize perTsidCountArray; public TimeSeriesBlockHash(int tsHashChannel, int timestampIntervalChannel, BlockFactory blockFactory) { super(blockFactory); this.tsHashChannel = tsHashChannel; this.timestampIntervalChannel = timestampIntervalChannel; this.tsidArray = new BytesRefArrayWithSize(blockFactory); this.timestampArray = new LongArrayWithSize(blockFactory); this.perTsidCountArray = new IntArrayWithSize(blockFactory); } @Override public void close() { Releasables.close(tsidArray, timestampArray, perTsidCountArray); } private OrdinalBytesRefVector getTsidVector(Page page) { BytesRefBlock block = page.getBlock(tsHashChannel); var ordinalBlock = block.asOrdinals(); if (ordinalBlock == null) { throw new IllegalStateException("expected ordinal block for tsid"); } var ordinalVector = ordinalBlock.asVector(); if (ordinalVector == null) { throw new IllegalStateException("expected ordinal vector for tsid"); } return ordinalVector; } private LongVector getTimestampVector(Page page) { final LongBlock timestampsBlock = page.getBlock(timestampIntervalChannel); LongVector timestampsVector = timestampsBlock.asVector(); if (timestampsVector == null) { throw new IllegalStateException("expected long vector for timestamp"); } return timestampsVector; } @Override public void add(Page page, GroupingAggregatorFunction.AddInput addInput) { final BytesRefVector tsidDict; final IntVector tsidOrdinals; { final var tsidVector = getTsidVector(page); tsidDict = tsidVector.getDictionaryVector(); tsidOrdinals = tsidVector.getOrdinalsVector(); } try (var ordsBuilder = blockFactory.newIntVectorBuilder(tsidOrdinals.getPositionCount())) { final BytesRef spare = new BytesRef(); final BytesRef lastTsid = new BytesRef(); final LongVector timestampVector = getTimestampVector(page); int lastOrd = -1; for (int i = 0; i < tsidOrdinals.getPositionCount(); i++) { final int newOrd = tsidOrdinals.getInt(i); boolean newGroup = false; if (lastOrd != newOrd) { final var newTsid = tsidDict.getBytesRef(newOrd, spare); if (positionCount() == 0) { newGroup = true; } else if (lastOrd == -1) { tsidArray.get(lastTsidPosition, lastTsid); newGroup = lastTsid.equals(newTsid) == false; } else { newGroup = true; } if (newGroup) { endTsidGroup(); lastTsidPosition = tsidArray.count; tsidArray.append(newTsid); } lastOrd = newOrd; } final long timestamp = timestampVector.getLong(i); if (newGroup || timestamp != lastTimestamp) { assert newGroup || lastTimestamp >= timestamp : "@timestamp goes backward " + lastTimestamp + " < " + timestamp; timestampArray.append(timestamp); lastTimestamp = timestamp; currentTimestampCount++; } ordsBuilder.appendInt(timestampArray.count - 1); } try (var ords = ordsBuilder.build()) { addInput.add(0, ords); } } } private void endTsidGroup() { if (currentTimestampCount > 0) { perTsidCountArray.append(currentTimestampCount); currentTimestampCount = 0; } } @Override public ReleasableIterator<IntBlock> lookup(Page page, ByteSizeValue targetBlockSize) { throw new UnsupportedOperationException("TODO"); } @Override public Block[] getKeys() { endTsidGroup(); final Block[] blocks = new Block[2]; try { if (OrdinalBytesRefBlock.isDense(positionCount(), tsidArray.count)) { blocks[0] = buildTsidBlockWithOrdinal(); } else { blocks[0] = buildTsidBlock(); } blocks[1] = timestampArray.toBlock(); return blocks; } finally { if (blocks[blocks.length - 1] == null) { Releasables.close(blocks); } } } private BytesRefBlock buildTsidBlockWithOrdinal() { try (IntVector.FixedBuilder ordinalBuilder = blockFactory.newIntVectorFixedBuilder(positionCount())) { for (int i = 0; i < tsidArray.count; i++) { int numTimestamps = perTsidCountArray.array.get(i); for (int t = 0; t < numTimestamps; t++) { ordinalBuilder.appendInt(i); } } final IntVector ordinalVector = ordinalBuilder.build(); BytesRefVector dictionary = null; boolean success = false; try { dictionary = tsidArray.toVector(); var result = new OrdinalBytesRefVector(ordinalVector, dictionary).asBlock(); success = true; return result; } finally { if (success == false) { Releasables.close(ordinalVector, dictionary); } } } } private BytesRefBlock buildTsidBlock() { try (BytesRefVector.Builder tsidBuilder = blockFactory.newBytesRefVectorBuilder(positionCount());) { final BytesRef tsid = new BytesRef(); for (int i = 0; i < tsidArray.count; i++) { tsidArray.array.get(i, tsid); int numTimestamps = perTsidCountArray.array.get(i); for (int t = 0; t < numTimestamps; t++) { tsidBuilder.appendBytesRef(tsid); } } return tsidBuilder.build().asBlock(); } } private int positionCount() { return timestampArray.count; } @Override public IntVector nonEmpty() { long endExclusive = positionCount(); return IntVector.range(0, Math.toIntExact(endExclusive), blockFactory); } @Override public BitArray seenGroupIds(BigArrays bigArrays) { return new Range(0, positionCount()).seenGroupIds(bigArrays); } public String toString() { return "TimeSeriesBlockHash{keys=[BytesRefKey[channel=" + tsHashChannel + "], LongKey[channel=" + timestampIntervalChannel + "]], entries=" + positionCount() + "b}"; } private static
TimeSeriesBlockHash
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/MonoFilterTest.java
{ "start": 999, "end": 4773 }
class ____ { @Test public void sourceNull() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> { new MonoFilter<Integer>(null, e -> true); }); } @Test public void predicateNull() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> { Mono.never().filter(null); }); } @Test public void normal() { Mono.just(1) .filter(v -> v % 2 == 0) .subscribeWith(AssertSubscriber.create()) .assertNoValues() .assertComplete() .assertNoError(); Mono.just(1) .filter(v -> v % 2 != 0) .subscribeWith(AssertSubscriber.create()) .assertValues(1) .assertComplete() .assertNoError(); } @Test public void normalBackpressuredJust() { AssertSubscriber<Integer> ts = AssertSubscriber.create(0); Mono.just(1) .filter(v -> v % 2 != 0) .subscribe(ts); ts.assertNoValues() .assertNotComplete() .assertNoError(); ts.request(10); ts.assertValues(1) .assertComplete() .assertNoError(); } @Test public void normalBackpressuredCallable() { AssertSubscriber<Integer> ts = AssertSubscriber.create(0); Mono.fromCallable(() -> 2) .filter(v -> v % 2 == 0) .subscribe(ts); ts.assertNoValues() .assertNotComplete() .assertNoError(); ts.request(10); ts.assertValues(2) .assertComplete() .assertNoError(); } @Test public void predicateThrows() { AssertSubscriber<Object> ts = AssertSubscriber.create(2); Mono.create(s -> s.success(1)) .filter(v -> { throw new RuntimeException("forced failure"); }) .subscribe(ts); ts.assertNoValues() .assertNotComplete() .assertError(RuntimeException.class) .assertErrorMessage("forced failure"); } @Test public void syncFusion() { AssertSubscriber<Object> ts = AssertSubscriber.create(); Mono.just(2) .filter(v -> (v & 1) == 0) .subscribe(ts); ts.assertValues(2) .assertNoError() .assertComplete(); } @Test public void asyncFusion() { AssertSubscriber<Object> ts = AssertSubscriber.create(); //TODO find a suitable source that can be async fused (MonoProcessor was never fuseable) NextProcessor<Integer> up = new NextProcessor<>(null); up.filter(v -> (v & 1) == 0) .subscribe(ts); up.onNext(2); up.onComplete(); ts.assertValues(2) .assertNoError() .assertComplete(); } @Test public void asyncFusionBackpressured() { AssertSubscriber<Object> ts = AssertSubscriber.create(1); //TODO find a suitable source that can be async fused (MonoProcessor was never fuseable) NextProcessor<Integer> up = new NextProcessor<>(null); Mono.just(1) .hide() .flatMap(w -> up.filter(v -> (v & 1) == 0)) .subscribe(ts); up.onNext(2); ts.assertValues(2) .assertNoError() .assertComplete(); try{ up.onNext(3); } catch(Exception e){ assertThat(Exceptions.isCancel(e)).isTrue(); } ts.assertValues(2) .assertNoError() .assertComplete(); } @Test public void filterMono() { StepVerifier.create(Mono.just(2).filter(s -> s % 2 == 0)) .expectNext(2) .verifyComplete(); } @Test public void filterMonoNot() { StepVerifier.create(Mono.just(1).filter(s -> s % 2 == 0)) .verifyComplete(); } @Test public void scanOperator() { MonoFilter<Integer> test = new MonoFilter<>(Mono.just(1), (v -> v % 2 != 0)); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); } @Test public void scanFuseableOperator() { MonoFilterFuseable<Integer> test = new MonoFilterFuseable<>(Mono.just(1), (v -> v % 2 != 0)); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); } }
MonoFilterTest
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxMergeComparing.java
{ "start": 1824, "end": 4818 }
class ____<T> extends Flux<T> implements SourceProducer<T> { final int prefetch; final Comparator<? super T> valueComparator; final Publisher<? extends T>[] sources; final boolean delayError; final boolean waitForAllSources; @SafeVarargs FluxMergeComparing(int prefetch, Comparator<? super T> valueComparator, boolean delayError, boolean waitForAllSources, Publisher<? extends T>... sources) { if (prefetch <= 0) { throw new IllegalArgumentException("prefetch > 0 required but it was " + prefetch); } this.sources = Objects.requireNonNull(sources, "sources must be non-null"); for (int i = 0; i < sources.length; i++) { Publisher<? extends T> source = sources[i]; if (source == null) { throw new NullPointerException("sources[" + i + "] is null"); } } Operators.toFluxOrMono(this.sources); this.prefetch = prefetch; this.valueComparator = valueComparator; this.delayError = delayError; this.waitForAllSources = waitForAllSources; } /** * Returns a new instance which has the additional source to be merged together with * the current array of sources. The provided {@link Comparator} is tested for equality * with the current comparator, and if different is combined by {@link Comparator#thenComparing(Comparator)}. * <p> * This operation doesn't change the current {@link FluxMergeComparing} instance. * * @param source the new source to merge with the others * @return the new {@link FluxMergeComparing} instance */ FluxMergeComparing<T> mergeAdditionalSource(Publisher<? extends T> source, Comparator<? super T> otherComparator) { int n = sources.length; @SuppressWarnings("unchecked") Publisher<? extends T>[] newArray = new Publisher[n + 1]; System.arraycopy(sources, 0, newArray, 0, n); newArray[n] = source; if (!valueComparator.equals(otherComparator)) { @SuppressWarnings("unchecked") Comparator<T> currentComparator = (Comparator<T>) this.valueComparator; final Comparator<T> newComparator = currentComparator.thenComparing(otherComparator); return new FluxMergeComparing<>(prefetch, newComparator, delayError, waitForAllSources, newArray); } return new FluxMergeComparing<>(prefetch, valueComparator, delayError, waitForAllSources, newArray); } @Override public int getPrefetch() { return prefetch; } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.PARENT) return sources.length > 0 ? sources[0] : null; if (key == Attr.PREFETCH) return prefetch; if (key == Attr.DELAY_ERROR) return delayError; if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return SourceProducer.super.scanUnsafe(key); } @Override public void subscribe(CoreSubscriber<? super T> actual) { MergeOrderedMainProducer<T> main = new MergeOrderedMainProducer<>(actual, valueComparator, prefetch, sources.length, delayError, waitForAllSources); actual.onSubscribe(main); main.subscribe(sources); } static final
FluxMergeComparing
java
elastic__elasticsearch
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/IndexResolver.java
{ "start": 3721, "end": 32056 }
enum ____ { STANDARD_INDEX(SQL_TABLE, "INDEX"), ALIAS(SQL_VIEW, "ALIAS"), FROZEN_INDEX(SQL_TABLE, "FROZEN INDEX"), // value for user types unrecognized UNKNOWN("UNKNOWN", "UNKNOWN"); public static final EnumSet<IndexType> VALID_INCLUDE_FROZEN = EnumSet.of(STANDARD_INDEX, ALIAS, FROZEN_INDEX); public static final EnumSet<IndexType> VALID_REGULAR = EnumSet.of(STANDARD_INDEX, ALIAS); private final String toSql; private final String toNative; IndexType(String sql, String toNative) { this.toSql = sql; this.toNative = toNative; } public String toSql() { return toSql; } public String toNative() { return toNative; } } public record IndexInfo(String cluster, String name, IndexType type) { @Override public String toString() { return buildRemoteIndexName(cluster, name); } } public static final String SQL_TABLE = "TABLE"; public static final String SQL_VIEW = "VIEW"; private static final IndicesOptions INDICES_ONLY_OPTIONS = IndicesOptions.builder() .concreteTargetOptions(IndicesOptions.ConcreteTargetOptions.ALLOW_UNAVAILABLE_TARGETS) .wildcardOptions( IndicesOptions.WildcardOptions.builder() .matchOpen(true) .matchClosed(false) .includeHidden(false) .allowEmptyExpressions(true) .resolveAliases(false) ) .gatekeeperOptions( IndicesOptions.GatekeeperOptions.builder().ignoreThrottled(true).allowClosedIndices(true).allowAliasToMultipleIndices(true) ) .build(); private static final IndicesOptions FROZEN_INDICES_OPTIONS = IndicesOptions.builder() .concreteTargetOptions(IndicesOptions.ConcreteTargetOptions.ALLOW_UNAVAILABLE_TARGETS) .wildcardOptions( IndicesOptions.WildcardOptions.builder() .matchOpen(true) .matchClosed(false) .includeHidden(false) .allowEmptyExpressions(true) .resolveAliases(false) ) .gatekeeperOptions( IndicesOptions.GatekeeperOptions.builder().ignoreThrottled(false).allowClosedIndices(true).allowAliasToMultipleIndices(true) ) .build(); public static final IndicesOptions FIELD_CAPS_INDICES_OPTIONS = IndicesOptions.builder() .concreteTargetOptions(IndicesOptions.ConcreteTargetOptions.ALLOW_UNAVAILABLE_TARGETS) .wildcardOptions( IndicesOptions.WildcardOptions.builder() .matchOpen(true) .matchClosed(false) .includeHidden(false) .allowEmptyExpressions(true) .resolveAliases(true) ) .gatekeeperOptions( IndicesOptions.GatekeeperOptions.builder().ignoreThrottled(true).allowClosedIndices(true).allowAliasToMultipleIndices(true) ) .build(); public static final IndicesOptions FIELD_CAPS_FROZEN_INDICES_OPTIONS = IndicesOptions.builder() .concreteTargetOptions(IndicesOptions.ConcreteTargetOptions.ALLOW_UNAVAILABLE_TARGETS) .wildcardOptions( IndicesOptions.WildcardOptions.builder() .matchOpen(true) .matchClosed(false) .includeHidden(false) .allowEmptyExpressions(true) .resolveAliases(true) ) .gatekeeperOptions( IndicesOptions.GatekeeperOptions.builder().ignoreThrottled(false).allowClosedIndices(true).allowAliasToMultipleIndices(true) ) .build(); public static final Set<String> ALL_FIELDS = Set.of("*"); public static final Set<String> INDEX_METADATA_FIELD = Set.of("_index"); public static final String UNMAPPED = "unmapped"; private final Client client; private final String clusterName; private final DataTypeRegistry typeRegistry; private final Supplier<Set<String>> remoteClusters; public IndexResolver(Client client, String clusterName, DataTypeRegistry typeRegistry, Supplier<Set<String>> remoteClusters) { this.client = client; this.clusterName = clusterName; this.typeRegistry = typeRegistry; this.remoteClusters = remoteClusters; } public String clusterName() { return clusterName; } public Set<String> remoteClusters() { return remoteClusters.get(); } /** * Resolves only the names, differentiating between indices and aliases. * This method is required since the other methods rely on mapping which is tied to an index (not an alias). */ public void resolveNames( String clusterWildcard, String indexWildcard, String javaRegex, EnumSet<IndexType> types, ActionListener<Set<IndexInfo>> listener ) { // first get aliases (if specified) boolean retrieveAliases = CollectionUtils.isEmpty(types) || types.contains(IndexType.ALIAS); boolean retrieveIndices = CollectionUtils.isEmpty(types) || types.contains(IndexType.STANDARD_INDEX); boolean retrieveFrozenIndices = CollectionUtils.isEmpty(types) || types.contains(IndexType.FROZEN_INDEX); String[] indexWildcards = Strings.commaDelimitedListToStringArray(indexWildcard); Set<IndexInfo> indexInfos = new HashSet<>(); if (retrieveAliases && clusterIsLocal(clusterWildcard)) { ResolveIndexAction.Request resolveRequest = new ResolveIndexAction.Request(indexWildcards, IndicesOptions.lenientExpandOpen()); client.admin().indices().resolveIndex(resolveRequest, wrap(response -> { for (ResolveIndexAction.ResolvedAlias alias : response.getAliases()) { indexInfos.add(new IndexInfo(clusterName, alias.getName(), IndexType.ALIAS)); } for (ResolveIndexAction.ResolvedDataStream dataStream : response.getDataStreams()) { indexInfos.add(new IndexInfo(clusterName, dataStream.getName(), IndexType.ALIAS)); } resolveIndices(clusterWildcard, indexWildcards, javaRegex, retrieveIndices, retrieveFrozenIndices, indexInfos, listener); }, ex -> { // with security, two exception can be thrown: // INFE - if no alias matches // security exception is the user cannot access aliases // in both cases, that is allowed and we continue with the indices request if (ex instanceof IndexNotFoundException || ex instanceof ElasticsearchSecurityException) { resolveIndices( clusterWildcard, indexWildcards, javaRegex, retrieveIndices, retrieveFrozenIndices, indexInfos, listener ); } else { listener.onFailure(ex); } })); } else { resolveIndices(clusterWildcard, indexWildcards, javaRegex, retrieveIndices, retrieveFrozenIndices, indexInfos, listener); } } private void resolveIndices( String clusterWildcard, String[] indexWildcards, String javaRegex, boolean retrieveIndices, boolean retrieveFrozenIndices, Set<IndexInfo> indexInfos, ActionListener<Set<IndexInfo>> listener ) { if (retrieveIndices || retrieveFrozenIndices) { if (clusterIsLocal(clusterWildcard)) { // resolve local indices GetIndexRequest indexRequest = new GetIndexRequest(MasterNodeRequest.INFINITE_MASTER_NODE_TIMEOUT).indices(indexWildcards) .features(Feature.SETTINGS) .includeDefaults(false) .indicesOptions(INDICES_ONLY_OPTIONS); // if frozen indices are requested, make sure to update the request accordingly if (retrieveFrozenIndices) { indexRequest.indicesOptions(FROZEN_INDICES_OPTIONS); } client.admin().indices().getIndex(indexRequest, listener.delegateFailureAndWrap((delegate, indices) -> { if (indices != null) { for (String indexName : indices.getIndices()) { boolean isFrozen = retrieveFrozenIndices && indices.getSettings().get(indexName).getAsBoolean("index.frozen", false); indexInfos.add( new IndexInfo(clusterName, indexName, isFrozen ? IndexType.FROZEN_INDEX : IndexType.STANDARD_INDEX) ); } } resolveRemoteIndices(clusterWildcard, indexWildcards, javaRegex, retrieveFrozenIndices, indexInfos, delegate); })); } else { resolveRemoteIndices(clusterWildcard, indexWildcards, javaRegex, retrieveFrozenIndices, indexInfos, listener); } } else { filterResults(javaRegex, indexInfos, listener); } } private void resolveRemoteIndices( String clusterWildcard, String[] indexWildcards, String javaRegex, boolean retrieveFrozenIndices, Set<IndexInfo> indexInfos, ActionListener<Set<IndexInfo>> listener ) { if (hasText(clusterWildcard)) { IndicesOptions indicesOptions = retrieveFrozenIndices ? FIELD_CAPS_FROZEN_INDICES_OPTIONS : FIELD_CAPS_INDICES_OPTIONS; FieldCapabilitiesRequest fieldRequest = createFieldCapsRequest( qualifyAndJoinIndices(clusterWildcard, indexWildcards), ALL_FIELDS, indicesOptions, emptyMap() ); client.fieldCaps(fieldRequest, wrap(response -> { String[] indices = response.getIndices(); if (indices != null) { for (String indexName : indices) { // TODO: perform two requests w/ & w/o frozen option to retrieve (by diff) the throttling status? Tuple<String, String> splitRef = splitQualifiedIndex(indexName); // Field caps on "remote:foo" should always return either empty or remote indices. But in case cluster's // detail is missing, it's going to be a local index. TODO: why would this happen? String cluster = splitRef.v1() == null ? clusterName : splitRef.v1(); indexInfos.add(new IndexInfo(cluster, splitRef.v2(), IndexType.STANDARD_INDEX)); } } filterResults(javaRegex, indexInfos, listener); }, ex -> { // see comment in resolveNames() if (ex instanceof NoSuchRemoteClusterException || ex instanceof ElasticsearchSecurityException) { filterResults(javaRegex, indexInfos, listener); } else { listener.onFailure(ex); } })); } else { filterResults(javaRegex, indexInfos, listener); } } private static void filterResults(String javaRegex, Set<IndexInfo> indexInfos, ActionListener<Set<IndexInfo>> listener) { // since the index name does not support ?, filter the results manually Pattern pattern = javaRegex != null ? Pattern.compile(javaRegex) : null; Set<IndexInfo> result = new TreeSet<>(Comparator.comparing(IndexInfo::cluster).thenComparing(IndexInfo::name)); for (IndexInfo indexInfo : indexInfos) { if (pattern == null || pattern.matcher(indexInfo.name()).matches()) { result.add(indexInfo); } } listener.onResponse(result); } private boolean clusterIsLocal(String clusterWildcard) { return clusterWildcard == null || simpleMatch(clusterWildcard, clusterName); } /** * Resolves a pattern to one (potentially compound meaning that spawns multiple indices) mapping. */ public void resolveAsMergedMapping( String indexWildcard, Set<String> fieldNames, IndicesOptions indicesOptions, Map<String, Object> runtimeMappings, boolean crossProjectEnabled, String projectRouting, ResolvedIndexExpressions resolvedIndexExpressions, ActionListener<IndexResolution> listener ) { IndicesOptions iOpts; if (crossProjectEnabled) { iOpts = CrossProjectIndexResolutionValidator.indicesOptionsForCrossProjectFanout(indicesOptions); } else { iOpts = indicesOptions; } FieldCapabilitiesRequest fieldRequest = createFieldCapsRequest(indexWildcard, fieldNames, iOpts, runtimeMappings); if (crossProjectEnabled) { fieldRequest.includeResolvedTo(true); } client.fieldCaps(fieldRequest, listener.delegateFailureAndWrap((l, response) -> { if (crossProjectEnabled) { Map<String, ResolvedIndexExpressions> resolvedRemotely = response.getResolvedRemotely(); ElasticsearchException ex = CrossProjectIndexResolutionValidator.validate( iOpts, projectRouting, resolvedIndexExpressions, resolvedRemotely ); if (ex != null) { l.onFailure(ex); return; } } l.onResponse(mergedMappings(typeRegistry, indexWildcard, response)); })); } /** * Resolves a pattern to one (potentially compound meaning that spawns multiple indices) mapping. */ public void resolveAsMergedMapping( String indexWildcard, Set<String> fieldNames, boolean includeFrozen, Map<String, Object> runtimeMappings, ActionListener<IndexResolution> listener ) { resolveAsMergedMapping(indexWildcard, fieldNames, includeFrozen, runtimeMappings, listener, (fieldName, types) -> null); } /** * Resolves a pattern to one (potentially compound meaning that spawns multiple indices) mapping. */ public void resolveAsMergedMapping( String indexWildcard, Set<String> fieldNames, boolean includeFrozen, Map<String, Object> runtimeMappings, ActionListener<IndexResolution> listener, BiFunction<String, Map<String, FieldCapabilities>, InvalidMappedField> specificValidityVerifier ) { FieldCapabilitiesRequest fieldRequest = createFieldCapsRequest(indexWildcard, fieldNames, includeFrozen, runtimeMappings); client.fieldCaps( fieldRequest, listener.delegateFailureAndWrap( (l, response) -> l.onResponse(mergedMappings(typeRegistry, indexWildcard, response, specificValidityVerifier, null, null)) ) ); } public void resolveAsMergedMapping( String indexWildcard, Set<String> fieldNames, boolean includeFrozen, Map<String, Object> runtimeMappings, ActionListener<IndexResolution> listener, BiFunction<String, Map<String, FieldCapabilities>, InvalidMappedField> specificValidityVerifier, BiConsumer<EsField, InvalidMappedField> fieldUpdater, Set<String> allowedMetadataFields ) { FieldCapabilitiesRequest fieldRequest = createFieldCapsRequest(indexWildcard, fieldNames, includeFrozen, runtimeMappings); client.fieldCaps( fieldRequest, listener.delegateFailureAndWrap( (l, response) -> l.onResponse( mergedMappings(typeRegistry, indexWildcard, response, specificValidityVerifier, fieldUpdater, allowedMetadataFields) ) ) ); } public static IndexResolution mergedMappings( DataTypeRegistry typeRegistry, String indexPattern, FieldCapabilitiesResponse fieldCapsResponse, BiFunction<String, Map<String, FieldCapabilities>, InvalidMappedField> specificValidityVerifier ) { return mergedMappings(typeRegistry, indexPattern, fieldCapsResponse, specificValidityVerifier, null, null); } public static IndexResolution mergedMappings( DataTypeRegistry typeRegistry, String indexPattern, FieldCapabilitiesResponse fieldCapsResponse, BiFunction<String, Map<String, FieldCapabilities>, InvalidMappedField> specificValidityVerifier, BiConsumer<EsField, InvalidMappedField> fieldUpdater, Set<String> allowedMetadataFields ) { if (fieldCapsResponse.getIndices().length == 0) { return IndexResolution.notFound(indexPattern); } BiFunction<String, Map<String, FieldCapabilities>, InvalidMappedField> validityVerifier = (fieldName, types) -> { InvalidMappedField f = specificValidityVerifier.apply(fieldName, types); if (f != null) { return f; } StringBuilder errorMessage = new StringBuilder(); boolean hasUnmapped = types.containsKey(UNMAPPED); if (types.size() > (hasUnmapped ? 2 : 1)) { // build the error message // and create a MultiTypeField for (Entry<String, FieldCapabilities> type : types.entrySet()) { // skip unmapped if (UNMAPPED.equals(type.getKey())) { continue; } if (errorMessage.length() > 0) { errorMessage.append(", "); } errorMessage.append("["); errorMessage.append(type.getKey()); errorMessage.append("] in "); errorMessage.append(Arrays.toString(type.getValue().indices())); } errorMessage.insert(0, "mapped as [" + (types.size() - (hasUnmapped ? 1 : 0)) + "] incompatible types: "); return new InvalidMappedField(fieldName, errorMessage.toString()); } // type is okay, check aggregation else { FieldCapabilities fieldCap = types.values().iterator().next(); // validate search/agg-able if (fieldCap.isAggregatable() && fieldCap.nonAggregatableIndices() != null) { errorMessage.append("mapped as aggregatable except in "); errorMessage.append(Arrays.toString(fieldCap.nonAggregatableIndices())); } if (fieldCap.isSearchable() && fieldCap.nonSearchableIndices() != null) { if (errorMessage.length() > 0) { errorMessage.append(","); } errorMessage.append("mapped as searchable except in "); errorMessage.append(Arrays.toString(fieldCap.nonSearchableIndices())); } if (errorMessage.length() > 0) { return new InvalidMappedField(fieldName, errorMessage.toString()); } } // everything checks return null; }; // merge all indices onto the same one List<EsIndex> indices = buildIndices( typeRegistry, null, fieldCapsResponse, null, i -> indexPattern, validityVerifier, fieldUpdater, allowedMetadataFields ); if (indices.size() > 1) { throw new QlIllegalArgumentException( "Incorrect merging of mappings (likely due to a bug) - expect at most one but found [{}]", indices.size() ); } String[] indexNames = fieldCapsResponse.getIndices(); if (indices.isEmpty()) { return IndexResolution.valid(new EsIndex(indexNames[0], emptyMap(), Set.of())); } else { EsIndex idx = indices.get(0); return IndexResolution.valid(new EsIndex(idx.name(), idx.mapping(), Set.of(indexNames))); } } public static IndexResolution mergedMappings( DataTypeRegistry typeRegistry, String indexPattern, FieldCapabilitiesResponse fieldCapsResponse ) { return mergedMappings(typeRegistry, indexPattern, fieldCapsResponse, (fieldName, types) -> null, null, null); } private static EsField createField( DataTypeRegistry typeRegistry, String fieldName, Map<String, Map<String, FieldCapabilities>> globalCaps, Map<String, EsField> hierarchicalMapping, Map<String, EsField> flattedMapping, Function<String, EsField> field ) { Map<String, EsField> parentProps = hierarchicalMapping; int dot = fieldName.lastIndexOf('.'); String fullFieldName = fieldName; EsField parent = null; if (dot >= 0) { String parentName = fieldName.substring(0, dot); fieldName = fieldName.substring(dot + 1); parent = flattedMapping.get(parentName); if (parent == null) { Map<String, FieldCapabilities> map = globalCaps.get(parentName); Function<String, EsField> fieldFunction; // lack of parent implies the field is an alias if (map == null) { // as such, create the field manually, marking the field to also be an alias fieldFunction = s -> createField(typeRegistry, s, OBJECT.esType(), null, new TreeMap<>(), false, true); } else { Iterator<FieldCapabilities> iterator = map.values().iterator(); FieldCapabilities parentCap = iterator.next(); if (iterator.hasNext() && UNMAPPED.equals(parentCap.getType())) { parentCap = iterator.next(); } final FieldCapabilities parentC = parentCap; fieldFunction = s -> createField( typeRegistry, s, parentC.getType(), parentC.getMetricType(), new TreeMap<>(), parentC.isAggregatable(), false ); } parent = createField(typeRegistry, parentName, globalCaps, hierarchicalMapping, flattedMapping, fieldFunction); } parentProps = parent.getProperties(); } EsField esField = field.apply(fieldName); if (parent instanceof UnsupportedEsField unsupportedParent) { String inherited = unsupportedParent.getInherited(); String type = unsupportedParent.getOriginalType(); if (inherited == null) { // mark the sub-field as unsupported, just like its parent, setting the first unsupported parent as the current one esField = new UnsupportedEsField(esField.getName(), type, unsupportedParent.getName(), esField.getProperties()); } else { // mark the sub-field as unsupported, just like its parent, but setting the first unsupported parent // as the parent's first unsupported grandparent esField = new UnsupportedEsField(esField.getName(), type, inherited, esField.getProperties()); } } parentProps.put(fieldName, esField); flattedMapping.put(fullFieldName, esField); return esField; } private static EsField createField( DataTypeRegistry typeRegistry, String fieldName, String typeName, TimeSeriesParams.MetricType metricType, Map<String, EsField> props, boolean isAggregateable, boolean isAlias ) { DataType esType = typeRegistry.fromEs(typeName, metricType); if (esType == TEXT) { return new TextEsField(fieldName, props, false, isAlias); } if (esType == KEYWORD) { int length = Short.MAX_VALUE; // TODO: to check whether isSearchable/isAggregateable takes into account the presence of the normalizer boolean normalized = false; return new KeywordEsField(fieldName, props, isAggregateable, length, normalized, isAlias); } if (esType == DATETIME) { return DateEsField.dateEsField(fieldName, props, isAggregateable); } if (esType == UNSUPPORTED) { String originalType = metricType == TimeSeriesParams.MetricType.COUNTER ? "counter" : typeName; return new UnsupportedEsField(fieldName, originalType, null, props); } return new EsField(fieldName, esType, props, isAggregateable, isAlias); } private static FieldCapabilitiesRequest createFieldCapsRequest( String index, Set<String> fieldNames, IndicesOptions indicesOptions, Map<String, Object> runtimeMappings ) { return new FieldCapabilitiesRequest().indices(Strings.commaDelimitedListToStringArray(index)) .fields(fieldNames.toArray(String[]::new)) .includeUnmapped(true) .runtimeFields(runtimeMappings) // lenient because we throw our own errors looking at the response e.g. if something was not resolved // also because this way security doesn't throw authorization exceptions but rather honors ignore_unavailable .indicesOptions(indicesOptions); } private static FieldCapabilitiesRequest createFieldCapsRequest( String index, Set<String> fieldNames, boolean includeFrozen, Map<String, Object> runtimeMappings ) { IndicesOptions indicesOptions = includeFrozen ? FIELD_CAPS_FROZEN_INDICES_OPTIONS : FIELD_CAPS_INDICES_OPTIONS; return createFieldCapsRequest(index, fieldNames, indicesOptions, runtimeMappings); } /** * Resolves a pattern to multiple, separate indices. Doesn't perform validation. */ public void resolveAsSeparateMappings( String indexWildcard, String javaRegex, boolean includeFrozen, Map<String, Object> runtimeMappings, ActionListener<List<EsIndex>> listener ) { FieldCapabilitiesRequest fieldRequest = createFieldCapsRequest(indexWildcard, ALL_FIELDS, includeFrozen, runtimeMappings); client.fieldCaps(fieldRequest, listener.delegateFailureAndWrap((delegate, response) -> { client.admin().indices().getAliases(createGetAliasesRequest(response, includeFrozen), wrap(aliases -> { delegate.onResponse(separateMappings(typeRegistry, javaRegex, response, aliases.getAliases())); }, ex -> { if (ex instanceof IndexNotFoundException || ex instanceof ElasticsearchSecurityException) { delegate.onResponse(separateMappings(typeRegistry, javaRegex, response, null)); } else { delegate.onFailure(ex); } })); })); } private static GetAliasesRequest createGetAliasesRequest(FieldCapabilitiesResponse response, boolean includeFrozen) { return new GetAliasesRequest(MasterNodeRequest.INFINITE_MASTER_NODE_TIMEOUT).aliases("*") .indices(response.getIndices()) .indicesOptions(includeFrozen ? FIELD_CAPS_FROZEN_INDICES_OPTIONS : FIELD_CAPS_INDICES_OPTIONS); } public static List<EsIndex> separateMappings( DataTypeRegistry typeRegistry, String javaRegex, FieldCapabilitiesResponse fieldCaps, Map<String, List<AliasMetadata>> aliases ) { return buildIndices(typeRegistry, javaRegex, fieldCaps, aliases, Function.identity(), (s, cap) -> null, null, null); } private static
IndexType
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/object/MappingSqlQueryWithParameters.java
{ "start": 1987, "end": 3711 }
class ____<T extends @Nullable Object> extends SqlQuery<T> { /** * Constructor to allow use as a JavaBean. */ public MappingSqlQueryWithParameters() { } /** * Convenient constructor with DataSource and SQL string. * @param ds the DataSource to use to get connections * @param sql the SQL to run */ public MappingSqlQueryWithParameters(DataSource ds, String sql) { super(ds, sql); } /** * Implementation of protected abstract method. This invokes the subclass's * implementation of the mapRow() method. */ @Override protected RowMapper<T> newRowMapper(@Nullable Object @Nullable [] parameters, @Nullable Map<?, ?> context) { return new RowMapperImpl(parameters, context); } /** * Subclasses must implement this method to convert each row * of the ResultSet into an object of the result type. * @param rs the ResultSet we're working through * @param rowNum row number (from 0) we're up to * @param parameters to the query (passed to the execute() method). * Subclasses are rarely interested in these. * It can be {@code null} if there are no parameters. * @param context passed to the execute() method. * It can be {@code null} if no contextual information is need. * @return an object of the result type * @throws SQLException if there's an error extracting data. * Subclasses can simply not catch SQLExceptions, relying on the * framework to clean up. */ protected abstract T mapRow(ResultSet rs, int rowNum, @Nullable Object @Nullable [] parameters, @Nullable Map<?, ?> context) throws SQLException; /** * Implementation of RowMapper that calls the enclosing * class's {@code mapRow} method for each row. */ protected
MappingSqlQueryWithParameters
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/TypeInferenceUtil.java
{ "start": 3298, "end": 12570 }
class ____ { /** * Runs the entire type inference process. * * @param typeInference type inference of the current call * @param callContext call context of the current call * @param surroundingInfo information about the outer wrapping call of a current function call * for performing input type inference */ public static Result runTypeInference( TypeInference typeInference, CallContext callContext, @Nullable SurroundingInfo surroundingInfo) { try { return runTypeInferenceInternal(typeInference, callContext, surroundingInfo); } catch (ValidationException e) { throw createInvalidCallException(callContext, e); } catch (Throwable t) { throw createUnexpectedException(callContext, t); } } /** Casts the call's argument if necessary. */ public static CallContext castArguments( TypeInference typeInference, CallContext callContext, @Nullable DataType outputType) { return castArguments(typeInference, callContext, outputType, true); } private static CallContext castArguments( TypeInference typeInference, CallContext callContext, @Nullable DataType outputType, boolean throwOnInferInputFailure) { final List<DataType> actualTypes = callContext.getArgumentDataTypes(); typeInference .getStaticArguments() .ifPresent( staticArgs -> { if (actualTypes.size() != staticArgs.size()) { throw new ValidationException( String.format( "Invalid number of arguments. %d arguments expected after argument expansion but %d passed.", staticArgs.size(), actualTypes.size())); } }); final CastCallContext castCallContext = inferInputTypes(typeInference, callContext, outputType, throwOnInferInputFailure); // final check if the call is valid after casting final List<DataType> expectedTypes = castCallContext.getArgumentDataTypes(); for (int pos = 0; pos < actualTypes.size(); pos++) { final DataType expectedType = expectedTypes.get(pos); final DataType actualType = actualTypes.get(pos); if (!supportsImplicitCast(actualType.getLogicalType(), expectedType.getLogicalType())) { if (!throwOnInferInputFailure) { // abort the adaption, e.g. if a NULL is passed for a NOT NULL argument return callContext; } throw new ValidationException( String.format( "Invalid argument type at position %d. Data type %s expected but %s passed.", pos, expectedType, actualType)); } } return castCallContext; } /** * Infers an output type using the given {@link TypeStrategy}. It assumes that input arguments * have been adapted before if necessary. */ public static DataType inferOutputType( CallContext callContext, TypeStrategy outputTypeStrategy) { final Optional<DataType> potentialOutputType = outputTypeStrategy.inferType(callContext); if (potentialOutputType.isEmpty()) { throw new ValidationException( "Could not infer an output type for the given arguments."); } final DataType outputType = potentialOutputType.get(); if (isUnknown(outputType)) { throw new ValidationException( "Could not infer an output type for the given arguments. Untyped NULL received."); } return outputType; } /** * Infers {@link StateInfo}s using the given {@link StateTypeStrategy}s. It assumes that input * arguments have been adapted before if necessary. */ public static LinkedHashMap<String, StateInfo> inferStateInfos( CallContext callContext, LinkedHashMap<String, StateTypeStrategy> stateTypeStrategies) { return stateTypeStrategies.entrySet().stream() .map( e -> Map.entry( e.getKey(), inferStateInfo(callContext, e.getKey(), e.getValue()))) .collect( Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (x, y) -> y, LinkedHashMap::new)); } /** Generates a signature of the given {@link FunctionDefinition}. */ public static String generateSignature( TypeInference typeInference, String name, FunctionDefinition definition) { final List<StaticArgument> staticArguments = typeInference.getStaticArguments().orElse(null); if (staticArguments != null) { return formatStaticArguments(name, staticArguments); } return typeInference.getInputTypeStrategy().getExpectedSignatures(definition).stream() .map(s -> formatSignature(name, s)) .collect(Collectors.joining("\n")); } /** Returns an exception for invalid input arguments. */ public static ValidationException createInvalidInputException( TypeInference typeInference, CallContext callContext, ValidationException cause) { return new ValidationException( String.format( "Invalid input arguments. Expected signatures are:\n%s", generateSignature( typeInference, callContext.getName(), callContext.getFunctionDefinition())), cause); } /** Returns an exception for an invalid call to a function. */ public static ValidationException createInvalidCallException( CallContext callContext, ValidationException cause) { return new ValidationException( String.format( "Invalid function call:\n%s(%s)", callContext.getName(), callContext.getArgumentDataTypes().stream() .map(DataType::toString) .collect(Collectors.joining(", "))), cause); } /** Returns an exception for an unexpected error during type inference. */ public static TableException createUnexpectedException( CallContext callContext, Throwable cause) { return new TableException( String.format( "Unexpected error in type inference logic of function '%s'. This is a bug.", callContext.getName()), cause); } /** * Validates argument counts. * * @param argumentCount expected argument count * @param actualCount actual argument count * @param throwOnFailure if true, the function throws a {@link ValidationException} if the * actual value does not meet the expected argument count * @return a boolean indicating if expected argument counts match the actual counts */ public static boolean validateArgumentCount( ArgumentCount argumentCount, int actualCount, boolean throwOnFailure) { final int minCount = argumentCount.getMinCount().orElse(0); if (actualCount < minCount) { if (throwOnFailure) { throw new ValidationException( String.format( "Invalid number of arguments. At least %d arguments expected but %d passed.", minCount, actualCount)); } return false; } final int maxCount = argumentCount.getMaxCount().orElse(Integer.MAX_VALUE); if (actualCount > maxCount) { if (throwOnFailure) { throw new ValidationException( String.format( "Invalid number of arguments. At most %d arguments expected but %d passed.", maxCount, actualCount)); } return false; } if (!argumentCount.isValidCount(actualCount)) { if (throwOnFailure) { throw new ValidationException( String.format( "Invalid number of arguments. %d arguments passed.", actualCount)); } return false; } return true; } /** * Information what the outer world (i.e. an outer wrapping call) expects from the current * function call. This can be helpful for an {@link InputTypeStrategy}. * * @see CallContext#getOutputDataType() */ @Internal public
TypeInferenceUtil
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/Condition_constructor_with_text_description_Test.java
{ "start": 862, "end": 1562 }
class ____ { @Test void should_set_description() { String text = "your eyes can deceive you; don't trust them"; Condition<Object> condition = new Condition<Object>(text) { @Override public boolean matches(Object value) { return false; } }; assertThat(condition.description.value()).isEqualTo(text); } @Test void should_set_empty_description_if_description_is_null() { Condition<Object> condition = new Condition<Object>((String) null) { @Override public boolean matches(Object value) { return false; } }; assertThat(condition.description.value()).isEmpty(); } }
Condition_constructor_with_text_description_Test
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/saml/SamlPrivateAttributePredicate.java
{ "start": 1199, "end": 3705 }
class ____ implements Predicate<Attribute> { private static final Logger logger = LogManager.getLogger(SamlPrivateAttributePredicate.class); private static final Predicate<Attribute> MATCH_NONE = new Predicate<Attribute>() { @Override public boolean test(Attribute attribute) { return false; } @Override public String toString() { return "<matching no SAML private attributes>"; } }; private final Predicate<Attribute> predicate; SamlPrivateAttributePredicate(RealmConfig config) { this.predicate = buildPrivateAttributesPredicate(config); } private static Predicate<Attribute> buildPrivateAttributesPredicate(RealmConfig config) { if (false == config.hasSetting(PRIVATE_ATTRIBUTES)) { logger.trace("No SAML private attributes setting configured."); return MATCH_NONE; } final List<String> attributesList = config.getSetting(PRIVATE_ATTRIBUTES); if (attributesList == null || attributesList.isEmpty()) { logger.trace("No SAML private attributes configured for setting [{}].", PRIVATE_ATTRIBUTES); return MATCH_NONE; } final Set<String> attributesSet = attributesList.stream() .filter(name -> name != null && false == name.isBlank()) .collect(Collectors.toUnmodifiableSet()); if (attributesSet.isEmpty()) { return MATCH_NONE; } logger.trace("SAML private attributes configured: {}", attributesSet); return new Predicate<>() { @Override public boolean test(Attribute attribute) { if (attribute == null) { return false; } if (attribute.getName() != null && attributesSet.contains(attribute.getName())) { return true; } return attribute.getFriendlyName() != null && attributesSet.contains(attribute.getFriendlyName()); } @Override public String toString() { return "<matching " + attributesSet + " SAML private attributes>"; } }; } @Override public boolean test(Attribute attribute) { return predicate.test(attribute); } @Override public String toString() { return this.getClass().getSimpleName() + " {predicate=" + predicate + "}"; } }
SamlPrivateAttributePredicate
java
square__retrofit
retrofit/src/main/java/retrofit2/http/Query.java
{ "start": 2558, "end": 2778 }
interface ____ { /** The query parameter name. */ String value(); /** * Specifies whether the parameter {@linkplain #value() name} and value are already URL encoded. */ boolean encoded() default false; }
Query
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/properties/PropertiesComponentResolvedValueTest.java
{ "start": 1063, "end": 4179 }
class ____ extends ContextTestSupport { @Test public void testResolved() { org.apache.camel.spi.PropertiesComponent pc = context.getPropertiesComponent(); Assertions.assertTrue(pc.getResolvedValue("unknown").isEmpty()); Assertions.assertTrue(pc.getResolvedValue("greeting").isPresent()); Assertions.assertTrue(pc.getResolvedValue("cool.end").isPresent()); Assertions.assertTrue(pc.getResolvedValue("place").isPresent()); Assertions.assertTrue(pc.getResolvedValue("myserver").isPresent()); // added initial via code var p = pc.getResolvedValue("greeting").get(); Assertions.assertEquals("greeting", p.name()); Assertions.assertEquals("Hello World", p.originalValue()); Assertions.assertEquals("Hello World", p.value()); Assertions.assertEquals("Hi", p.defaultValue()); Assertions.assertEquals("InitialProperties", p.source()); // from properties file p = pc.getResolvedValue("cool.end").get(); Assertions.assertEquals("cool.end", p.name()); Assertions.assertEquals("mock:result", p.originalValue()); Assertions.assertEquals("mock:result", p.value()); Assertions.assertNull(p.defaultValue()); Assertions.assertEquals("classpath:org/apache/camel/component/properties/myproperties.properties", p.source()); // no source but using default value p = pc.getResolvedValue("place").get(); Assertions.assertEquals("place", p.name()); Assertions.assertEquals("Paris", p.originalValue()); Assertions.assertEquals("Paris", p.value()); Assertions.assertEquals("Paris", p.defaultValue()); Assertions.assertNull(p.source()); // nested p = pc.getResolvedValue("myserver").get(); Assertions.assertEquals("myserver", p.name()); Assertions.assertEquals("127.0.0.1", p.value()); Assertions.assertEquals("{{env:MY_SERVER:127.0.0.1}}", p.originalValue()); Assertions.assertNull(p.defaultValue()); Assertions.assertEquals("env", p.source()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .setBody(constant("{{greeting:Hi}}")) .setHeader("bar", constant("{{?place:Paris}}")) .setHeader("server", constant("{{myserver}}")) .to("{{cool.end}}"); } }; } @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); context.getPropertiesComponent().setLocation("classpath:org/apache/camel/component/properties/myproperties.properties"); context.getPropertiesComponent().addInitialProperty("greeting", "Hello World"); context.getPropertiesComponent().addInitialProperty("myserver", "{{env:MY_SERVER:127.0.0.1}}"); return context; } }
PropertiesComponentResolvedValueTest
java
google__guice
core/test/com/google/inject/ProvisionListenerTest.java
{ "start": 27741, "end": 28335 }
class ____ implements ProvisionListener { private final Class<?> notifyType; private final String firstSource; private final AtomicBoolean notified; public SpecialChecker(Class<?> notifyType, String firstSource, AtomicBoolean notified) { this.notifyType = notifyType; this.firstSource = firstSource; this.notified = notified; } @Override public <T> void onProvision(ProvisionInvocation<T> provision) { notified.set(true); assertEquals(notifyType, provision.getBinding().getKey().getRawType()); } } private static
SpecialChecker
java
apache__camel
components/camel-mvel/src/main/java/org/apache/camel/component/mvel/MvelComponent.java
{ "start": 1230, "end": 3798 }
class ____ extends DefaultComponent { @Metadata(defaultValue = "true", description = "Sets whether to use resource content cache or not") private boolean contentCache = true; @Metadata private boolean allowTemplateFromHeader; @Metadata private boolean allowContextMapAll; public MvelComponent() { } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { boolean cache = getAndRemoveParameter(parameters, "contentCache", Boolean.class, contentCache); MvelEndpoint answer = new MvelEndpoint(uri, this, remaining); answer.setContentCache(cache); answer.setAllowTemplateFromHeader(allowTemplateFromHeader); answer.setAllowContextMapAll(allowContextMapAll); setProperties(answer, parameters); // if its a http resource then append any remaining parameters and update the resource uri if (ResourceHelper.isHttpUri(remaining)) { remaining = ResourceHelper.appendParameters(remaining, parameters); answer.setResourceUri(remaining); } return answer; } public boolean isContentCache() { return contentCache; } /** * Sets whether to use resource content cache or not */ public void setContentCache(boolean contentCache) { this.contentCache = contentCache; } public boolean isAllowTemplateFromHeader() { return allowTemplateFromHeader; } /** * Whether to allow to use resource template from header or not (default false). * * Enabling this allows to specify dynamic templates via message header. However this can be seen as a potential * security vulnerability if the header is coming from a malicious user, so use this with care. */ public void setAllowTemplateFromHeader(boolean allowTemplateFromHeader) { this.allowTemplateFromHeader = allowTemplateFromHeader; } public boolean isAllowContextMapAll() { return allowContextMapAll; } /** * Sets whether the context map should allow access to all details. By default only the message body and headers can * be accessed. This option can be enabled for full access to the current Exchange and CamelContext. Doing so impose * a potential security risk as this opens access to the full power of CamelContext API. */ public void setAllowContextMapAll(boolean allowContextMapAll) { this.allowContextMapAll = allowContextMapAll; } }
MvelComponent
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/PluggableAuthenticatorChainTests.java
{ "start": 1641, "end": 1763 }
class ____ extends ESTestCase { private ThreadContext threadContext; private static
PluggableAuthenticatorChainTests
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/inheritance/tableperclass/abstractparent/AbstractEntity.java
{ "start": 575, "end": 802 }
class ____ { @Id public Long id; @Column public String commonField; public AbstractEntity() { } protected AbstractEntity(Long id, String commonField) { this.commonField = commonField; this.id = id; } }
AbstractEntity
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/impl/TestErrorTranslation.java
{ "start": 5680, "end": 6346 }
class ____ extends IOException { public static final String MESSAGE = "no-arg constructor"; public NoConstructorIOE() { super(MESSAGE); } } @Test public void testMultiObjectExceptionFilledIn() throws Throwable { MultiObjectDeleteException ase = new MultiObjectDeleteException(Collections.emptyList()); RetryPolicyContext context = RetryPolicyContext.builder() .exception(ase) .build(); RetryOnErrorCodeCondition retry = RetryOnErrorCodeCondition.create(""); assertThat(retry.shouldRetry(context)) .describedAs("retry policy of MultiObjectException") .isFalse(); } }
NoConstructorIOE
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/common/validation/SourceDestValidator.java
{ "start": 4432, "end": 10215 }
class ____ { private final ClusterState state; private final IndexNameExpressionResolver indexNameExpressionResolver; private final RemoteClusterService remoteClusterService; private final RemoteClusterLicenseChecker remoteClusterLicenseChecker; private final IngestService ingestService; private final String[] source; private final String destIndex; private final String destPipeline; private final String nodeName; private final String license; private ValidationException validationException = null; private SortedSet<String> resolvedSource = null; private SortedSet<String> resolvedRemoteSource = null; private String resolvedDest = null; Context( final ClusterState state, final IndexNameExpressionResolver indexNameExpressionResolver, final RemoteClusterService remoteClusterService, final RemoteClusterLicenseChecker remoteClusterLicenseChecker, final IngestService ingestService, final String[] source, final String destIndex, final String destPipeline, final String nodeName, final String license ) { this.state = state; this.indexNameExpressionResolver = indexNameExpressionResolver; this.remoteClusterService = remoteClusterService; this.remoteClusterLicenseChecker = remoteClusterLicenseChecker; this.ingestService = ingestService; this.source = source; this.destIndex = destIndex; this.destPipeline = destPipeline; this.nodeName = nodeName; this.license = license; } public ClusterState getState() { return state; } public RemoteClusterService getRemoteClusterService() { return remoteClusterService; } public RemoteClusterLicenseChecker getRemoteClusterLicenseChecker() { return remoteClusterLicenseChecker; } public IndexNameExpressionResolver getIndexNameExpressionResolver() { return indexNameExpressionResolver; } public IngestService getIngestService() { return ingestService; } public boolean isRemoteSearchEnabled() { return remoteClusterLicenseChecker != null; } public String[] getSource() { return source; } public String getDestIndex() { return destIndex; } public String getNodeName() { return nodeName; } public String getLicense() { return license; } public SortedSet<String> resolveSource() { if (resolvedSource == null) { resolveLocalAndRemoteSource(); } return resolvedSource; } public SortedSet<String> resolveRemoteSource() { if (resolvedRemoteSource == null) { resolveLocalAndRemoteSource(); } return resolvedRemoteSource; } public String resolveDest() { if (resolvedDest == null) { try { Index singleWriteIndex = indexNameExpressionResolver.concreteWriteIndex( state, IndicesOptions.lenientExpandOpen(), destIndex, true, false ); resolvedDest = singleWriteIndex != null ? singleWriteIndex.getName() : destIndex; } catch (IllegalArgumentException e) { // stop here as we can not return a single dest index addValidationError(e.getMessage()); throw validationException; } } return resolvedDest; } public ValidationException addValidationError(String error, Object... args) { if (validationException == null) { validationException = new ValidationException(); } validationException.addValidationError(getMessage(error, args)); return validationException; } public ValidationException getValidationException() { return validationException; } // convenience method to make testing easier public Set<String> getRegisteredRemoteClusterNames() { return remoteClusterService.getRegisteredRemoteClusterNames(); } // convenience method to make testing easier public TransportVersion getRemoteClusterVersion(String cluster) { return remoteClusterService.getConnection(cluster).getTransportVersion(); } private void resolveLocalAndRemoteSource() { resolvedSource = new TreeSet<>(Arrays.asList(source)); resolvedRemoteSource = new TreeSet<>(RemoteClusterLicenseChecker.remoteIndices(resolvedSource)); resolvedSource.removeAll(resolvedRemoteSource); // special case: if indexNameExpressionResolver gets an empty list it treats it as _all if (resolvedSource.isEmpty() == false) { resolvedSource = new TreeSet<>( Arrays.asList( indexNameExpressionResolver.concreteIndexNames( state, DEFAULT_INDICES_OPTIONS_FOR_VALIDATION, true, resolvedSource.toArray(Strings.EMPTY_ARRAY) ) ) ); } } } public
Context
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/StreamingOutputStream.java
{ "start": 238, "end": 300 }
class ____ extends ByteArrayOutputStream { }
StreamingOutputStream
java
apache__spark
resource-managers/yarn/src/main/java/org/apache/spark/deploy/yarn/ProxyUtils.java
{ "start": 1801, "end": 1867 }
class ____ implements Hamlet.__ { // Empty } public static
__
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/internal/QueryParameterBindingsImpl.java
{ "start": 12684, "end": 13281 }
class ____ implements MutableCacheKeyBuilder { final List<Object> values; int hashCode; public MutableCacheKeyImpl(int parameterBindingMapSize) { values = new ArrayList<>( parameterBindingMapSize ); } @Override public void addValue(Object value) { values.add( value ); } @Override public void addHashCode(int hashCode) { this.hashCode = 37 * this.hashCode + hashCode; } @Override public QueryKey.ParameterBindingsMemento build() { return new ParameterBindingsMementoImpl( values.toArray( new Object[0] ), hashCode ); } } private static
MutableCacheKeyImpl
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/alterTable/MySqlAlterTableAddIndex_5.java
{ "start": 1053, "end": 2369 }
class ____ extends TestCase { public void test_alter_first() throws Exception { String sql = "ALTER TABLE t_order ADD UNIQUE GLOBAL INDEX `g_i_buyer` (`buyer_id`) COVERING (order_snapshot) dbpartition by hash(`buyer_id`) tbpartition by hash(`buyer_id`);"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); assertEquals("ALTER TABLE t_order\n" + "\tADD UNIQUE GLOBAL INDEX `g_i_buyer` (`buyer_id`) COVERING (order_snapshot) DBPARTITION BY hash(`buyer_id`) TBPARTITION BY hash(`buyer_id`);", SQLUtils.toMySqlString(stmt)); assertEquals("alter table t_order\n" + "\tadd unique global index `g_i_buyer` (`buyer_id`) covering (order_snapshot) dbpartition by hash(`buyer_id`) tbpartition by hash(`buyer_id`);", SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); SchemaStatVisitor visitor = new SQLUtils().createSchemaStatVisitor(JdbcConstants.MYSQL); stmt.accept(visitor); TableStat tableStat = visitor.getTableStat("t_order"); assertNotNull(tableStat); assertEquals(1, tableStat.getAlterCount()); assertEquals(1, tableStat.getCreateIndexCount()); } }
MySqlAlterTableAddIndex_5
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/api/protocolrecords/impl/pb/KillTaskAttemptResponsePBImpl.java
{ "start": 1126, "end": 1986 }
class ____ extends ProtoBase<KillTaskAttemptResponseProto> implements KillTaskAttemptResponse { KillTaskAttemptResponseProto proto = KillTaskAttemptResponseProto.getDefaultInstance(); KillTaskAttemptResponseProto.Builder builder = null; boolean viaProto = false; public KillTaskAttemptResponsePBImpl() { builder = KillTaskAttemptResponseProto.newBuilder(); } public KillTaskAttemptResponsePBImpl(KillTaskAttemptResponseProto proto) { this.proto = proto; viaProto = true; } public KillTaskAttemptResponseProto getProto() { proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = KillTaskAttemptResponseProto.newBuilder(proto); } viaProto = false; } }
KillTaskAttemptResponsePBImpl
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/localdate/LocalDateAssert_isToday_Test.java
{ "start": 1145, "end": 2044 }
class ____ extends LocalDateAssertBaseTest { @Test void should_pass_if_actual_is_today() { assertThat(REFERENCE).isToday(); } @Test void should_fail_if_actual_is_before_today() { // WHEN ThrowingCallable code = () -> assertThat(BEFORE).isToday(); // THEN assertThatAssertionErrorIsThrownBy(code).withMessage(shouldBeToday(BEFORE).create()); } @Test void should_fail_if_actual_is_after_today() { // WHEN ThrowingCallable code = () -> assertThat(AFTER).isToday(); // THEN assertThatAssertionErrorIsThrownBy(code).withMessage(shouldBeToday(AFTER).create()); } @Test void should_fail_if_actual_is_null() { // GIVEN LocalDate actual = null; // WHEN ThrowingCallable code = () -> assertThat(actual).isToday(); // THEN assertThatAssertionErrorIsThrownBy(code).withMessage(actualIsNull()); } }
LocalDateAssert_isToday_Test
java
elastic__elasticsearch
libs/tdigest/src/main/java/org/elasticsearch/tdigest/IntAVLTree.java
{ "start": 15644, "end": 16778 }
class ____ implements Releasable, Accountable { private static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(IntStack.class); private final TDigestArrays arrays; private boolean closed = false; private final TDigestIntArray stack; private int size; IntStack(TDigestArrays arrays) { this.arrays = arrays; stack = arrays.newIntArray(0); size = 0; } @Override public long ramBytesUsed() { return SHALLOW_SIZE + stack.ramBytesUsed(); } int size() { return size; } int pop() { int value = stack.get(--size); stack.resize(size); return value; } void push(int v) { stack.resize(++size); stack.set(size - 1, v); } @Override public void close() { if (closed == false) { closed = true; arrays.adjustBreaker(-SHALLOW_SIZE); stack.close(); } } } private static
IntStack
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientService.java
{ "start": 1392, "end": 4161 }
class ____ implements ReactiveOAuth2AuthorizedClientService { private final Map<OAuth2AuthorizedClientId, OAuth2AuthorizedClient> authorizedClients = new ConcurrentHashMap<>(); private final ReactiveClientRegistrationRepository clientRegistrationRepository; /** * Constructs an {@code InMemoryReactiveOAuth2AuthorizedClientService} using the * provided parameters. * @param clientRegistrationRepository the repository of client registrations */ public InMemoryReactiveOAuth2AuthorizedClientService( ReactiveClientRegistrationRepository clientRegistrationRepository) { Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null"); this.clientRegistrationRepository = clientRegistrationRepository; } @Override @SuppressWarnings("unchecked") public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId, String principalName) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.hasText(principalName, "principalName cannot be empty"); return (Mono<T>) this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId) .mapNotNull((clientRegistration) -> { OAuth2AuthorizedClientId id = new OAuth2AuthorizedClientId(clientRegistrationId, principalName); OAuth2AuthorizedClient cachedAuthorizedClient = this.authorizedClients.get(id); if (cachedAuthorizedClient == null) { return null; } return new OAuth2AuthorizedClient(clientRegistration, cachedAuthorizedClient.getPrincipalName(), cachedAuthorizedClient.getAccessToken(), cachedAuthorizedClient.getRefreshToken()); }); } @Override public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) { Assert.notNull(authorizedClient, "authorizedClient cannot be null"); Assert.notNull(principal, "principal cannot be null"); return Mono.fromRunnable(() -> { OAuth2AuthorizedClientId identifier = new OAuth2AuthorizedClientId( authorizedClient.getClientRegistration().getRegistrationId(), principal.getName()); this.authorizedClients.put(identifier, authorizedClient); }); } @Override public Mono<Void> removeAuthorizedClient(String clientRegistrationId, String principalName) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.hasText(principalName, "principalName cannot be empty"); // @formatter:off return this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId) .map((clientRegistration) -> new OAuth2AuthorizedClientId(clientRegistrationId, principalName)) .doOnNext(this.authorizedClients::remove) .then(Mono.empty()); // @formatter:on } }
InMemoryReactiveOAuth2AuthorizedClientService
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/config/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfig.java
{ "start": 2264, "end": 2355 }
class ____ { @Bean public String foo() { return "Resolver Foo"; } }
ResolverConfig
java
apache__camel
components/camel-aws/camel-aws2-sqs/src/main/java/org/apache/camel/component/aws2/sqs/Sqs2MessageHelper.java
{ "start": 1032, "end": 4737 }
class ____ { public static final String TYPE_STRING = "String"; public static final String TYPE_BINARY = "Binary"; private Sqs2MessageHelper() { } public static MessageAttributeValue toMessageAttributeValue(Object value) { if (value instanceof String && !((String) value).isEmpty()) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType(TYPE_STRING); mav.stringValue((String) value); return mav.build(); } else if (value instanceof ByteBuffer) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType(TYPE_BINARY); mav.binaryValue(SdkBytes.fromByteBuffer((ByteBuffer) value)); return mav.build(); } else if (value instanceof byte[]) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType(TYPE_BINARY); mav.binaryValue(SdkBytes.fromByteArray((byte[]) value)); return mav.build(); } else if (value instanceof Boolean) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType("Number.Boolean"); mav.stringValue(Boolean.TRUE.equals(value) ? "1" : "0"); return mav.build(); } else if (value instanceof Number) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); final String dataType; if (value instanceof Integer) { dataType = "Number.int"; } else if (value instanceof Byte) { dataType = "Number.byte"; } else if (value instanceof Double) { dataType = "Number.double"; } else if (value instanceof Float) { dataType = "Number.float"; } else if (value instanceof Long) { dataType = "Number.long"; } else if (value instanceof Short) { dataType = "Number.short"; } else { dataType = "Number"; } mav.dataType(dataType); mav.stringValue(value.toString()); return mav.build(); } else if (value instanceof Date) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType(TYPE_STRING); mav.stringValue(value.toString()); return mav.build(); } return null; } public static Object fromMessageAttributeValue(MessageAttributeValue mav) { if (mav == null) { return null; } if (mav.binaryValue() != null) { return mav.binaryValue(); } else if (mav.stringValue() != null) { String s = mav.stringValue(); String dt = mav.dataType(); if (dt == null || TYPE_STRING.equals(dt)) { return s; } else if ("Number.Boolean".equals(dt)) { return "1".equals(s) ? Boolean.TRUE : Boolean.FALSE; } else if ("Number.int".equals(dt)) { return Integer.valueOf(s); } else if ("Number.byte".equals(dt)) { return Byte.valueOf(s); } else if ("Number.double".equals(dt)) { return Double.valueOf(s); } else if ("Number.float".equals(dt)) { return Float.valueOf(s); } else if ("Number.long".equals(dt)) { return Long.valueOf(s); } else if ("Number.short".equals(dt)) { return Short.valueOf(s); } return s; } return null; } }
Sqs2MessageHelper
java
google__dagger
javatests/artifacts/dagger-ksp/java-app/src/main/java/app/SimpleComponentClasses.java
{ "start": 1186, "end": 1484 }
class ____ { @Provides static ProvidedFoo provideFoo() { return new ProvidedFoo(); } @Provides @Singleton static ScopedProvidedFoo provideScopedFoo() { return new ScopedProvidedFoo(); } } @Singleton @Component(modules = SimpleModule.class)
SimpleModule
java
quarkusio__quarkus
extensions/reactive-mssql-client/deployment/src/test/java/io/quarkus/reactive/mssql/client/ConfigUrlMissingDefaultDatasourceStaticInjectionTest.java
{ "start": 1789, "end": 1987 }
class ____ { @Inject Pool pool; public CompletionStage<?> usePool() { return pool.getConnection().toCompletionStage().toCompletableFuture(); } } }
MyBean
java
apache__flink
flink-formats/flink-orc/src/main/java/org/apache/flink/orc/util/OrcFormatStatisticsReportUtil.java
{ "start": 2172, "end": 9944 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(OrcFormatStatisticsReportUtil.class); public static TableStats getTableStatistics( List<Path> files, DataType producedDataType, Configuration hadoopConfig) { return getTableStatistics( files, producedDataType, hadoopConfig, Runtime.getRuntime().availableProcessors()); } public static TableStats getTableStatistics( List<Path> files, DataType producedDataType, Configuration hadoopConfig, int statisticsThreadNum) { ExecutorService executorService = null; try { long rowCount = 0; Map<String, ColumnStatistics> columnStatisticsMap = new HashMap<>(); RowType producedRowType = (RowType) producedDataType.getLogicalType(); executorService = Executors.newFixedThreadPool( statisticsThreadNum, new ExecutorThreadFactory("orc-get-table-statistic-worker")); List<Future<FileOrcStatistics>> fileRowCountFutures = new ArrayList<>(); for (Path file : files) { fileRowCountFutures.add( executorService.submit(new OrcFileRowCountCalculator(hadoopConfig, file))); } for (Future<FileOrcStatistics> fileCountFuture : fileRowCountFutures) { FileOrcStatistics fileOrcStatistics = fileCountFuture.get(); rowCount += fileOrcStatistics.getRowCount(); for (String column : producedRowType.getFieldNames()) { int fieldIdx = fileOrcStatistics.getFieldNames().indexOf(column); if (fieldIdx >= 0) { int colId = fileOrcStatistics.getColumnTypes().get(fieldIdx).getId(); ColumnStatistics statistic = fileOrcStatistics.getStatistics()[colId]; updateStatistics(statistic, column, columnStatisticsMap); } } } Map<String, ColumnStats> columnStatsMap = convertToColumnStats(rowCount, columnStatisticsMap, producedRowType); return new TableStats(rowCount, columnStatsMap); } catch (Exception e) { LOG.warn("Reporting statistics failed for Orc format: {}", e.getMessage()); return TableStats.UNKNOWN; } finally { if (executorService != null) { executorService.shutdownNow(); } } } private static void updateStatistics( ColumnStatistics statistic, String column, Map<String, ColumnStatistics> columnStatisticsMap) { ColumnStatistics previousStatistics = columnStatisticsMap.get(column); if (previousStatistics == null) { columnStatisticsMap.put(column, statistic); } else { if (previousStatistics instanceof ColumnStatisticsImpl) { ((ColumnStatisticsImpl) previousStatistics).merge((ColumnStatisticsImpl) statistic); } } } private static Map<String, ColumnStats> convertToColumnStats( long totalRowCount, Map<String, ColumnStatistics> columnStatisticsMap, RowType logicalType) { Map<String, ColumnStats> columnStatsMap = new HashMap<>(); for (String column : logicalType.getFieldNames()) { ColumnStatistics columnStatistics = columnStatisticsMap.get(column); if (columnStatistics == null) { continue; } ColumnStats columnStats = convertToColumnStats( totalRowCount, logicalType.getTypeAt(logicalType.getFieldIndex(column)), columnStatistics); columnStatsMap.put(column, columnStats); } return columnStatsMap; } private static ColumnStats convertToColumnStats( long totalRowCount, LogicalType logicalType, ColumnStatistics columnStatistics) { ColumnStats.Builder builder = new ColumnStats.Builder().setNdv(null).setAvgLen(null).setMaxLen(null); if (!columnStatistics.hasNull()) { builder.setNullCount(0L); } else { builder.setNullCount(totalRowCount - columnStatistics.getNumberOfValues()); } // For complex types: ROW, ARRAY, MAP. The returned statistics have wrong null count // value, so now complex types stats return null. switch (logicalType.getTypeRoot()) { case BOOLEAN: break; case TINYINT: case SMALLINT: case INTEGER: case BIGINT: if (columnStatistics instanceof IntegerColumnStatistics) { builder.setMax(((IntegerColumnStatistics) columnStatistics).getMaximum()) .setMin(((IntegerColumnStatistics) columnStatistics).getMinimum()); break; } else { return null; } case FLOAT: case DOUBLE: if (columnStatistics instanceof DoubleColumnStatistics) { builder.setMax(((DoubleColumnStatistics) columnStatistics).getMaximum()) .setMin(((DoubleColumnStatistics) columnStatistics).getMinimum()); break; } else { return null; } case CHAR: case VARCHAR: if (columnStatistics instanceof StringColumnStatistics) { builder.setMax(((StringColumnStatistics) columnStatistics).getMaximum()) .setMin(((StringColumnStatistics) columnStatistics).getMinimum()); break; } else { return null; } case DATE: if (columnStatistics instanceof DateColumnStatistics) { Date maximum = (Date) ((DateColumnStatistics) columnStatistics).getMaximum(); Date minimum = (Date) ((DateColumnStatistics) columnStatistics).getMinimum(); builder.setMax(maximum).setMin(minimum); break; } else { return null; } case TIMESTAMP_WITHOUT_TIME_ZONE: case TIMESTAMP_WITH_TIME_ZONE: if (columnStatistics instanceof TimestampColumnStatistics) { builder.setMax(((TimestampColumnStatistics) columnStatistics).getMaximum()) .setMin(((TimestampColumnStatistics) columnStatistics).getMinimum()); break; } else { return null; } case DECIMAL: if (columnStatistics instanceof DecimalColumnStatistics) { builder.setMax( ((DecimalColumnStatistics) columnStatistics) .getMaximum() .bigDecimalValue()) .setMin( ((DecimalColumnStatistics) columnStatistics) .getMinimum() .bigDecimalValue()); break; } else { return null; } default: return null; } return builder.build(); } private static
OrcFormatStatisticsReportUtil
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesReplicationControllersEndpointBuilderFactory.java
{ "start": 53862, "end": 57648 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final KubernetesReplicationControllersHeaderNameBuilder INSTANCE = new KubernetesReplicationControllersHeaderNameBuilder(); /** * The Producer operation. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code KubernetesOperation}. */ public String kubernetesOperation() { return "CamelKubernetesOperation"; } /** * The namespace name. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code KubernetesNamespaceName}. */ public String kubernetesNamespaceName() { return "CamelKubernetesNamespaceName"; } /** * The replication controller labels. * * The option is a: {@code Map<String, String>} type. * * Group: producer * * @return the name of the header {@code * KubernetesReplicationControllersLabels}. */ public String kubernetesReplicationControllersLabels() { return "CamelKubernetesReplicationControllersLabels"; } /** * The replication controller name. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code * KubernetesReplicationControllerName}. */ public String kubernetesReplicationControllerName() { return "CamelKubernetesReplicationControllerName"; } /** * The spec for a replication controller. * * The option is a: {@code * io.fabric8.kubernetes.api.model.ReplicationControllerSpec} type. * * Group: producer * * @return the name of the header {@code * KubernetesReplicationControllerSpec}. */ public String kubernetesReplicationControllerSpec() { return "CamelKubernetesReplicationControllerSpec"; } /** * The number of replicas for a replication controller during the Scale * operation. * * The option is a: {@code Integer} type. * * Group: producer * * @return the name of the header {@code * KubernetesReplicationControllerReplicas}. */ public String kubernetesReplicationControllerReplicas() { return "CamelKubernetesReplicationControllerReplicas"; } /** * Action watched by the consumer. * * The option is a: {@code io.fabric8.kubernetes.client.Watcher.Action} * type. * * Group: consumer * * @return the name of the header {@code KubernetesEventAction}. */ public String kubernetesEventAction() { return "CamelKubernetesEventAction"; } /** * Timestamp of the action watched by the consumer. * * The option is a: {@code long} type. * * Group: consumer * * @return the name of the header {@code KubernetesEventTimestamp}. */ public String kubernetesEventTimestamp() { return "CamelKubernetesEventTimestamp"; } } static KubernetesReplicationControllersEndpointBuilder endpointBuilder(String componentName, String path) {
KubernetesReplicationControllersHeaderNameBuilder
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/concurrent/BasicThreadFactory.java
{ "start": 11990, "end": 14576 }
class ____ an internal counter that is incremented each time the * {@link #newThread(Runnable)} method is invoked. * * @return the number of threads created by this factory */ public long getThreadCount() { return threadCounter.get(); } /** * Gets the {@link UncaughtExceptionHandler} for the threads created by * this factory. Result can be <strong>null</strong> if no handler was provided. * * @return the {@link UncaughtExceptionHandler} */ public final Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() { return uncaughtExceptionHandler; } /** * Gets the wrapped {@link ThreadFactory}. This factory is used for * actually creating threads. This method never returns <strong>null</strong>. If no * {@link ThreadFactory} was passed when this object was created, a default * thread factory is returned. * * @return the wrapped {@link ThreadFactory} */ public final ThreadFactory getWrappedFactory() { return wrappedFactory; } /** * Initializes the specified thread. This method is called by * {@link #newThread(Runnable)} after a new thread has been obtained from * the wrapped thread factory. It initializes the thread according to the * options set for this factory. * * @param thread the thread to be initialized */ private void initializeThread(final Thread thread) { if (getNamingPattern() != null) { final Long count = Long.valueOf(threadCounter.incrementAndGet()); thread.setName(String.format(getNamingPattern(), count)); } if (getUncaughtExceptionHandler() != null) { thread.setUncaughtExceptionHandler(getUncaughtExceptionHandler()); } if (getPriority() != null) { thread.setPriority(getPriority().intValue()); } if (getDaemonFlag() != null) { thread.setDaemon(getDaemonFlag().booleanValue()); } } /** * Creates a new thread. This implementation delegates to the wrapped * factory for creating the thread. Then, on the newly created thread the * corresponding configuration options are set. * * @param runnable the {@link Runnable} to be executed by the new thread * @return the newly created thread */ @Override public Thread newThread(final Runnable runnable) { final Thread thread = getWrappedFactory().newThread(runnable); initializeThread(thread); return thread; } }
maintains
java
quarkusio__quarkus
extensions/hibernate-orm/deployment-spi/src/main/java/io/quarkus/hibernate/orm/deployment/spi/AdditionalJpaModelBuildItem.java
{ "start": 252, "end": 964 }
class ____ extends MultiBuildItem { private final String className; private final Set<String> persistenceUnits; /** * @deprecated Use {@link AdditionalJpaModelBuildItem#AdditionalJpaModelBuildItem(String, Set)} instead, * which should fit the use case of JBeret better. */ @Deprecated(since = "3.28", forRemoval = true) public AdditionalJpaModelBuildItem(String className) { Objects.requireNonNull(className); this.className = className; this.persistenceUnits = null; } /** * @param className The name of the additional class. * @param persistenceUnits The name of persistence units to which this
AdditionalJpaModelBuildItem
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/support/descriptor/ClassSource.java
{ "start": 1837, "end": 2037 }
class ____: {@value} * * @since 1.8 */ @API(status = STABLE, since = "1.8") public static final String CLASS_SCHEME = "class"; /** * Create a new {@code ClassSource} using the supplied
sources
java
apache__camel
components/camel-google/camel-google-functions/src/test/java/org/apache/camel/component/google/functions/mock/MockCloudFunctionsService.java
{ "start": 2299, "end": 12395 }
class ____ extends CloudFunctionsServiceImplBase implements MockGrpcService { private List<AbstractMessage> requests; private Queue<Object> responses; public MockCloudFunctionsService() { requests = new ArrayList<>(); responses = new LinkedList<>(); } public List<AbstractMessage> getRequests() { return requests; } public void addResponse(AbstractMessage response) { responses.add(response); } public void setResponses(List<AbstractMessage> responses) { this.responses = new LinkedList<Object>(responses); } public void addException(Exception exception) { responses.add(exception); } public void reset() { requests = new ArrayList<>(); responses = new LinkedList<>(); } @Override public void listFunctions(ListFunctionsRequest request, StreamObserver<ListFunctionsResponse> responseObserver) { Object response = responses.remove(); if (response instanceof ListFunctionsResponse) { requests.add(request); responseObserver.onNext((ListFunctionsResponse) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException( String.format("Unrecognized response type %s for method ListFunctions, expected %s or %s", response.getClass().getName(), ListFunctionsResponse.class.getName(), Exception.class.getName()))); } } @Override public void getFunction(GetFunctionRequest request, StreamObserver<CloudFunction> responseObserver) { Object response = responses.remove(); if (response instanceof CloudFunction) { requests.add(request); responseObserver.onNext((CloudFunction) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException( String.format("Unrecognized response type %s for method GetFunction, expected %s or %s", response.getClass().getName(), CloudFunction.class.getName(), Exception.class.getName()))); } } @Override public void createFunction(CreateFunctionRequest request, StreamObserver<Operation> responseObserver) { Object response = responses.remove(); if (response instanceof Operation) { requests.add(request); responseObserver.onNext((Operation) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException( String.format("Unrecognized response type %s for method CreateFunction, expected %s or %s", response.getClass().getName(), Operation.class.getName(), Exception.class.getName()))); } } @Override public void updateFunction(UpdateFunctionRequest request, StreamObserver<Operation> responseObserver) { Object response = responses.remove(); if (response instanceof Operation) { requests.add(request); responseObserver.onNext((Operation) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException( String.format("Unrecognized response type %s for method UpdateFunction, expected %s or %s", response.getClass().getName(), Operation.class.getName(), Exception.class.getName()))); } } @Override public void deleteFunction(DeleteFunctionRequest request, StreamObserver<Operation> responseObserver) { Object response = responses.remove(); if (response instanceof Operation) { requests.add(request); responseObserver.onNext((Operation) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException( String.format("Unrecognized response type %s for method DeleteFunction, expected %s or %s", response.getClass().getName(), Operation.class.getName(), Exception.class.getName()))); } } @Override public void callFunction(CallFunctionRequest request, StreamObserver<CallFunctionResponse> responseObserver) { Object response = responses.remove(); if (response instanceof CallFunctionResponse) { requests.add(request); responseObserver.onNext((CallFunctionResponse) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException( String.format("Unrecognized response type %s for method CallFunction, expected %s or %s", response.getClass().getName(), CallFunctionResponse.class.getName(), Exception.class.getName()))); } } @Override public void generateUploadUrl( GenerateUploadUrlRequest request, StreamObserver<GenerateUploadUrlResponse> responseObserver) { Object response = responses.remove(); if (response instanceof GenerateUploadUrlResponse) { requests.add(request); responseObserver.onNext((GenerateUploadUrlResponse) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException( String.format("Unrecognized response type %s for method GenerateUploadUrl, expected %s or %s", response.getClass().getName(), GenerateUploadUrlResponse.class.getName(), Exception.class.getName()))); } } @Override public void generateDownloadUrl( GenerateDownloadUrlRequest request, StreamObserver<GenerateDownloadUrlResponse> responseObserver) { Object response = responses.remove(); if (response instanceof GenerateDownloadUrlResponse) { requests.add(request); responseObserver.onNext((GenerateDownloadUrlResponse) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException( String.format("Unrecognized response type %s for method GenerateDownloadUrl, expected %s or %s", response.getClass().getName(), GenerateDownloadUrlResponse.class.getName(), Exception.class.getName()))); } } @Override public void setIamPolicy(SetIamPolicyRequest request, StreamObserver<Policy> responseObserver) { Object response = responses.remove(); if (response instanceof Policy) { requests.add(request); responseObserver.onNext((Policy) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException( String.format("Unrecognized response type %s for method SetIamPolicy, expected %s or %s", response.getClass().getName(), Policy.class.getName(), Exception.class.getName()))); } } @Override public void getIamPolicy(GetIamPolicyRequest request, StreamObserver<Policy> responseObserver) { Object response = responses.remove(); if (response instanceof Policy) { requests.add(request); responseObserver.onNext((Policy) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException( String.format("Unrecognized response type %s for method GetIamPolicy, expected %s or %s", response.getClass().getName(), Policy.class.getName(), Exception.class.getName()))); } } @Override public void testIamPermissions( TestIamPermissionsRequest request, StreamObserver<TestIamPermissionsResponse> responseObserver) { Object response = responses.remove(); if (response instanceof TestIamPermissionsResponse) { requests.add(request); responseObserver.onNext((TestIamPermissionsResponse) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException( String.format("Unrecognized response type %s for method TestIamPermissions, expected %s or %s", response.getClass().getName(), TestIamPermissionsResponse.class.getName(), Exception.class.getName()))); } } @Override public ServerServiceDefinition getServiceDefinition() { return bindService(); } }
MockCloudFunctionsService
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/logical/SmallIntType.java
{ "start": 1165, "end": 2799 }
class ____ extends LogicalType { private static final long serialVersionUID = 1L; public static final int PRECISION = 5; private static final String FORMAT = "SMALLINT"; private static final Set<String> NULL_OUTPUT_CONVERSION = conversionSet(Short.class.getName()); private static final Set<String> NOT_NULL_INPUT_OUTPUT_CONVERSION = conversionSet(Short.class.getName(), short.class.getName()); private static final Class<?> DEFAULT_CONVERSION = Short.class; public SmallIntType(boolean isNullable) { super(isNullable, LogicalTypeRoot.SMALLINT); } public SmallIntType() { this(true); } @Override public LogicalType copy(boolean isNullable) { return new SmallIntType(isNullable); } @Override public String asSerializableString() { return withNullability(FORMAT); } @Override public boolean supportsInputConversion(Class<?> clazz) { return NOT_NULL_INPUT_OUTPUT_CONVERSION.contains(clazz.getName()); } @Override public boolean supportsOutputConversion(Class<?> clazz) { if (isNullable()) { return NULL_OUTPUT_CONVERSION.contains(clazz.getName()); } return NOT_NULL_INPUT_OUTPUT_CONVERSION.contains(clazz.getName()); } @Override public Class<?> getDefaultConversion() { return DEFAULT_CONVERSION; } @Override public List<LogicalType> getChildren() { return Collections.emptyList(); } @Override public <R> R accept(LogicalTypeVisitor<R> visitor) { return visitor.visit(this); } }
SmallIntType
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/lineage/TableLineageDatasetImpl.java
{ "start": 1433, "end": 3522 }
class ____ implements TableLineageDataset { @JsonProperty private String name; @JsonProperty private String namespace; private CatalogContext catalogContext; private CatalogBaseTable catalogBaseTable; @JsonProperty private ObjectPath objectPath; @JsonProperty private Map<String, LineageDatasetFacet> facets; public TableLineageDatasetImpl( ContextResolvedTable contextResolvedTable, Optional<LineageDataset> lineageDatasetOpt) { this.name = contextResolvedTable.getIdentifier().asSummaryString(); this.namespace = lineageDatasetOpt.map(lineageDataset -> lineageDataset.namespace()).orElse(""); this.catalogContext = CatalogContext.createContext( contextResolvedTable.getCatalog().isPresent() ? contextResolvedTable.getIdentifier().getCatalogName() : "", contextResolvedTable.getCatalog().orElse(null)); this.catalogBaseTable = contextResolvedTable.getTable(); this.objectPath = contextResolvedTable.isAnonymous() ? null : contextResolvedTable.getIdentifier().toObjectPath(); this.facets = new HashMap<>(); if (lineageDatasetOpt.isPresent()) { this.facets.putAll(lineageDatasetOpt.get().facets()); } } public void addLineageDatasetFacet(LineageDatasetFacet facet) { facets.put(facet.name(), facet); } @Override public String name() { return name; } @Override public String namespace() { return namespace; } @Override public Map<String, LineageDatasetFacet> facets() { return facets; } @Override public CatalogContext catalogContext() { return catalogContext; } @Override public CatalogBaseTable table() { return catalogBaseTable; } @Override public ObjectPath objectPath() { return objectPath; } }
TableLineageDatasetImpl
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/InstanceOfAssertFactoriesTest.java
{ "start": 31638, "end": 32433 }
class ____ { private final Object actual = 0.0; @Test void createAssert() { // WHEN AbstractDoubleAssert<?> result = DOUBLE.createAssert(actual); // THEN result.isZero(); } @ParameterizedTest @MethodSource("valueProviders") void createAssert_with_ValueProvider(ValueProvider<?> delegate) { // GIVEN ValueProvider<?> valueProvider = mockThatDelegatesTo(delegate); // WHEN AbstractDoubleAssert<?> result = DOUBLE.createAssert(valueProvider); // THEN result.isZero(); verify(valueProvider).apply(Double.class); } private Stream<ValueProvider<?>> valueProviders() { return Stream.of(type -> actual, type -> convert("0.0", type)); } } @Nested
Double_Factory
java
apache__flink
flink-connectors/flink-hadoop-compatibility/src/test/java/org/apache/flink/api/java/hadoop/mapred/HadoopInputFormatTest.java
{ "start": 11455, "end": 11636 }
class ____ extends DummyInputFormat implements JobConfigurable { @Override public void configure(JobConf jobConf) {} } }
JobConfigurableDummyInputFormat
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/streamrecord/StreamElementSerializerUpgradeTest.java
{ "start": 2477, "end": 2922 }
class ____ implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<StreamElement> { @Override public TypeSerializer<StreamElement> createPriorSerializer() { return new StreamElementSerializer<>(StringSerializer.INSTANCE); } @Override public StreamElement createTestData() { return new StreamRecord<>("key", 123456); } } /** * This
StreamElementSetup
java
quarkusio__quarkus
integration-tests/resteasy-jackson/src/test/java/io/quarkus/it/resteasy/jackson/BigKeysResourceTest.java
{ "start": 260, "end": 769 }
class ____ { @Test public void test() throws IOException { given() .contentType("application/json") .accept("application/json") .body("{\"bdMap\":{\"1\":\"One\", \"2\":\"Two\"}, \"biMap\":{\"1\":\"One\", \"2\":\"Two\"}}") .when().post("/bigkeys") .then() .statusCode(200) .body("bdMap.1", equalTo("One")) .body("biMap.2", equalTo("Two")); } }
BigKeysResourceTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/longs/Longs_assertIsNotNegative_Test.java
{ "start": 911, "end": 1908 }
class ____ extends LongsBaseTest { @Test void should_succeed_since_actual_is_not_negative() { longs.assertIsNotNegative(someInfo(), 6L); } @Test void should_succeed_since_actual_is_zero() { longs.assertIsNotNegative(someInfo(), 0L); } @Test void should_fail_since_actual_is_negative() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> longs.assertIsNotNegative(someInfo(), -6L)) .withMessage("%nExpecting actual:%n -6L%nto be greater than or equal to:%n 0L%n".formatted()); } @Test void should_succeed_since_actual_negative_is_not_negative_according_to_custom_comparison_strategy() { longsWithAbsValueComparisonStrategy.assertIsNotNegative(someInfo(), -1L); } @Test void should_succeed_since_actual_positive_is_not_negative_according_to_custom_comparison_strategy() { longsWithAbsValueComparisonStrategy.assertIsNotNegative(someInfo(), 1L); } }
Longs_assertIsNotNegative_Test
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/NodesToAttributesMappingRequest.java
{ "start": 1222, "end": 3209 }
class ____ { public static NodesToAttributesMappingRequest newInstance( AttributeMappingOperationType operation, List<NodeToAttributes> nodesToAttributes, boolean failOnUnknownNodes) { NodesToAttributesMappingRequest request = Records.newRecord(NodesToAttributesMappingRequest.class); request.setNodesToAttributes(nodesToAttributes); request.setFailOnUnknownNodes(failOnUnknownNodes); request.setOperation(operation); return request; } public static NodesToAttributesMappingRequest newInstance( AttributeMappingOperationType operation, List<NodeToAttributes> nodesToAttributes, boolean failOnUnknownNodes, String subClusterId) { NodesToAttributesMappingRequest request = Records.newRecord(NodesToAttributesMappingRequest.class); request.setNodesToAttributes(nodesToAttributes); request.setFailOnUnknownNodes(failOnUnknownNodes); request.setOperation(operation); request.setOperation(operation); request.setSubClusterId(subClusterId); return request; } @Public @Unstable public abstract void setNodesToAttributes( List<NodeToAttributes> nodesToAttributes); @Public @Unstable public abstract List<NodeToAttributes> getNodesToAttributes(); @Public @Unstable public abstract void setFailOnUnknownNodes(boolean failOnUnknownNodes); @Public @Unstable public abstract boolean getFailOnUnknownNodes(); @Public @Unstable public abstract void setOperation(AttributeMappingOperationType operation); @Public @Unstable public abstract AttributeMappingOperationType getOperation(); /** * Get the subClusterId. * * @return subClusterId. */ @Public @InterfaceStability.Evolving public abstract String getSubClusterId(); /** * Set the subClusterId. * * @param subClusterId subCluster Id. */ @Public @InterfaceStability.Evolving public abstract void setSubClusterId(String subClusterId); }
NodesToAttributesMappingRequest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/LocalTimeOffset.java
{ "start": 11829, "end": 13817 }
class ____ extends Transition { private final long firstOverlappingLocalTime; private final long firstNonOverlappingLocalTime; private final boolean movesBackToPreviousDay; private Overlap( long millis, LocalTimeOffset previous, long startUtcMillis, long firstOverlappingLocalTime, long firstNonOverlappingLocalTime, boolean movesBackToPreviousDay ) { super(millis, previous, startUtcMillis); this.firstOverlappingLocalTime = firstOverlappingLocalTime; this.firstNonOverlappingLocalTime = firstNonOverlappingLocalTime; assert firstOverlappingLocalTime < firstNonOverlappingLocalTime; this.movesBackToPreviousDay = movesBackToPreviousDay; } @Override public long localToUtc(long localMillis, Strategy strat) { if (localMillis >= firstNonOverlappingLocalTime) { return localToUtcInThisOffset(localMillis); } if (localMillis >= firstOverlappingLocalTime) { return strat.inOverlap(localMillis, this); } return strat.beforeOverlap(localMillis, this); } /** * The first local time after the overlap stops. */ public long firstNonOverlappingLocalTime() { return firstNonOverlappingLocalTime; } /** * The first local time to be appear twice. */ public long firstOverlappingLocalTime() { return firstOverlappingLocalTime; } @Override protected boolean anyMoveBackToPreviousDay() { return movesBackToPreviousDay || previous().anyMoveBackToPreviousDay(); } @Override protected String toString(long millis) { return "Overlap of " + millis + "@" + Instant.ofEpochMilli(startUtcMillis()); } } private static
Overlap
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/checkpoint/EnumCounter.java
{ "start": 863, "end": 963 }
enum ____ { INPUTKEY, INPUTVALUE, OUTPUTRECORDS, CHECKPOINT_BYTES, CHECKPOINT_MS }
EnumCounter
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/InvalidConfigurationClassDefinitionTests.java
{ "start": 1458, "end": 2019 }
class ____ { @Bean String dummy() { return "dummy"; } } BeanDefinition configBeanDef = rootBeanDefinition(Config.class).getBeanDefinition(); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.registerBeanDefinition("config", configBeanDef); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); assertThatExceptionOfType(BeanDefinitionParsingException.class) .isThrownBy(() -> pp.postProcessBeanFactory(beanFactory)) .withMessageContaining("Remove the final modifier"); } }
Config
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/Conditional.java
{ "start": 1315, "end": 1658 }
class ____ or indirectly annotated with * {@code @Component}, including {@link Configuration @Configuration} classes</li> * <li>as a meta-annotation, for the purpose of composing custom stereotype * annotations</li> * <li>as a method-level annotation on any {@link Bean @Bean} method</li> * </ul> * * <p>If a {@code @Configuration}
directly
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FileIoProvider.java
{ "start": 29921, "end": 31993 }
class ____ extends FileOutputStream { private @Nullable final FsVolumeSpi volume; /** * {@inheritDoc}. */ private WrappedFileOutputStream( @Nullable FsVolumeSpi volume, File f, boolean append) throws FileNotFoundException { super(f, append); this.volume = volume; } /** * {@inheritDoc}. */ private WrappedFileOutputStream( @Nullable FsVolumeSpi volume, FileDescriptor fd) { super(fd); this.volume = volume; } /** * {@inheritDoc}. */ @Override public void write(int b) throws IOException { final long begin = profilingEventHook.beforeFileIo(volume, WRITE, LEN_INT); try { faultInjectorEventHook.beforeFileIo(volume, WRITE, LEN_INT); super.write(b); profilingEventHook.afterFileIo(volume, WRITE, begin, LEN_INT); } catch(Exception e) { onFailure(volume, begin); throw e; } } /** * {@inheritDoc}. */ @Override public void write(@Nonnull byte[] b) throws IOException { final long begin = profilingEventHook.beforeFileIo(volume, WRITE, b .length); try { faultInjectorEventHook.beforeFileIo(volume, WRITE, b.length); super.write(b); profilingEventHook.afterFileIo(volume, WRITE, begin, b.length); } catch(Exception e) { onFailure(volume, begin); throw e; } } /** * {@inheritDoc}. */ @Override public void write(@Nonnull byte[] b, int off, int len) throws IOException { final long begin = profilingEventHook.beforeFileIo(volume, WRITE, len); try { faultInjectorEventHook.beforeFileIo(volume, WRITE, len); super.write(b, off, len); profilingEventHook.afterFileIo(volume, WRITE, begin, len); } catch(Exception e) { onFailure(volume, begin); throw e; } } } /** * A thin wrapper over {@link FileInputStream} that allows * instrumenting IO. */ private final
WrappedFileOutputStream
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/api/parallel/ResourceLockAnnotationTests.java
{ "start": 20654, "end": 20830 }
class ____ { @Test @ResourceLock("c1") void test() { } } @Nested @ClassTemplate @ResourceLock(value = "d1", target = ResourceLockTarget.CHILDREN)
NestedClass
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/security/inheritance/AbstractImplMethodSecuredTest.java
{ "start": 3677, "end": 9984 }
class ____ { protected static QuarkusUnitTest getRunner() { return getRunner(""); } protected static QuarkusUnitTest getRunner(String applicationProperties) { return new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addPackage("io.quarkus.resteasy.reactive.server.test.security.inheritance.noclassannotation") .addPackage("io.quarkus.resteasy.reactive.server.test.security.inheritance.classrolesallowed") .addPackage("io.quarkus.resteasy.reactive.server.test.security.inheritance.classdenyall") .addPackage("io.quarkus.resteasy.reactive.server.test.security.inheritance.classpermitall") .addPackage("io.quarkus.resteasy.reactive.server.test.security.inheritance.multiple.pathonbase") .addClasses(TestIdentityProvider.class, TestIdentityController.class, SecurityAnnotation.class, SubPaths.class, JsonObjectReader.class) .addAsResource( new StringAsset(applicationProperties + System.lineSeparator() + "quarkus.log.category.\"io.quarkus.vertx.http.runtime.QuarkusErrorHandler\".level=OFF" + System.lineSeparator()), "application.properties")); } @BeforeAll public static void setupUsers() { TestIdentityController.resetRoles() .add("admin", "admin", "admin") .add("user", "user", "user"); } protected boolean denyAllUnannotated() { return false; } protected String roleRequiredForUnannotatedEndpoint() { return null; } private void assertPath(String basePath, Object securityAnnotationObj, String classSecurityOn) { assertPath(basePath, toSecurityAnnotation(securityAnnotationObj), classSecurityOn); } private void assertSecuredSubResourcePath(String basePath) { // sub resource locator is not secured, e.g. @Path("sub") public SubResource subResource() { ... } var path = NONE.assemblePath(basePath) + SECURED_SUB_RESOURCE_ENDPOINT_PATH; var methodSubPath = NONE.methodSubPath(basePath) + SECURED_SUB_RESOURCE_ENDPOINT_PATH; boolean defJaxRsSecurity = denyAllUnannotated() || roleRequiredForUnannotatedEndpoint() != null; final SecurityAnnotation securityAnnotation; if (defJaxRsSecurity) { // subresource locator is not secured, therefore default JAX-RS security wins securityAnnotation = NONE; } else { // sub resource endpoint itself has RolesAllowed, e.g. @RolesAllowed @Path("endpoint") String endpoint() { ... } securityAnnotation = METHOD_ROLES_ALLOWED; } assertPath(path, methodSubPath, securityAnnotation); } private void assertPath(String basePath, SecurityAnnotation securityAnnotation, String classSecurityOn) { var path = securityAnnotation.assemblePath(basePath, classSecurityOn); var methodSubPath = securityAnnotation.methodSubPath(basePath, classSecurityOn); assertPath(path, methodSubPath, securityAnnotation); } private void assertPath(String basePath, SecurityAnnotation securityAnnotation) { var path = securityAnnotation.assemblePath(basePath); var methodSubPath = securityAnnotation.methodSubPath(basePath); assertPath(path, methodSubPath, securityAnnotation); } private void assertPath(String path, String methodSubPath, SecurityAnnotation securityAnnotation) { var invalidPayload = "}{\"simple\": \"obj\"}"; var validPayload = "{\"simple\": \"obj\"}"; boolean defJaxRsSecurity = denyAllUnannotated() || roleRequiredForUnannotatedEndpoint() != null; boolean endpointSecuredWithDefJaxRsSec = defJaxRsSecurity && !securityAnnotation.hasSecurityAnnotation(); boolean endpointSecured = endpointSecuredWithDefJaxRsSec || securityAnnotation.endpointSecured(); // test anonymous - for secured endpoints: unauthenticated if (endpointSecured) { given().contentType(ContentType.JSON).body(invalidPayload).post(path).then().statusCode(401); } else { given().contentType(ContentType.JSON).body(validPayload).post(path).then().statusCode(200).body(is(methodSubPath)); } // test user - for secured endpoints: unauthorized if (endpointSecured) { given().contentType(ContentType.JSON).body(invalidPayload).auth().preemptive().basic("user", "user").post(path) .then().statusCode(403); } else { given().contentType(ContentType.JSON).body(validPayload).auth().preemptive().basic("user", "user").post(path).then() .statusCode(200).body(is(methodSubPath)); } // test admin - for secured endpoints: authorized boolean denyAccess = securityAnnotation.denyAll() || (endpointSecuredWithDefJaxRsSec && denyAllUnannotated()); if (denyAccess) { given().contentType(ContentType.JSON).body(invalidPayload).auth().preemptive().basic("admin", "admin").post(path) .then().statusCode(403); } else { given().contentType(ContentType.JSON).body(invalidPayload).auth().preemptive().basic("admin", "admin").post(path) .then().statusCode(500); given().contentType(ContentType.JSON).body(validPayload).auth().preemptive().basic("admin", "admin").post(path) .then().statusCode(200).body(is(methodSubPath)); } } private static void assertNotFound(String basePath) { var path = NONE.assembleNotFoundPath(basePath); // this assures that not-tested scenarios are simply not supported by RESTEasy // should this assertion fail, we need to assure implementation method is secured given().contentType(ContentType.JSON).body("{\"simple\": \"obj\"}").post(path).then().statusCode(404); } private static SecurityAnnotation toSecurityAnnotation(Object securityAnnotationObj) { // we use Object due to @EnumSource
AbstractImplMethodSecuredTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/metrics/DataNodePeerMetrics.java
{ "start": 2073, "end": 2239 }
class ____ DataNode peer metrics (e.g. numOps, AvgTime, etc.) for * various peer operations. */ @InterfaceAudience.Private @InterfaceStability.Unstable public
maintains
java
quarkusio__quarkus
integration-tests/hibernate-search-orm-elasticsearch-outbox-polling/src/main/java/io/quarkus/it/hibernate/search/orm/elasticsearch/coordination/outboxpolling/HibernateSearchOutboxPollingTestResource.java
{ "start": 642, "end": 3776 }
class ____ { @Inject EntityManager entityManager; @Inject UserTransaction userTransaction; @PUT @Path("/check-agents-running") @Produces(MediaType.TEXT_PLAIN) public String checkAgentsRunning() { OutboxPollingTestUtils.awaitAgentsRunning(entityManager, userTransaction, 1); return "OK"; } @PUT @Path("/init-data") @Transactional public void initData() { createPerson("John Irving"); createPerson("David Lodge"); createPerson("Paul Auster"); createPerson("John Grisham"); // Add many other entities, so that mass indexing has something to do. // DO NOT REMOVE, it's important to have many entities to fully test mass indexing. for (int i = 0; i < 1000; i++) { createPerson("Other entity #" + i); } } @PUT @Path("/await-event-processing") public void awaitEventProcessing() { OutboxPollingTestUtils.awaitNoMoreOutboxEvents(entityManager, userTransaction); } @GET @Path("/search") @Produces(MediaType.TEXT_PLAIN) @Transactional public String testSearch() { SearchSession searchSession = Search.session(entityManager); List<Person> person = searchSession.search(Person.class) .where(f -> f.match().field("name").matching("john")) .sort(f -> f.field("name_sort")) .fetchHits(20); assertEquals(2, person.size()); assertEquals("John Grisham", person.get(0).getName()); assertEquals("John Irving", person.get(1).getName()); assertEquals(4 + 1000, searchSession.search(Person.class) .where(f -> f.matchAll()) .fetchTotalHitCount()); return "OK"; } @PUT @Path("/purge") @Produces(MediaType.TEXT_PLAIN) public String testPurge() { SearchSession searchSession = Search.session(entityManager); searchSession.workspace().purge(); return "OK"; } @PUT @Path("/refresh") @Produces(MediaType.TEXT_PLAIN) public String testRefresh() { SearchSession searchSession = Search.session(entityManager); searchSession.workspace().refresh(); return "OK"; } @GET @Path("/search-empty") @Produces(MediaType.TEXT_PLAIN) @Transactional public String testSearchEmpty() { SearchSession searchSession = Search.session(entityManager); List<Person> person = searchSession.search(Person.class) .where(f -> f.matchAll()) .fetchHits(20); assertEquals(0, person.size()); return "OK"; } @PUT @Path("/mass-indexer") @Produces(MediaType.TEXT_PLAIN) public String testMassIndexer() throws InterruptedException { SearchSession searchSession = Search.session(entityManager); searchSession.massIndexer().startAndWait(); return "OK"; } private void createPerson(String name) { Person entity = new Person(name); entityManager.persist(entity); } }
HibernateSearchOutboxPollingTestResource
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/WrrLocalityLoadBalancerTest.java
{ "start": 8826, "end": 9926 }
class ____ extends SocketAddress { private final String name; private FakeSocketAddress(String name) { this.name = name; } @Override public int hashCode() { return Objects.hash(name); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FakeSocketAddress)) { return false; } FakeSocketAddress that = (FakeSocketAddress) o; return Objects.equals(name, that.name); } @Override public String toString() { return name; } } Attributes.Builder attrBuilder = Attributes.newBuilder() .set(EquivalentAddressGroup.ATTR_LOCALITY_NAME, locality); if (localityWeight != null) { attrBuilder.set(XdsAttributes.ATTR_LOCALITY_WEIGHT, localityWeight); } EquivalentAddressGroup eag = new EquivalentAddressGroup(new FakeSocketAddress(name), attrBuilder.build()); return AddressFilter.setPathFilter(eag, Collections.singletonList(locality)); } }
FakeSocketAddress
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1435/Issue1435Test.java
{ "start": 517, "end": 789 }
class ____ { @ProcessorTest public void mustNotSetListToNull() { InObject source = new InObject( "Rainbow Dash" ); OutObject result = Issue1435Mapper.INSTANCE.map( source ); assertThat( result.isRainbowDash() ).isTrue(); } }
Issue1435Test
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RScript.java
{ "start": 963, "end": 1162 }
enum ____ { /** * Execute script as read operation */ READ_ONLY, /** * Execute script as write operation */ READ_WRITE }
Mode
java
google__auto
value/src/test/java/com/google/auto/value/processor/TypeEncoderTest.java
{ "start": 12943, "end": 15789 }
class ____<V> {} } } @Test public void testOuterParameterizedInnerNot() { TypeElement outerElement = typeElementOf(Outer.class); DeclaredType doubleMirror = typeMirrorOf(Double.class); DeclaredType outerOfDoubleMirror = typeUtils.getDeclaredType(outerElement, doubleMirror); TypeElement innerWithoutTypeParamElement = typeElementOf(Outer.InnerWithoutTypeParam.class); DeclaredType parameterizedInnerWithoutTypeParam = typeUtils.getDeclaredType(outerOfDoubleMirror, innerWithoutTypeParamElement); String encoded = TypeEncoder.encode(parameterizedInnerWithoutTypeParam); String myPackage = getClass().getPackage().getName(); String decoded = TypeEncoder.decode( encoded, elementUtils, typeUtils, myPackage, baseWithoutContainedTypes()); String expected = "TypeEncoderTest.Outer<Double>.InnerWithoutTypeParam"; assertThat(decoded).isEqualTo(expected); } @Test public void testOuterParameterizedInnerAlso() { TypeElement outerElement = typeElementOf(Outer.class); DeclaredType doubleMirror = typeMirrorOf(Double.class); DeclaredType outerOfDoubleMirror = typeUtils.getDeclaredType(outerElement, doubleMirror); TypeElement middleElement = typeElementOf(Outer.Middle.class); DeclaredType stringMirror = typeMirrorOf(String.class); DeclaredType middleOfStringMirror = typeUtils.getDeclaredType(outerOfDoubleMirror, middleElement, stringMirror); TypeElement innerWithTypeParamElement = typeElementOf(Outer.Middle.InnerWithTypeParam.class); DeclaredType integerMirror = typeMirrorOf(Integer.class); DeclaredType parameterizedInnerWithTypeParam = typeUtils.getDeclaredType(middleOfStringMirror, innerWithTypeParamElement, integerMirror); String encoded = TypeEncoder.encode(parameterizedInnerWithTypeParam); String myPackage = getClass().getPackage().getName(); String decoded = TypeEncoder.decode( encoded, elementUtils, typeUtils, myPackage, baseWithoutContainedTypes()); String expected = "TypeEncoderTest.Outer<Double>.Middle<String>.InnerWithTypeParam<Integer>"; assertThat(decoded).isEqualTo(expected); } private static Set<TypeMirror> typeMirrorSet(TypeMirror... typeMirrors) { Set<TypeMirror> set = new TypeMirrorSet(); for (TypeMirror typeMirror : typeMirrors) { assertThat(set.add(typeMirror)).isTrue(); } return set; } private TypeElement typeElementOf(Class<?> c) { return elementUtils.getTypeElement(c.getCanonicalName()); } private DeclaredType typeMirrorOf(Class<?> c) { return MoreTypes.asDeclared(typeElementOf(c).asType()); } /** * Returns a "base type" for TypeSimplifier that does not contain any nested types. The point * being that every {@code TypeSimplifier} has a base type that the
InnerWithTypeParam
java
quarkusio__quarkus
extensions/grpc/deployment/src/test/java/io/quarkus/grpc/auth/SecurityEventObserver.java
{ "start": 282, "end": 548 }
class ____ { private final List<SecurityEvent> storage = new CopyOnWriteArrayList<>(); void observe(@Observes SecurityEvent event) { storage.add(event); } List<SecurityEvent> getStorage() { return storage; } }
SecurityEventObserver
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/matchers/CustomMatchersTest.java
{ "start": 850, "end": 1013 }
class ____ implements ArgumentMatcher<Boolean> { public boolean matches(Boolean arg) { return true; } } private final
IsAnyBoolean
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/script/ScriptStats.java
{ "start": 9028, "end": 9368 }
class ____ { static final String SCRIPT_STATS = "script"; static final String CONTEXTS = "contexts"; static final String COMPILATIONS = "compilations"; static final String CACHE_EVICTIONS = "cache_evictions"; static final String COMPILATION_LIMIT_TRIGGERED = "compilation_limit_triggered"; } }
Fields
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/BeanClassLoaderAware.java
{ "start": 1304, "end": 1412 }
interface ____ extends Aware { /** * Callback that supplies the bean {@link ClassLoader
BeanClassLoaderAware
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/scripting/config/LangNamespaceHandler.java
{ "start": 1443, "end": 2125 }
class ____ extends NamespaceHandlerSupport { @Override public void init() { registerScriptBeanDefinitionParser("groovy", "org.springframework.scripting.groovy.GroovyScriptFactory"); registerScriptBeanDefinitionParser("bsh", "org.springframework.scripting.bsh.BshScriptFactory"); registerScriptBeanDefinitionParser("std", "org.springframework.scripting.support.StandardScriptFactory"); registerBeanDefinitionParser("defaults", new ScriptingDefaultsParser()); } private void registerScriptBeanDefinitionParser(String key, String scriptFactoryClassName) { registerBeanDefinitionParser(key, new ScriptBeanDefinitionParser(scriptFactoryClassName)); } }
LangNamespaceHandler
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/commit/CommitterEventHandler.java
{ "start": 2771, "end": 5567 }
class ____ extends AbstractService implements EventHandler<CommitterEvent> { private static final Logger LOG = LoggerFactory.getLogger(CommitterEventHandler.class); private final AppContext context; private final OutputCommitter committer; private final RMHeartbeatHandler rmHeartbeatHandler; private ThreadPoolExecutor launcherPool; private Thread eventHandlingThread; private BlockingQueue<CommitterEvent> eventQueue = new LinkedBlockingQueue<CommitterEvent>(); private final AtomicBoolean stopped; private final ClassLoader jobClassLoader; private Thread jobCommitThread = null; private int commitThreadCancelTimeoutMs; private long commitWindowMs; private FileSystem fs; private Path startCommitFile; private Path endCommitSuccessFile; private Path endCommitFailureFile; public CommitterEventHandler(AppContext context, OutputCommitter committer, RMHeartbeatHandler rmHeartbeatHandler) { this(context, committer, rmHeartbeatHandler, null); } public CommitterEventHandler(AppContext context, OutputCommitter committer, RMHeartbeatHandler rmHeartbeatHandler, ClassLoader jobClassLoader) { super("CommitterEventHandler"); this.context = context; this.committer = committer; this.rmHeartbeatHandler = rmHeartbeatHandler; this.stopped = new AtomicBoolean(false); this.jobClassLoader = jobClassLoader; } @Override protected void serviceInit(Configuration conf) throws Exception { super.serviceInit(conf); commitThreadCancelTimeoutMs = conf.getInt( MRJobConfig.MR_AM_COMMITTER_CANCEL_TIMEOUT_MS, MRJobConfig.DEFAULT_MR_AM_COMMITTER_CANCEL_TIMEOUT_MS); commitWindowMs = conf.getLong(MRJobConfig.MR_AM_COMMIT_WINDOW_MS, MRJobConfig.DEFAULT_MR_AM_COMMIT_WINDOW_MS); try { fs = FileSystem.get(conf); JobID id = TypeConverter.fromYarn(context.getApplicationID()); JobId jobId = TypeConverter.toYarn(id); String user = UserGroupInformation.getCurrentUser().getShortUserName(); startCommitFile = MRApps.getStartJobCommitFile(conf, user, jobId); endCommitSuccessFile = MRApps.getEndJobCommitSuccessFile(conf, user, jobId); endCommitFailureFile = MRApps.getEndJobCommitFailureFile(conf, user, jobId); } catch (IOException e) { throw new YarnRuntimeException(e); } } @Override protected void serviceStart() throws Exception { ThreadFactoryBuilder tfBuilder = new ThreadFactoryBuilder() .setNameFormat("CommitterEvent Processor #%d"); if (jobClassLoader != null) { // if the job classloader is enabled, we need to use the job classloader // as the thread context classloader (TCCL) of these threads in case the // committer needs to load another
CommitterEventHandler
java
apache__dubbo
dubbo-metadata/dubbo-metadata-definition-protobuf/src/main/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilder.java
{ "start": 6916, "end": 11746 }
class ____ java<br/> * * @param fieldName * @param typeName * @return */ private void validateMapType(String fieldName, String typeName) { Matcher matcher = MAP_PATTERN.matcher(typeName); if (!matcher.matches()) { throw new IllegalArgumentException("Map protobuf property " + fieldName + "of Type " + typeName + " can't be parsed.The type name should match[" + MAP_PATTERN.toString() + "]."); } } /** * get unCollection unMap property name from setting method.<br/> * ex:setXXX();<br/> * * @param methodName * @return */ private String generateSimpleFiledName(String methodName) { return toCamelCase(methodName.substring(3)); } /** * get map property name from setting method.<br/> * ex: putAllXXX();<br/> * * @param methodName * @return */ private String generateMapFieldName(String methodName) { return toCamelCase(methodName.substring(6)); } /** * get list property name from setting method.<br/> * ex: getXXXList()<br/> * * @param methodName * @return */ private String generateListFieldName(String methodName) { return toCamelCase(methodName.substring(3, methodName.length() - 4)); } private String toCamelCase(String nameString) { char[] chars = nameString.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); } /** * judge custom type or primitive type property<br/> * 1. proto3 grammar ex: string name = 1 <br/> * 2. proto3 grammar ex: optional string name =1 <br/> * generated setting method ex: setNameValue(String name); * * @param method * @return */ private boolean isSimplePropertySettingMethod(Method method) { String methodName = method.getName(); Class<?>[] types = method.getParameterTypes(); if (!methodName.startsWith("set") || types.length != 1) { return false; } // filter general setting method // 1. - setUnknownFields( com.google.protobuf.UnknownFieldSet unknownFields) // 2. - setField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value) // 3. - setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index,java.lang.Object value) if ("setField".equals(methodName) && types[0].equals(Descriptors.FieldDescriptor.class) || "setUnknownFields".equals(methodName) && types[0].equals(UnknownFieldSet.class) || "setRepeatedField".equals(methodName) && types[0].equals(Descriptors.FieldDescriptor.class)) { return false; } // String property has two setting method. // skip setXXXBytes(com.google.protobuf.ByteString value) // parse setXXX(String string) if (methodName.endsWith("Bytes") && types[0].equals(ByteString.class)) { return false; } // Protobuf property has two setting method. // skip setXXX(com.google.protobuf.Builder value) // parse setXXX(com.google.protobuf.Message value) if (GeneratedMessageV3.Builder.class.isAssignableFrom(types[0])) { return false; } // Enum property has two setting method. // skip setXXXValue(int value) // parse setXXX(SomeEnum value) return !methodName.endsWith("Value") || types[0] != int.class; } /** * judge List property</br> * proto3 grammar ex: repeated string names; </br> * generated getting method:List<String> getNamesList() * * @param method * @return */ boolean isListPropertyGettingMethod(Method method) { String methodName = method.getName(); Class<?> type = method.getReturnType(); if (!methodName.startsWith("get") || !methodName.endsWith("List")) { return false; } // skip the setting method with Pb entity builder as parameter if (methodName.endsWith("BuilderList")) { return false; } // if field name end with List, should skip return List.class.isAssignableFrom(type); } /** * judge map property</br> * proto3 grammar : map<string,string> card = 1; </br> * generated setting method: putAllCards(java.util.Map<String, string> values) </br> * * @param methodTemp * @return */ private boolean isMapPropertySettingMethod(Method methodTemp) { String methodName = methodTemp.getName(); Class[] parameters = methodTemp.getParameterTypes(); return methodName.startsWith("putAll") && parameters.length == 1 && Map.class.isAssignableFrom(parameters[0]); } }
in
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/text/CompositeFormatTest.java
{ "start": 1231, "end": 3313 }
class ____ extends AbstractLangTest { /** * Ensures that the parse/format separation is correctly maintained. */ @Test void testCompositeFormat() { final Format parser = new Format() { private static final long serialVersionUID = 1L; @Override public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { throw new UnsupportedOperationException("Not implemented"); } @Override public Object parseObject(final String source, final ParsePosition pos) { return null; // do nothing } }; final Format formatter = new Format() { private static final long serialVersionUID = 1L; @Override public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { return null; // do nothing } @Override public Object parseObject(final String source, final ParsePosition pos) { throw new UnsupportedOperationException("Not implemented"); } }; final CompositeFormat composite = new CompositeFormat(parser, formatter); composite.parseObject("", null); composite.format(new Object(), new StringBuffer(), null); assertEquals(parser, composite.getParser(), "Parser get method incorrectly implemented"); assertEquals(formatter, composite.getFormatter(), "Formatter get method incorrectly implemented"); } @Test void testUsage() throws Exception { final Format f1 = new SimpleDateFormat("MMddyyyy", Locale.ENGLISH); final Format f2 = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH); final CompositeFormat c = new CompositeFormat(f1, f2); final String testString = "January 3, 2005"; assertEquals(testString, c.format(c.parseObject("01032005"))); assertEquals(testString, c.reformat("01032005")); } }
CompositeFormatTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregationStrategyAsPredicateTest.java
{ "start": 1151, "end": 2415 }
class ____ extends ContextTestSupport { @Test public void testAggregateCompletionAware() throws Exception { MockEndpoint result = getMockEndpoint("mock:aggregated"); result.expectedBodiesReceived("A+B+C", "X+Y+ZZZZ"); result.message(0).exchangeProperty(Exchange.AGGREGATED_COMPLETED_BY).isEqualTo("predicate"); result.message(1).exchangeProperty(Exchange.AGGREGATED_COMPLETED_BY).isEqualTo("predicate"); template.sendBodyAndHeader("direct:start", "A", "id", 123); template.sendBodyAndHeader("direct:start", "B", "id", 123); template.sendBodyAndHeader("direct:start", "C", "id", 123); template.sendBodyAndHeader("direct:start", "X", "id", 123); template.sendBodyAndHeader("direct:start", "Y", "id", 123); template.sendBodyAndHeader("direct:start", "ZZZZ", "id", 123); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").aggregate(header("id"), new MyCompletionStrategy()).to("mock:aggregated"); } }; } private static final
AggregationStrategyAsPredicateTest
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsComposedOnSingleAnnotatedElementTests.java
{ "start": 6762, "end": 7049 }
interface ____ { @AliasFor("cacheName") String value() default ""; @AliasFor("value") String cacheName() default ""; String key() default ""; } @Cacheable("fooCache") @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Inherited @
Cacheable
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Issue64.java
{ "start": 240, "end": 686 }
class ____ extends TestCase { public void test_for_issue() throws Exception { VO vo = new VO(); vo.foo = "xxxxxx"; String text = JSON.toJSONString(vo, SerializerFeature.BeanToArray); Assert.assertEquals("[\"xxxxxx\"]", text); VO vo2 = JSON.parseObject(text, VO.class, Feature.SupportArrayToBean); Assert.assertEquals(vo2.foo, vo.foo); } public static
Issue64
java
quarkusio__quarkus
core/deployment/src/test/java/io/quarkus/deployment/proxy/SimpleInvocationHandler.java
{ "start": 831, "end": 1089 }
class ____ implements InvocationHandler { public int invocationCount = 0; @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { invocationCount++; return args; } }
SimpleInvocationHandler
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/topn/TopNEncoder.java
{ "start": 850, "end": 2857 }
interface ____ { /** * An encoder that encodes values such that sorting the bytes sorts the values. */ DefaultSortableTopNEncoder DEFAULT_SORTABLE = new DefaultSortableTopNEncoder(); /** * An encoder that encodes values as compactly as possible without making the * encoded bytes sortable. */ DefaultUnsortableTopNEncoder DEFAULT_UNSORTABLE = new DefaultUnsortableTopNEncoder(); /** * An encoder for IP addresses. */ FixedLengthTopNEncoder IP = new FixedLengthTopNEncoder(InetAddressPoint.BYTES); /** * An encoder for UTF-8 text. */ UTF8TopNEncoder UTF8 = new UTF8TopNEncoder(); /** * An encoder for semver versions. */ VersionTopNEncoder VERSION = new VersionTopNEncoder(); /** * Placeholder encoder for unsupported data types. */ UnsupportedTypesTopNEncoder UNSUPPORTED = new UnsupportedTypesTopNEncoder(); void encodeLong(long value, BreakingBytesRefBuilder bytesRefBuilder); long decodeLong(BytesRef bytes); void encodeInt(int value, BreakingBytesRefBuilder bytesRefBuilder); int decodeInt(BytesRef bytes); void encodeFloat(float value, BreakingBytesRefBuilder bytesRefBuilder); float decodeFloat(BytesRef bytes); void encodeDouble(double value, BreakingBytesRefBuilder bytesRefBuilder); double decodeDouble(BytesRef bytes); void encodeBoolean(boolean value, BreakingBytesRefBuilder bytesRefBuilder); boolean decodeBoolean(BytesRef bytes); int encodeBytesRef(BytesRef value, BreakingBytesRefBuilder bytesRefBuilder); BytesRef decodeBytesRef(BytesRef bytes, BytesRef scratch); /** * Get a version of this encoder that encodes values such that sorting * the encoded bytes sorts by the values. */ TopNEncoder toSortable(); /** * Get a version of this encoder that encodes values as fast as possible * without making the encoded bytes sortable. */ TopNEncoder toUnsortable(); }
TopNEncoder