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
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/certReload/ManagementHttpServerTlsCertificateReloadTest.java
{ "start": 1936, "end": 5281 }
class ____ { public static final File temp = new File("target/test-certificates-" + UUID.randomUUID()); private static final String APP_PROPS = """ quarkus.management.enabled=true quarkus.management.ssl.certificate.reload-period=30s quarkus.management.ssl.certificate.files=%s quarkus.management.ssl.certificate.key-files=%s loc=%s """.formatted(temp.getAbsolutePath() + "/tls.crt", temp.getAbsolutePath() + "/tls.key", temp.getAbsolutePath()); @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addAsResource(new StringAsset(APP_PROPS), "application.properties")) .setBeforeAllCustomizer(() -> { try { // Prepare a random directory to store the certificates. temp.mkdirs(); Files.copy(new File("target/certificates/reload-C.crt").toPath(), new File(temp, "/tls.crt").toPath()); Files.copy(new File("target/certificates/reload-C.key").toPath(), new File(temp, "/tls.key").toPath()); Files.copy(new File("target/certificates/reload-C-ca.crt").toPath(), new File(temp, "/ca.crt").toPath()); } catch (Exception e) { throw new RuntimeException(e); } }) .addBuildChainCustomizer(buildCustomizer()) .setAfterAllCustomizer(() -> { try { Files.deleteIfExists(new File(temp, "/tls.crt").toPath()); Files.deleteIfExists(new File(temp, "/tls.key").toPath()); Files.deleteIfExists(new File(temp, "/ca.crt").toPath()); Files.deleteIfExists(temp.toPath()); } catch (Exception e) { throw new RuntimeException(e); } }); static Consumer<BuildChainBuilder> buildCustomizer() { return new Consumer<BuildChainBuilder>() { @Override public void accept(BuildChainBuilder builder) { builder.addBuildStep(new BuildStep() { @Override public void execute(BuildContext context) { NonApplicationRootPathBuildItem buildItem = context.consume(NonApplicationRootPathBuildItem.class); context.produce(buildItem.routeBuilder() .management() .route("/hello") .handler(new MyHandler()) .build()); } }).produces(RouteBuildItem.class) .consumes(NonApplicationRootPathBuildItem.class) .build(); } }; } @Inject Vertx vertx; @ConfigProperty(name = "loc") File certs; @Test void test() throws IOException, ExecutionException, InterruptedException, TimeoutException { var options = new HttpClientOptions() .setSsl(true) .setDefaultPort(9001) // Management
ManagementHttpServerTlsCertificateReloadTest
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/authorization/method/Jsr250AuthorizationManagerTests.java
{ "start": 11498, "end": 11593 }
class ____ { public void inheritedAnnotations() { } } public
ClassLevelIllegalAnnotations
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/management/ManagementWithJksWithAliasTest.java
{ "start": 3289, "end": 4054 }
class ____ implements Handler<RoutingContext> { @Override public void handle(RoutingContext rc) { Assertions.assertThat(rc.request().connection().isSsl()).isTrue(); Assertions.assertThat(rc.request().isSSL()).isTrue(); Assertions.assertThat(rc.request().connection().sslSession()).isNotNull(); rc.response().end("ssl"); } } @Test public void testSslWithJks() { RestAssured.given() .trustStore(new File("target/certs/ssl-management-interface-alias-test-truststore.jks"), "secret") .get("https://localhost:9001/management/my-route") .then().statusCode(200).body(Matchers.equalTo("ssl")); } @Singleton static
MyHandler
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/ProcessTableFunction.java
{ "start": 11209, "end": 11510 }
class ____ { * public long count = 0L; * } * * public void eval(@StateHint CountState memory, @ArgumentHint(SET_SEMANTIC_TABLE) Row input) { * memory.count++; * collect("Seen rows: " + memory.count); * } * } * * // Function that waits for a second event coming in *
CountState
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
{ "start": 44788, "end": 49346 }
class ____ extends Call { final Connection connection; // connection to client final Writable rpcRequest; // Serialized Rpc request from client ByteBuffer rpcResponse; // the response for this call private ResponseParams responseParams; // the response params private Writable rv; // the byte response RpcCall(RpcCall call) { super(call); this.connection = call.connection; this.rpcRequest = call.rpcRequest; this.rv = call.rv; this.responseParams = call.responseParams; } RpcCall(Connection connection, int id) { this(connection, id, RpcConstants.INVALID_RETRY_COUNT); } RpcCall(Connection connection, int id, int retryCount) { this(connection, id, retryCount, null, RPC.RpcKind.RPC_BUILTIN, RpcConstants.DUMMY_CLIENT_ID, null, null); } RpcCall(Connection connection, int id, int retryCount, Writable param, RPC.RpcKind kind, byte[] clientId, Span span, CallerContext context) { this(connection, id, retryCount, param, kind, clientId, span, context, new byte[0]); } RpcCall(Connection connection, int id, int retryCount, Writable param, RPC.RpcKind kind, byte[] clientId, Span span, CallerContext context, byte[] authHeader) { super(id, retryCount, kind, clientId, span, context, authHeader); this.connection = connection; this.rpcRequest = param; } @Override boolean isOpen() { return connection.channel.isOpen(); } void setResponseFields(Writable returnValue, ResponseParams responseParams) { this.rv = returnValue; this.responseParams = responseParams; } @Override public String getProtocol() { return "rpc"; } @Override public UserGroupInformation getRemoteUser() { return connection.user; } @Override public InetAddress getHostInetAddress() { return connection.getHostInetAddress(); } @Override public int getRemotePort() { return connection.getRemotePort(); } @Override public Void run() throws Exception { if (!connection.channel.isOpen()) { Server.LOG.info(Thread.currentThread().getName() + ": skipped " + this); return null; } long startNanos = Time.monotonicNowNanos(); this.setStartHandleTimestampNanos(startNanos); Writable value = null; ResponseParams responseParams = new ResponseParams(); try { value = call( rpcKind, connection.protocolName, rpcRequest, getTimestampNanos()); } catch (Throwable e) { populateResponseParamsOnError(e, responseParams); } if (!isResponseDeferred()) { long deltaNanos = Time.monotonicNowNanos() - startNanos; ProcessingDetails details = getProcessingDetails(); details.set(Timing.PROCESSING, deltaNanos, TimeUnit.NANOSECONDS); deltaNanos -= details.get(Timing.LOCKWAIT, TimeUnit.NANOSECONDS); deltaNanos -= details.get(Timing.LOCKSHARED, TimeUnit.NANOSECONDS); deltaNanos -= details.get(Timing.LOCKEXCLUSIVE, TimeUnit.NANOSECONDS); details.set(Timing.LOCKFREE, deltaNanos, TimeUnit.NANOSECONDS); setResponseFields(value, responseParams); sendResponse(); details.setReturnStatus(responseParams.returnStatus); } else { LOG.debug("Deferring response for callId: {}", this.callId); } return null; } /** * @param t the {@link java.lang.Throwable} to use to set * errorInfo * @param responseParams the {@link ResponseParams} instance to populate */ private void populateResponseParamsOnError(Throwable t, ResponseParams responseParams) { if (t instanceof UndeclaredThrowableException) { t = t.getCause(); } logException(Server.LOG, t, this); if (t instanceof RpcServerException) { RpcServerException rse = ((RpcServerException) t); responseParams.returnStatus = rse.getRpcStatusProto(); responseParams.detailedErr = rse.getRpcErrorCodeProto(); } else { responseParams.returnStatus = RpcStatusProto.ERROR; responseParams.detailedErr = RpcErrorCodeProto.ERROR_APPLICATION; } responseParams.errorClass = t.getClass().getName(); responseParams.error = StringUtils.stringifyException(t); // Remove redundant error
RpcCall
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSNamesystem.java
{ "start": 12872, "end": 13163 }
class ____ implements AuditLogger { @Override public void initialize(Configuration conf) { } @Override public void logAuditEvent(boolean succeeded, String userName, InetAddress addr, String cmd, String src, String dst, FileStatus stat) { } } }
DummyAuditLogger
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/R2dbcReactiveOAuth2AuthorizedClientService.java
{ "start": 10337, "end": 12638 }
class ____ { private final String clientRegistrationId; private final String principalName; private final OAuth2AccessToken accessToken; private final OAuth2RefreshToken refreshToken; /** * Constructs an {@code OAuth2AuthorizedClientHolder} using the provided * parameters. * @param authorizedClient the authorized client * @param principal the End-User {@link Authentication} (Resource Owner) */ public OAuth2AuthorizedClientHolder(OAuth2AuthorizedClient authorizedClient, Authentication principal) { Assert.notNull(authorizedClient, "authorizedClient cannot be null"); Assert.notNull(principal, "principal cannot be null"); this.clientRegistrationId = authorizedClient.getClientRegistration().getRegistrationId(); this.principalName = principal.getName(); this.accessToken = authorizedClient.getAccessToken(); this.refreshToken = authorizedClient.getRefreshToken(); } /** * Constructs an {@code OAuth2AuthorizedClientHolder} using the provided * parameters. * @param clientRegistrationId the client registration id * @param principalName the principal name of the End-User (Resource Owner) * @param accessToken the access token * @param refreshToken the refresh token */ public OAuth2AuthorizedClientHolder(String clientRegistrationId, String principalName, OAuth2AccessToken accessToken, OAuth2RefreshToken refreshToken) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.hasText(principalName, "principalName cannot be empty"); Assert.notNull(accessToken, "accessToken cannot be null"); this.clientRegistrationId = clientRegistrationId; this.principalName = principalName; this.accessToken = accessToken; this.refreshToken = refreshToken; } public String getClientRegistrationId() { return this.clientRegistrationId; } public String getPrincipalName() { return this.principalName; } public OAuth2AccessToken getAccessToken() { return this.accessToken; } public OAuth2RefreshToken getRefreshToken() { return this.refreshToken; } } /** * The default {@code Function} that maps {@link OAuth2AuthorizedClientHolder} to a * {@code Map} of {@link String} and {@link Parameter}. */ public static
OAuth2AuthorizedClientHolder
java
spring-projects__spring-security
saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationTests.java
{ "start": 1218, "end": 12676 }
class ____ { @Test public void withRelyingPartyRegistrationWorks() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() .nameIdFormat("format") .authnRequestsSigned(true) .assertingPartyMetadata((a) -> a.singleSignOnServiceBinding(Saml2MessageBinding.POST)) .assertingPartyMetadata((a) -> a.wantAuthnRequestsSigned(false)) .assertingPartyMetadata((a) -> a.signingAlgorithms((algs) -> algs.add("alg"))) .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT) .build(); RelyingPartyRegistration copy = registration.mutate().build(); compareRegistrations(registration, copy); } @Test void mutateWhenInvokedThenCreatesCopy() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() .nameIdFormat("format") .assertingPartyMetadata((a) -> a.singleSignOnServiceBinding(Saml2MessageBinding.POST)) .assertingPartyMetadata((a) -> a.wantAuthnRequestsSigned(false)) .assertingPartyMetadata((a) -> a.signingAlgorithms((algs) -> algs.add("alg"))) .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT) .build(); RelyingPartyRegistration copy = registration.mutate().build(); compareRegistrations(registration, copy); } private void compareRegistrations(RelyingPartyRegistration registration, RelyingPartyRegistration copy) { assertThat(copy.getRegistrationId()).isEqualTo(registration.getRegistrationId()).isEqualTo("simplesamlphp"); assertThat(copy.getAssertingPartyMetadata().getEntityId()) .isEqualTo(registration.getAssertingPartyMetadata().getEntityId()) .isEqualTo("https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/metadata.php"); assertThat(copy.getAssertionConsumerServiceLocation()) .isEqualTo(registration.getAssertionConsumerServiceLocation()) .isEqualTo("{baseUrl}" + Saml2WebSsoAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI); assertThat(copy.getSigningX509Credentials()).containsAll(registration.getSigningX509Credentials()); assertThat(copy.getDecryptionX509Credentials()).containsAll(registration.getDecryptionX509Credentials()); assertThat(copy.getEntityId()).isEqualTo(registration.getEntityId()) .isEqualTo(copy.getEntityId()) .isEqualTo(registration.getEntityId()) .isEqualTo("{baseUrl}/saml2/service-provider-metadata/{registrationId}"); assertThat(copy.getAssertingPartyMetadata().getSingleSignOnServiceLocation()) .isEqualTo(registration.getAssertingPartyMetadata().getSingleSignOnServiceLocation()) .isEqualTo("https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/SSOService.php"); assertThat(copy.getAssertingPartyMetadata().getSingleSignOnServiceBinding()) .isEqualTo(registration.getAssertingPartyMetadata().getSingleSignOnServiceBinding()) .isEqualTo(Saml2MessageBinding.POST); assertThat(copy.getAssertingPartyMetadata().getWantAuthnRequestsSigned()) .isEqualTo(registration.getAssertingPartyMetadata().getWantAuthnRequestsSigned()) .isFalse(); assertThat(copy.getAssertionConsumerServiceBinding()) .isEqualTo(registration.getAssertionConsumerServiceBinding()); assertThat(copy.getDecryptionX509Credentials()).isEqualTo(registration.getDecryptionX509Credentials()); assertThat(copy.getSigningX509Credentials()).isEqualTo(registration.getSigningX509Credentials()); assertThat(copy.getAssertingPartyMetadata().getEncryptionX509Credentials()) .isEqualTo(registration.getAssertingPartyMetadata().getEncryptionX509Credentials()); assertThat(copy.getAssertingPartyMetadata().getVerificationX509Credentials()) .isEqualTo(registration.getAssertingPartyMetadata().getVerificationX509Credentials()); assertThat(copy.getAssertingPartyMetadata().getSigningAlgorithms()) .isEqualTo(registration.getAssertingPartyMetadata().getSigningAlgorithms()); assertThat(copy.getNameIdFormat()).isEqualTo(registration.getNameIdFormat()); assertThat(copy.isAuthnRequestsSigned()).isEqualTo(registration.isAuthnRequestsSigned()); } @Test public void buildWhenUsingDefaultsThenAssertionConsumerServiceBindingDefaultsToPost() { RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("id") .entityId("entity-id") .assertionConsumerServiceLocation("location") .assertingPartyMetadata((assertingParty) -> assertingParty.entityId("entity-id") .singleSignOnServiceLocation("location") .verificationX509Credentials((c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential()))) .build(); assertThat(relyingPartyRegistration.getAssertionConsumerServiceBinding()).isEqualTo(Saml2MessageBinding.POST); } @Test public void buildPreservesCredentialsOrder() { Saml2X509Credential altRpCredential = TestSaml2X509Credentials.altPrivateCredential(); Saml2X509Credential altApCredential = TestSaml2X509Credentials.altPublicCredential(); Saml2X509Credential verifyingCredential = TestSaml2X509Credentials.relyingPartyVerifyingCredential(); Saml2X509Credential encryptingCredential = TestSaml2X509Credentials.relyingPartyEncryptingCredential(); Saml2X509Credential signingCredential = TestSaml2X509Credentials.relyingPartySigningCredential(); Saml2X509Credential decryptionCredential = TestSaml2X509Credentials.relyingPartyDecryptingCredential(); // Test with the alt credentials first RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.noCredentials() .assertingPartyMetadata((assertingParty) -> assertingParty.verificationX509Credentials((c) -> { c.add(altApCredential); c.add(verifyingCredential); }).encryptionX509Credentials((c) -> { c.add(altApCredential); c.add(encryptingCredential); })) .signingX509Credentials((c) -> { c.add(altRpCredential); c.add(signingCredential); }) .decryptionX509Credentials((c) -> { c.add(altRpCredential); c.add(decryptionCredential); }) .build(); assertThat(relyingPartyRegistration.getSigningX509Credentials()).containsExactly(altRpCredential, signingCredential); assertThat(relyingPartyRegistration.getDecryptionX509Credentials()).containsExactly(altRpCredential, decryptionCredential); assertThat(relyingPartyRegistration.getAssertingPartyMetadata().getVerificationX509Credentials()) .containsExactly(altApCredential, verifyingCredential); assertThat(relyingPartyRegistration.getAssertingPartyMetadata().getEncryptionX509Credentials()) .containsExactly(altApCredential, encryptingCredential); // Test with the alt credentials last relyingPartyRegistration = TestRelyingPartyRegistrations.noCredentials() .assertingPartyMetadata((assertingParty) -> assertingParty.verificationX509Credentials((c) -> { c.add(verifyingCredential); c.add(altApCredential); }).encryptionX509Credentials((c) -> { c.add(encryptingCredential); c.add(altApCredential); })) .signingX509Credentials((c) -> { c.add(signingCredential); c.add(altRpCredential); }) .decryptionX509Credentials((c) -> { c.add(decryptionCredential); c.add(altRpCredential); }) .build(); assertThat(relyingPartyRegistration.getSigningX509Credentials()).containsExactly(signingCredential, altRpCredential); assertThat(relyingPartyRegistration.getDecryptionX509Credentials()).containsExactly(decryptionCredential, altRpCredential); assertThat(relyingPartyRegistration.getAssertingPartyMetadata().getVerificationX509Credentials()) .containsExactly(verifyingCredential, altApCredential); assertThat(relyingPartyRegistration.getAssertingPartyMetadata().getEncryptionX509Credentials()) .containsExactly(encryptingCredential, altApCredential); } @Test void withAssertingPartyMetadataWhenMetadataThenBuilderCopies() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() .nameIdFormat("format") .assertingPartyMetadata((a) -> a.singleSignOnServiceBinding(Saml2MessageBinding.POST)) .assertingPartyMetadata((a) -> a.wantAuthnRequestsSigned(false)) .assertingPartyMetadata((a) -> a.signingAlgorithms((algs) -> algs.add("alg"))) .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT) .build(); RelyingPartyRegistration copied = RelyingPartyRegistration .withAssertingPartyMetadata(registration.getAssertingPartyMetadata()) .registrationId(registration.getRegistrationId()) .entityId(registration.getEntityId()) .signingX509Credentials((c) -> c.addAll(registration.getSigningX509Credentials())) .decryptionX509Credentials((c) -> c.addAll(registration.getDecryptionX509Credentials())) .assertionConsumerServiceLocation(registration.getAssertionConsumerServiceLocation()) .assertionConsumerServiceBinding(registration.getAssertionConsumerServiceBinding()) .singleLogoutServiceLocation(registration.getSingleLogoutServiceLocation()) .singleLogoutServiceResponseLocation(registration.getSingleLogoutServiceResponseLocation()) .singleLogoutServiceBindings((c) -> c.addAll(registration.getSingleLogoutServiceBindings())) .nameIdFormat(registration.getNameIdFormat()) .authnRequestsSigned(registration.isAuthnRequestsSigned()) .build(); compareRegistrations(registration, copied); } @Test void withAssertingPartyMetadataWhenMetadataThenDisallowsDetails() { AssertingPartyMetadata metadata = new CustomAssertingPartyMetadata(); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> RelyingPartyRegistration.withAssertingPartyMetadata(metadata) .assertingPartyMetadata((a) -> a.entityId("entity-id")) .build()); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> RelyingPartyRegistration.withAssertingPartyMetadata(metadata) .build() .getAssertingPartyMetadata()); } @Test void withAssertingPartyMetadataWhenDetailsThenBuilderCopies() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() .nameIdFormat("format") .assertingPartyMetadata((a) -> a.singleSignOnServiceBinding(Saml2MessageBinding.POST)) .assertingPartyMetadata((a) -> a.wantAuthnRequestsSigned(false)) .assertingPartyMetadata((a) -> a.signingAlgorithms((algs) -> algs.add("alg"))) .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT) .build(); AssertingPartyMetadata details = registration.getAssertingPartyMetadata(); RelyingPartyRegistration copied = RelyingPartyRegistration.withAssertingPartyMetadata(details) .assertingPartyMetadata((a) -> a.entityId(details.getEntityId())) .registrationId(registration.getRegistrationId()) .entityId(registration.getEntityId()) .signingX509Credentials((c) -> c.addAll(registration.getSigningX509Credentials())) .decryptionX509Credentials((c) -> c.addAll(registration.getDecryptionX509Credentials())) .assertionConsumerServiceLocation(registration.getAssertionConsumerServiceLocation()) .assertionConsumerServiceBinding(registration.getAssertionConsumerServiceBinding()) .singleLogoutServiceLocation(registration.getSingleLogoutServiceLocation()) .singleLogoutServiceResponseLocation(registration.getSingleLogoutServiceResponseLocation()) .singleLogoutServiceBindings((c) -> c.addAll(registration.getSingleLogoutServiceBindings())) .nameIdFormat(registration.getNameIdFormat()) .authnRequestsSigned(registration.isAuthnRequestsSigned()) .build(); compareRegistrations(registration, copied); } private static
RelyingPartyRegistrationTests
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/ObjectUtils.java
{ "start": 20295, "end": 20491 }
class ____ for the given object. * <p>Returns a {@code "null"} String if {@code obj} is {@code null}. * @param obj the object to introspect (may be {@code null}) * @return the corresponding
name
java
spring-projects__spring-security
webauthn/src/main/java/org/springframework/security/web/webauthn/registration/WebAuthnRegistrationFilter.java
{ "start": 3623, "end": 9220 }
class ____ extends OncePerRequestFilter { static final String DEFAULT_REGISTER_CREDENTIAL_URL = "/webauthn/register"; private static final Log logger = LogFactory.getLog(WebAuthnRegistrationFilter.class); private final WebAuthnRelyingPartyOperations rpOptions; private final UserCredentialRepository userCredentials; private HttpMessageConverter<Object> converter = new JacksonJsonHttpMessageConverter( JsonMapper.builder().addModule(new WebauthnJacksonModule()).build()); private PublicKeyCredentialCreationOptionsRepository creationOptionsRepository = new HttpSessionPublicKeyCredentialCreationOptionsRepository(); private RequestMatcher registerCredentialMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.POST, DEFAULT_REGISTER_CREDENTIAL_URL); private RequestMatcher removeCredentialMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.DELETE, "/webauthn/register/{id}"); public WebAuthnRegistrationFilter(UserCredentialRepository userCredentials, WebAuthnRelyingPartyOperations rpOptions) { Assert.notNull(userCredentials, "userCredentials must not be null"); Assert.notNull(rpOptions, "rpOptions must not be null"); this.userCredentials = userCredentials; this.rpOptions = rpOptions; } /** * Sets the {@link RequestMatcher} to trigger this filter's the credential * registration operation . * <p/> * By default, the {@link RequestMatcher} is {@code POST /webauthn/register}. * @param registerCredentialMatcher the {@link RequestMatcher} to use * @since 6.5 */ public void setRegisterCredentialMatcher(RequestMatcher registerCredentialMatcher) { Assert.notNull(registerCredentialMatcher, "registerCredentialMatcher cannot be null"); this.registerCredentialMatcher = registerCredentialMatcher; } /** * Sets the {@link RequestMatcher} to trigger this filter's the credential removal * operation . * <p/> * By default, the {@link RequestMatcher} is {@code DELETE /webauthn/register/{id}}. * @param removeCredentialMatcher the {@link RequestMatcher} to use * @since 6.5 */ public void setRemoveCredentialMatcher(RequestMatcher removeCredentialMatcher) { Assert.notNull(removeCredentialMatcher, "removeCredentialMatcher cannot be null"); this.removeCredentialMatcher = removeCredentialMatcher; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (this.registerCredentialMatcher.matches(request)) { registerCredential(request, response); return; } RequestMatcher.MatchResult removeMatchResult = this.removeCredentialMatcher.matcher(request); if (removeMatchResult.isMatch()) { String id = removeMatchResult.getVariables().get("id"); removeCredential(request, response, id); return; } filterChain.doFilter(request, response); } /** * Set the {@link HttpMessageConverter} to read the * {@link WebAuthnRegistrationRequest} and write the response. The default is * {@link JacksonJsonHttpMessageConverter}. * @param converter the {@link HttpMessageConverter} to use. Cannot be null. */ public void setConverter(HttpMessageConverter<Object> converter) { Assert.notNull(converter, "converter cannot be null"); this.converter = converter; } /** * Sets the {@link PublicKeyCredentialCreationOptionsRepository} to use. The default * is {@link HttpSessionPublicKeyCredentialCreationOptionsRepository}. * @param creationOptionsRepository the * {@link PublicKeyCredentialCreationOptionsRepository} to use. Cannot be null. */ public void setCreationOptionsRepository(PublicKeyCredentialCreationOptionsRepository creationOptionsRepository) { Assert.notNull(creationOptionsRepository, "creationOptionsRepository cannot be null"); this.creationOptionsRepository = creationOptionsRepository; } private void registerCredential(HttpServletRequest request, HttpServletResponse response) throws IOException { WebAuthnRegistrationRequest registrationRequest = readRegistrationRequest(request); if (registrationRequest == null) { response.setStatus(HttpStatus.BAD_REQUEST.value()); return; } PublicKeyCredentialCreationOptions options = this.creationOptionsRepository.load(request); if (options == null) { response.setStatus(HttpStatus.BAD_REQUEST.value()); return; } this.creationOptionsRepository.save(request, response, null); CredentialRecord credentialRecord = this.rpOptions.registerCredential( new ImmutableRelyingPartyRegistrationRequest(options, registrationRequest.getPublicKey())); SuccessfulUserRegistrationResponse registrationResponse = new SuccessfulUserRegistrationResponse( credentialRecord); ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response); this.converter.write(registrationResponse, MediaType.APPLICATION_JSON, outputMessage); } private @Nullable WebAuthnRegistrationRequest readRegistrationRequest(HttpServletRequest request) { HttpInputMessage inputMessage = new ServletServerHttpRequest(request); try { return (WebAuthnRegistrationRequest) this.converter.read(WebAuthnRegistrationRequest.class, inputMessage); } catch (Exception ex) { logger.debug("Unable to parse WebAuthnRegistrationRequest", ex); return null; } } private void removeCredential(HttpServletRequest request, HttpServletResponse response, @Nullable String id) throws IOException { this.userCredentials.delete(Bytes.fromBase64(id)); response.setStatus(HttpStatus.NO_CONTENT.value()); } static
WebAuthnRegistrationFilter
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EqualsIgnoreCaseReplacementConverterTest.java
{ "start": 1307, "end": 2628 }
class ____ { @Test void testMarkerReplacement() { testReplacement("%marker", Strings.EMPTY); } @Test void testMarkerSimpleNameReplacement() { testReplacement("%markerSimpleName", Strings.EMPTY); } @Test void testLoggerNameReplacement() { testReplacement("%logger", "aaa[" + EqualsIgnoreCaseReplacementConverterTest.class.getName() + "]zzz"); } private void testReplacement(final String tag, final String expectedValue) { final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(EqualsIgnoreCaseReplacementConverterTest.class.getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("This is a test")) // .build(); final StringBuilder sb = new StringBuilder(); final LoggerContext ctx = LoggerContext.getContext(); final String[] options = new String[] {"aaa[" + tag + "]zzz", "AAA[]ZZZ", expectedValue}; final EqualsIgnoreCaseReplacementConverter converter = EqualsIgnoreCaseReplacementConverter.newInstance(ctx.getConfiguration(), options); assertNotNull(converter); converter.format(event, sb); assertEquals(expectedValue, sb.toString()); } }
EqualsIgnoreCaseReplacementConverterTest
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/message/ParameterizedMessageFactory.java
{ "start": 1193, "end": 1296 }
class ____ immutable. * </p> * * <p> * <strong>Note to implementors:</strong> * </p> * <p> * This
is
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopDoubleDoubleAggregator.java
{ "start": 4425, "end": 5491 }
class ____ implements AggregatorState { private final GroupingState internalState; private SingleState(BigArrays bigArrays, int limit, boolean ascending) { this.internalState = new GroupingState(bigArrays, limit, ascending); } public void add(double value, double outputValue) { internalState.add(0, value, outputValue); } @Override public void toIntermediate(Block[] blocks, int offset, DriverContext driverContext) { try (var intValues = driverContext.blockFactory().newConstantIntVector(0, 1)) { internalState.toIntermediate(blocks, offset, intValues, driverContext); } } Block toBlock(BlockFactory blockFactory) { try (var intValues = blockFactory.newConstantIntVector(0, 1)) { return internalState.toBlock(blockFactory, intValues); } } @Override public void close() { Releasables.closeExpectNoException(internalState); } } }
SingleState
java
apache__flink
flink-core/src/main/java/org/apache/flink/core/execution/DefaultJobExecutionStatusEvent.java
{ "start": 1102, "end": 2137 }
class ____ implements JobExecutionStatusEvent { private final JobID jobId; private final String jobName; private final JobStatus oldStatus; private final JobStatus newStatus; @Nullable private final Throwable cause; public DefaultJobExecutionStatusEvent( JobID jobId, String jobName, JobStatus oldStatus, JobStatus newStatus, @Nullable Throwable cause) { this.jobId = jobId; this.jobName = jobName; this.oldStatus = oldStatus; this.newStatus = newStatus; this.cause = cause; } @Override public JobStatus oldStatus() { return oldStatus; } @Override public JobStatus newStatus() { return newStatus; } @Nullable @Override public Throwable exception() { return cause; } @Override public JobID jobId() { return jobId; } @Override public String jobName() { return jobName; } }
DefaultJobExecutionStatusEvent
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest3.java
{ "start": 167, "end": 604 }
class ____ extends TestCase { public void test_for_issue() throws Exception { VO vo1 = JSON.parseObject("{\"date\":\"2016-05-05T20:24:28.484\"}", VO.class); Assert.assertEquals(20, vo1.date.getHour()); Assert.assertEquals(24, vo1.date.getMinute()); Assert.assertEquals(28, vo1.date.getSecond()); Assert.assertEquals(484000000, vo1.date.getNano()); } public static
LocalTimeTest3
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/util/Employee.java
{ "start": 692, "end": 1389 }
class ____ implements Comparable<Employee>, Doctor { // field public getter => valid property private final int age; public int getAge() { return age; } // fields without public getter => not a property private final String company = "google"; String getCompany() { return company; } private boolean firstJob; boolean isFirstJob() { return firstJob; } // field without getter => not a property @SuppressWarnings("unused") private final double salary; public Employee(double salary, int age) { super(); this.salary = salary; this.age = age; } @Override public int compareTo(Employee other) { return age - other.age; } }
Employee
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/orderedcollection/PrintJob.java
{ "start": 345, "end": 433 }
class ____ { @Id @GeneratedValue private long id; @Lob private byte[] data; }
PrintJob
java
square__retrofit
retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/CallExecuteObservable.java
{ "start": 2161, "end": 2520 }
class ____ implements Disposable { private final Call<?> call; private volatile boolean disposed; CallDisposable(Call<?> call) { this.call = call; } @Override public void dispose() { disposed = true; call.cancel(); } @Override public boolean isDisposed() { return disposed; } } }
CallDisposable
java
quarkusio__quarkus
extensions/hibernate-search-standalone-elasticsearch/deployment/src/main/java/io/quarkus/hibernate/search/standalone/elasticsearch/deployment/HibernateSearchStandaloneEnabled.java
{ "start": 346, "end": 702 }
class ____ implements BooleanSupplier { protected final HibernateSearchStandaloneBuildTimeConfig config; HibernateSearchStandaloneEnabled(HibernateSearchStandaloneBuildTimeConfig config) { this.config = config; } @Override public boolean getAsBoolean() { return config.enabled(); } }
HibernateSearchStandaloneEnabled
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/PromqlBaseParser.java
{ "start": 9792, "end": 10933 }
class ____ extends ExpressionContext { public TerminalNode LP() { return getToken(PromqlBaseParser.LP, 0); } public ExpressionContext expression() { return getRuleContext(ExpressionContext.class,0); } public TerminalNode RP() { return getToken(PromqlBaseParser.RP, 0); } @SuppressWarnings("this-escape") public ParenthesizedContext(ExpressionContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PromqlBaseParserListener ) ((PromqlBaseParserListener)listener).enterParenthesized(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PromqlBaseParserListener ) ((PromqlBaseParserListener)listener).exitParenthesized(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof PromqlBaseParserVisitor ) return ((PromqlBaseParserVisitor<? extends T>)visitor).visitParenthesized(this); else return visitor.visitChildren(this); } } @SuppressWarnings("CheckReturnValue") public static
ParenthesizedContext
java
apache__flink
flink-table/flink-sql-gateway/src/main/java/org/apache/flink/table/gateway/workflow/WorkflowInfo.java
{ "start": 1374, "end": 4143 }
class ____ { private final String materializedTableIdentifier; private final Map<String, String> dynamicOptions; private final Map<String, String> initConfig; private final Map<String, String> executionConfig; private final String restEndpointUrl; @JsonCreator public WorkflowInfo( @JsonProperty("materializedTableIdentifier") String materializedTableIdentifier, @JsonProperty("dynamicOptions") Map<String, String> dynamicOptions, @JsonProperty("initConfig") Map<String, String> initConfig, @JsonProperty("executionConfig") Map<String, String> executionConfig, @JsonProperty("restEndpointUrl") String restEndpointUrl) { this.materializedTableIdentifier = materializedTableIdentifier; this.dynamicOptions = dynamicOptions; this.initConfig = initConfig; this.executionConfig = executionConfig; this.restEndpointUrl = restEndpointUrl; } public String getMaterializedTableIdentifier() { return materializedTableIdentifier; } public Map<String, String> getDynamicOptions() { return dynamicOptions; } public Map<String, String> getInitConfig() { return initConfig; } public Map<String, String> getExecutionConfig() { return executionConfig; } public String getRestEndpointUrl() { return restEndpointUrl; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WorkflowInfo that = (WorkflowInfo) o; return Objects.equals(materializedTableIdentifier, that.materializedTableIdentifier) && Objects.equals(initConfig, that.initConfig) && Objects.equals(executionConfig, that.executionConfig) && Objects.equals(restEndpointUrl, that.restEndpointUrl); } @Override public int hashCode() { return Objects.hash( materializedTableIdentifier, dynamicOptions, initConfig, executionConfig, restEndpointUrl); } @Override public String toString() { return "WorkflowInfo{" + "materializedTableIdentifier='" + materializedTableIdentifier + '\'' + ", dynamicOptions=" + dynamicOptions + ", initConfig=" + initConfig + ", executionConfig=" + executionConfig + ", restEndpointUrl='" + restEndpointUrl + '\'' + '}'; } }
WorkflowInfo
java
bumptech__glide
library/src/main/java/com/bumptech/glide/util/ExceptionPassthroughInputStream.java
{ "start": 498, "end": 755 }
class ____ a workaround for * a framework issue where exceptions during reads while decoding bitmaps in {@link * android.graphics.BitmapFactory} can return partially decoded bitmaps. * * <p>Unlike the deprecated {@link ExceptionCatchingInputStream}, this
is
java
netty__netty
testsuite/src/main/java/io/netty/testsuite/transport/socket/TrafficShapingHandlerTest.java
{ "start": 2061, "end": 18866 }
class ____ extends AbstractSocketTest { private static final InternalLogger logger = InternalLoggerFactory.getInstance(TrafficShapingHandlerTest.class); private static final InternalLogger loggerServer = InternalLoggerFactory.getInstance("ServerTSH"); private static final InternalLogger loggerClient = InternalLoggerFactory.getInstance("ClientTSH"); static final int messageSize = 1024; static final int bandwidthFactor = 12; static final int minfactor = 3; static final int maxfactor = bandwidthFactor + bandwidthFactor / 2; static final long stepms = (1000 / bandwidthFactor - 10) / 10 * 10; static final long minimalms = Math.max(stepms / 2, 20) / 10 * 10; static final long check = 10; private static final Random random = new Random(); static final byte[] data = new byte[messageSize]; private static final String TRAFFIC = "traffic"; private static String currentTestName; private static int currentTestRun; private static EventExecutorGroup group; private static EventExecutorGroup groupForGlobal; private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(10); static { random.nextBytes(data); } @BeforeAll public static void createGroup() { logger.info("Bandwidth: " + minfactor + " <= " + bandwidthFactor + " <= " + maxfactor + " StepMs: " + stepms + " MinMs: " + minimalms + " CheckMs: " + check); group = new DefaultEventExecutorGroup(8); groupForGlobal = new DefaultEventExecutorGroup(8); } @AfterAll public static void destroyGroup() throws Exception { group.shutdownGracefully().sync(); groupForGlobal.shutdownGracefully().sync(); executor.shutdown(); } private static long[] computeWaitRead(int[] multipleMessage) { long[] minimalWaitBetween = new long[multipleMessage.length + 1]; minimalWaitBetween[0] = 0; for (int i = 0; i < multipleMessage.length; i++) { if (multipleMessage[i] > 1) { minimalWaitBetween[i + 1] = (multipleMessage[i] - 1) * stepms + minimalms; } else { minimalWaitBetween[i + 1] = 10; } } return minimalWaitBetween; } private static long[] computeWaitWrite(int[] multipleMessage) { long[] minimalWaitBetween = new long[multipleMessage.length + 1]; for (int i = 0; i < multipleMessage.length; i++) { if (multipleMessage[i] > 1) { minimalWaitBetween[i] = (multipleMessage[i] - 1) * stepms + minimalms; } else { minimalWaitBetween[i] = 10; } } return minimalWaitBetween; } private static long[] computeWaitAutoRead(int []autoRead) { long [] minimalWaitBetween = new long[autoRead.length + 1]; minimalWaitBetween[0] = 0; for (int i = 0; i < autoRead.length; i++) { if (autoRead[i] != 0) { if (autoRead[i] > 0) { minimalWaitBetween[i + 1] = -1; } else { minimalWaitBetween[i + 1] = check; } } else { minimalWaitBetween[i + 1] = 0; } } return minimalWaitBetween; } @Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testNoTrafficShapping(TestInfo testInfo) throws Throwable { currentTestName = "TEST NO TRAFFIC"; currentTestRun = 0; run(testInfo, new Runner<ServerBootstrap, Bootstrap>() { @Override public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable { testNoTrafficShapping(serverBootstrap, bootstrap); } }); } public void testNoTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 2, 1 }; long[] minimalWaitBetween = null; testTrafficShapping0(sb, cb, false, false, false, false, autoRead, minimalWaitBetween, multipleMessage); } @Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testWriteTrafficShapping(TestInfo testInfo) throws Throwable { currentTestName = "TEST WRITE"; currentTestRun = 0; run(testInfo, new Runner<ServerBootstrap, Bootstrap>() { @Override public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable { testWriteTrafficShapping(serverBootstrap, bootstrap); } }); } public void testWriteTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 2, 1, 1 }; long[] minimalWaitBetween = computeWaitWrite(multipleMessage); testTrafficShapping0(sb, cb, false, false, true, false, autoRead, minimalWaitBetween, multipleMessage); } @Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testReadTrafficShapping(TestInfo testInfo) throws Throwable { currentTestName = "TEST READ"; currentTestRun = 0; run(testInfo, new Runner<ServerBootstrap, Bootstrap>() { @Override public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable { testReadTrafficShapping(serverBootstrap, bootstrap); } }); } public void testReadTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 2, 1, 1 }; long[] minimalWaitBetween = computeWaitRead(multipleMessage); testTrafficShapping0(sb, cb, false, true, false, false, autoRead, minimalWaitBetween, multipleMessage); } @Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testWrite1TrafficShapping(TestInfo testInfo) throws Throwable { currentTestName = "TEST WRITE"; currentTestRun = 0; run(testInfo, new Runner<ServerBootstrap, Bootstrap>() { @Override public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable { testWrite1TrafficShapping(serverBootstrap, bootstrap); } }); } public void testWrite1TrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 1, 1 }; long[] minimalWaitBetween = computeWaitWrite(multipleMessage); testTrafficShapping0(sb, cb, false, false, true, false, autoRead, minimalWaitBetween, multipleMessage); } @Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testRead1TrafficShapping(TestInfo testInfo) throws Throwable { currentTestName = "TEST READ"; currentTestRun = 0; run(testInfo, new Runner<ServerBootstrap, Bootstrap>() { @Override public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable { testRead1TrafficShapping(serverBootstrap, bootstrap); } }); } public void testRead1TrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 1, 1 }; long[] minimalWaitBetween = computeWaitRead(multipleMessage); testTrafficShapping0(sb, cb, false, true, false, false, autoRead, minimalWaitBetween, multipleMessage); } @Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testWriteGlobalTrafficShapping(TestInfo testInfo) throws Throwable { currentTestName = "TEST GLOBAL WRITE"; currentTestRun = 0; run(testInfo, new Runner<ServerBootstrap, Bootstrap>() { @Override public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable { testWriteGlobalTrafficShapping(serverBootstrap, bootstrap); } }); } public void testWriteGlobalTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 2, 1, 1 }; long[] minimalWaitBetween = computeWaitWrite(multipleMessage); testTrafficShapping0(sb, cb, false, false, true, true, autoRead, minimalWaitBetween, multipleMessage); } @Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testReadGlobalTrafficShapping(TestInfo testInfo) throws Throwable { currentTestName = "TEST GLOBAL READ"; currentTestRun = 0; run(testInfo, new Runner<ServerBootstrap, Bootstrap>() { @Override public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable { testReadGlobalTrafficShapping(serverBootstrap, bootstrap); } }); } public void testReadGlobalTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 2, 1, 1 }; long[] minimalWaitBetween = computeWaitRead(multipleMessage); testTrafficShapping0(sb, cb, false, true, false, true, autoRead, minimalWaitBetween, multipleMessage); } @Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testAutoReadTrafficShapping(TestInfo testInfo) throws Throwable { currentTestName = "TEST AUTO READ"; currentTestRun = 0; run(testInfo, new Runner<ServerBootstrap, Bootstrap>() { @Override public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable { testAutoReadTrafficShapping(serverBootstrap, bootstrap); } }); } public void testAutoReadTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = { 1, -1, -1, 1, -2, 0, 1, 0, -3, 0, 1, 2, 0 }; int[] multipleMessage = new int[autoRead.length]; Arrays.fill(multipleMessage, 1); long[] minimalWaitBetween = computeWaitAutoRead(autoRead); testTrafficShapping0(sb, cb, false, true, false, false, autoRead, minimalWaitBetween, multipleMessage); } @Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testAutoReadGlobalTrafficShapping(TestInfo testInfo) throws Throwable { currentTestName = "TEST AUTO READ GLOBAL"; currentTestRun = 0; run(testInfo, new Runner<ServerBootstrap, Bootstrap>() { @Override public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable { testAutoReadGlobalTrafficShapping(serverBootstrap, bootstrap); } }); } public void testAutoReadGlobalTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = { 1, -1, -1, 1, -2, 0, 1, 0, -3, 0, 1, 2, 0 }; int[] multipleMessage = new int[autoRead.length]; Arrays.fill(multipleMessage, 1); long[] minimalWaitBetween = computeWaitAutoRead(autoRead); testTrafficShapping0(sb, cb, false, true, false, true, autoRead, minimalWaitBetween, multipleMessage); } /** * * @param additionalExecutor * shall the pipeline add the handler using an additional executor * @param limitRead * True to set Read Limit on Server side * @param limitWrite * True to set Write Limit on Client side * @param globalLimit * True to change Channel to Global TrafficShapping * @param minimalWaitBetween * time in ms that should be waited before getting the final result (note: for READ the values are * right shifted once, the first value being 0) * @param multipleMessage * how many message to send at each step (for READ: the first should be 1, as the two last steps to * ensure correct testing) * @throws Throwable */ private static void testTrafficShapping0( ServerBootstrap sb, Bootstrap cb, final boolean additionalExecutor, final boolean limitRead, final boolean limitWrite, final boolean globalLimit, int[] autoRead, long[] minimalWaitBetween, int[] multipleMessage) throws Throwable { currentTestRun++; logger.info("TEST: " + currentTestName + " RUN: " + currentTestRun + " Exec: " + additionalExecutor + " Read: " + limitRead + " Write: " + limitWrite + " Global: " + globalLimit); final ServerHandler sh = new ServerHandler(autoRead, multipleMessage); Promise<Boolean> promise = group.next().newPromise(); final ClientHandler ch = new ClientHandler(promise, minimalWaitBetween, multipleMessage, autoRead); final AbstractTrafficShapingHandler handler; if (limitRead) { if (globalLimit) { handler = new GlobalTrafficShapingHandler(groupForGlobal, 0, bandwidthFactor * messageSize, check); } else { handler = new ChannelTrafficShapingHandler(0, bandwidthFactor * messageSize, check); } } else if (limitWrite) { if (globalLimit) { handler = new GlobalTrafficShapingHandler(groupForGlobal, bandwidthFactor * messageSize, 0, check); } else { handler = new ChannelTrafficShapingHandler(bandwidthFactor * messageSize, 0, check); } } else { handler = null; } sb.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel c) throws Exception { if (limitRead) { c.pipeline().addLast(TRAFFIC, handler); } c.pipeline().addLast(sh); } }); cb.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel c) throws Exception { if (limitWrite) { c.pipeline().addLast(TRAFFIC, handler); } c.pipeline().addLast(ch); } }); Channel sc = sb.bind().sync().channel(); Channel cc = cb.connect(sc.localAddress()).sync().channel(); int totalNb = 0; for (int i = 1; i < multipleMessage.length; i++) { totalNb += multipleMessage[i]; } Long start = TrafficCounter.milliSecondFromNano(); int nb = multipleMessage[0]; for (int i = 0; i < nb; i++) { cc.write(cc.alloc().buffer().writeBytes(data)); } cc.flush(); promise.await(); Long stop = TrafficCounter.milliSecondFromNano(); assertTrue(promise.isSuccess(), "Error during execution of TrafficShapping: " + promise.cause()); float average = (totalNb * messageSize) / (float) (stop - start); logger.info("TEST: " + currentTestName + " RUN: " + currentTestRun + " Average of traffic: " + average + " compare to " + bandwidthFactor); sh.channel.close().sync(); ch.channel.close().sync(); sc.close().sync(); if (autoRead != null) { // for extra release call in AutoRead Thread.sleep(minimalms); } if (autoRead == null && minimalWaitBetween != null) { assertTrue(average <= maxfactor, "Overall Traffic not ok since > " + maxfactor + ": " + average); if (additionalExecutor) { // Oio is not as good when using additionalExecutor assertTrue(average >= 0.25, "Overall Traffic not ok since < 0.25: " + average); } else { assertTrue(average >= minfactor, "Overall Traffic not ok since < " + minfactor + ": " + average); } } if (handler != null && globalLimit) { ((GlobalTrafficShapingHandler) handler).release(); } if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) { throw ch.exception.get(); } if (sh.exception.get() != null) { throw sh.exception.get(); } if (ch.exception.get() != null) { throw ch.exception.get(); } } private static
TrafficShapingHandlerTest
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/annotation/AliasFor.java
{ "start": 4853, "end": 5140 }
class ____ declares {@code @AliasFor}.</li> * </ol> * </li> * </ul> * * <h3>Example: Explicit Aliases within an Annotation</h3> * <p>In {@code @ContextConfiguration}, {@code value} and {@code locations} * are explicit aliases for each other. * * <pre class="code"> public &#064;
that
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/SalesforceComponentTest.java
{ "start": 956, "end": 1697 }
class ____ extends AbstractSalesforceTestBase { private SalesforceHttpClient client = new SalesforceHttpClient(); private SalesforceComponent component; @Test public void usesUserSuppliedHttpClient() { assertEquals(client, component.getHttpClient()); } @Override protected void createComponent() throws Exception { super.createComponent(); client = new SalesforceHttpClient(); SalesforceEndpointConfig config = new SalesforceEndpointConfig(); config.setHttpClient(client); component = (SalesforceComponent) context.getComponent("salesforce"); component.setConfig(config); component.getLoginConfig().setLazyLogin(true); } }
SalesforceComponentTest
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/source/SelectionParameters.java
{ "start": 3615, "end": 4016 }
class ____ name */ public List<TypeMirror> getQualifiers() { return qualifiers; } /** * * @return qualifyingNames see qualifiers, used in combination with with @Named */ public List<String> getQualifyingNames() { return qualifyingNames; } /** * @return qualifiers used for further select the appropriate presence check method based on
and
java
apache__camel
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/number/grouping/BindyBigDecimalGroupingUnmarshallTest.java
{ "start": 2878, "end": 3470 }
class ____ { @DataField(pos = 1, precision = 2, rounding = "CEILING", pattern = "###,###.###", decimalSeparator = ",", groupingSeparator = ".") private BigDecimal grouping; public BigDecimal getGrouping() { return grouping; } public void setGrouping(BigDecimal grouping) { this.grouping = grouping; } @Override public String toString() { return "bigDecimal grouping : " + this.grouping; } } }
NumberModel
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/RMFatalEvent.java
{ "start": 1047, "end": 3052 }
class ____ extends AbstractEvent<RMFatalEventType> { private final Exception cause; private final String message; /** * Create a new event of the given type with the given cause. * @param rmFatalEventType The {@link RMFatalEventType} of the event * @param message a text description of the reason for the event */ public RMFatalEvent(RMFatalEventType rmFatalEventType, String message) { this(rmFatalEventType, null, message); } /** * Create a new event of the given type around the given source * {@link Exception}. * @param rmFatalEventType The {@link RMFatalEventType} of the event * @param cause the source exception */ public RMFatalEvent(RMFatalEventType rmFatalEventType, Exception cause) { this(rmFatalEventType, cause, null); } /** * Create a new event of the given type around the given source * {@link Exception} with the given cause. * @param rmFatalEventType The {@link RMFatalEventType} of the event * @param cause the source exception * @param message a text description of the reason for the event */ public RMFatalEvent(RMFatalEventType rmFatalEventType, Exception cause, String message) { super(rmFatalEventType); this.cause = cause; this.message = message; } /** * Get a text description of the reason for the event. If a cause was, that * {@link Exception} will be converted to a {@link String} and included in * the result. * @return a text description of the reason for the event */ public String getExplanation() { StringBuilder sb = new StringBuilder(); if (message != null) { sb.append(message); if (cause != null) { sb.append(": "); } } if (cause != null) { sb.append(StringUtils.stringifyException(cause)); } return sb.toString(); } @Override public String toString() { return String.format("RMFatalEvent of type %s, caused by %s", getType().name(), getExplanation()); } }
RMFatalEvent
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/paramcheck/ExtractorManager.java
{ "start": 1265, "end": 1478 }
class ____ { /** * ParamChecker will first look for the Checker annotation in the handler method, and if that annotation is null, it * will try to find the Checker annotation on the
ExtractorManager
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/OverrideStrictTypeInfoHandling3877Test.java
{ "start": 1135, "end": 1365 }
class ____ implements DefaultCommand {} @JsonTypeInfo(use = Id.NAME, requireTypeIdForSubtypes = OptBoolean.TRUE) @JsonSubTypes({ @JsonSubTypes.Type(value = DoTrueCommand.class, name = "do-true")})
DoDefaultCommand
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/aggs/kstest/SamplingMethod.java
{ "start": 2722, "end": 3455 }
class ____ extends SamplingMethod { public static final String NAME = "lower_tail"; private static final double[] CDF_POINTS; static { CDF_POINTS = new double[UpperTail.CDF_POINTS.length]; for (int i = 0; i < CDF_POINTS.length; i++) { CDF_POINTS[i] = 1 - UpperTail.CDF_POINTS[i]; } } @Override public String getName() { return NAME; } @Override protected double[] cdfPoints() { return CDF_POINTS; } } /** * A sampling methodology that provides CDF points that is uniformly sampled. * Meaning, all values are sampled equally */ public static
LowerTail
java
apache__dubbo
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleListener.java
{ "start": 3405, "end": 13393 }
class ____ implements RegistryProtocolListener, ConfigurationListener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MigrationRuleListener.class); private static final String DUBBO_SERVICEDISCOVERY_MIGRATION = "DUBBO_SERVICEDISCOVERY_MIGRATION"; private static final String MIGRATION_DELAY_KEY = "dubbo.application.migration.delay"; private static final int MIGRATION_DEFAULT_DELAY_TIME = 60000; private String ruleKey; protected final ConcurrentMap<MigrationInvoker<?>, MigrationRuleHandler<?>> handlers = new ConcurrentHashMap<>(); protected final LinkedBlockingQueue<String> ruleQueue = new LinkedBlockingQueue<>(); private final AtomicBoolean executorSubmit = new AtomicBoolean(false); private final ExecutorService ruleManageExecutor = Executors.newFixedThreadPool(1, new NamedThreadFactory("Dubbo-Migration-Listener")); protected ScheduledFuture<?> localRuleMigrationFuture; protected Future<?> ruleMigrationFuture; private DynamicConfiguration configuration; private volatile String rawRule; private volatile MigrationRule rule; private final ModuleModel moduleModel; public MigrationRuleListener(ModuleModel moduleModel) { this.moduleModel = moduleModel; init(); } private void init() { this.ruleKey = moduleModel.getApplicationModel().getApplicationName() + ".migration"; this.configuration = moduleModel.modelEnvironment().getDynamicConfiguration().orElse(null); if (this.configuration != null) { logger.info("Listening for migration rules on dataId " + ruleKey + ", group " + DUBBO_SERVICEDISCOVERY_MIGRATION); configuration.addListener(ruleKey, DUBBO_SERVICEDISCOVERY_MIGRATION, this); String rawRule = configuration.getConfig(ruleKey, DUBBO_SERVICEDISCOVERY_MIGRATION); if (StringUtils.isEmpty(rawRule)) { rawRule = INIT; } setRawRule(rawRule); } else { if (logger.isWarnEnabled()) { logger.warn( REGISTRY_EMPTY_ADDRESS, "", "", "Using default configuration rule because config center is not configured!"); } setRawRule(INIT); } String localRawRule = moduleModel.modelEnvironment().getLocalMigrationRule(); if (!StringUtils.isEmpty(localRawRule)) { localRuleMigrationFuture = moduleModel .getApplicationModel() .getFrameworkModel() .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getSharedScheduledExecutor() .schedule( () -> { if (this.rawRule.equals(INIT)) { this.process(new ConfigChangedEvent(null, null, localRawRule)); } }, getDelay(), TimeUnit.MILLISECONDS); } } private int getDelay() { int delay = MIGRATION_DEFAULT_DELAY_TIME; String delayStr = ConfigurationUtils.getProperty(moduleModel, MIGRATION_DELAY_KEY); if (StringUtils.isEmpty(delayStr)) { return delay; } try { delay = Integer.parseInt(delayStr); } catch (Exception e) { logger.warn(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Invalid migration delay param " + delayStr); } return delay; } @Override public synchronized void process(ConfigChangedEvent event) { String rawRule = event.getContent(); if (StringUtils.isEmpty(rawRule)) { // fail back to startup status rawRule = INIT; // logger.warn(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Received empty migration rule, will ignore."); } try { ruleQueue.put(rawRule); } catch (InterruptedException e) { logger.error( COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Put rawRule to rule management queue failed. rawRule: " + rawRule, e); } if (executorSubmit.compareAndSet(false, true)) { ruleMigrationFuture = ruleManageExecutor.submit(() -> { while (true) { String rule = ""; try { rule = ruleQueue.take(); if (StringUtils.isEmpty(rule)) { Thread.sleep(1000); } } catch (InterruptedException e) { logger.error( COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Poll Rule from config center failed.", e); } if (StringUtils.isEmpty(rule)) { continue; } if (Objects.equals(this.rawRule, rule)) { logger.info("Ignore duplicated rule"); continue; } logger.info("Using the following migration rule to migrate:"); logger.info(rule); setRawRule(rule); if (CollectionUtils.isEmptyMap(handlers)) { continue; } ExecutorService executorService = null; try { executorService = Executors.newFixedThreadPool( Math.min(handlers.size(), 100), new NamedThreadFactory("Dubbo-Invoker-Migrate")); List<Future<?>> migrationFutures = new ArrayList<>(handlers.size()); for (MigrationRuleHandler<?> handler : handlers.values()) { Future<?> future = executorService.submit(() -> handler.doMigrate(this.rule)); migrationFutures.add(future); } for (Future<?> future : migrationFutures) { try { future.get(); } catch (InterruptedException ie) { logger.warn( INTERNAL_ERROR, "unknown error in registry module", "", "Interrupted while waiting for migration async task to finish."); } catch (ExecutionException ee) { logger.error( INTERNAL_ERROR, "unknown error in registry module", "", "Migration async task failed.", ee.getCause()); } } } catch (Throwable t) { logger.error( INTERNAL_ERROR, "unknown error in registry module", "", "Error occurred when migration.", t); } finally { if (executorService != null) { executorService.shutdown(); } } } }); } } public void setRawRule(String rawRule) { this.rawRule = rawRule; this.rule = parseRule(this.rawRule); } private MigrationRule parseRule(String rawRule) { MigrationRule tmpRule = rule == null ? MigrationRule.getInitRule() : rule; if (INIT.equals(rawRule)) { tmpRule = MigrationRule.getInitRule(); } else { try { tmpRule = MigrationRule.parse(rawRule); } catch (Exception e) { logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Failed to parse migration rule...", e); } } return tmpRule; } @Override public void onExport(RegistryProtocol registryProtocol, Exporter<?> exporter) {} @Override public void onRefer( RegistryProtocol registryProtocol, ClusterInvoker<?> invoker, URL consumerUrl, URL registryURL) { MigrationRuleHandler<?> migrationRuleHandler = ConcurrentHashMapUtils.computeIfAbsent(handlers, (MigrationInvoker<?>) invoker, _key -> { ((MigrationInvoker<?>) invoker).setMigrationRuleListener(this); return new MigrationRuleHandler<>((MigrationInvoker<?>) invoker, consumerUrl); }); migrationRuleHandler.doMigrate(rule); } @Override public void onDestroy() { if (configuration != null) { configuration.removeListener(ruleKey, DUBBO_SERVICEDISCOVERY_MIGRATION, this); } if (ruleMigrationFuture != null) { ruleMigrationFuture.cancel(true); } if (localRuleMigrationFuture != null) { localRuleMigrationFuture.cancel(true); } ruleManageExecutor.shutdown(); ruleQueue.clear(); } public Map<MigrationInvoker<?>, MigrationRuleHandler<?>> getHandlers() { return handlers; } protected void removeMigrationInvoker(MigrationInvoker<?> migrationInvoker) { handlers.remove(migrationInvoker); } public MigrationRule getRule() { return rule; } }
MigrationRuleListener
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/boot/model/DiscriminatorPersistentEntity.java
{ "start": 684, "end": 2594 }
class ____ extends SubclassPersistentEntity implements JoinAwarePersistentEntity { private final List<Join> joins; private final List<Attribute> attributes; private String discriminatorValue; public DiscriminatorPersistentEntity(AuditTableData auditTableData, PersistentClass persistentClass) { super( auditTableData, persistentClass ); this.attributes = new ArrayList<>(); this.joins = new ArrayList<>(); } @Override public void addAttribute(Attribute attribute) { attributes.add( attribute ); } @Override public boolean isJoinAware() { return true; } public String getDiscriminatorValue() { return discriminatorValue; } public void setDiscriminatorValue(String discriminatorValue) { this.discriminatorValue = discriminatorValue; } @Override public List<Join> getJoins() { return Collections.unmodifiableList( joins ); } @Override public void addJoin(Join join) { this.joins.add( join ); } @Override public void build(JaxbHbmHibernateMapping mapping) { mapping.getSubclass().add( buildJaxbMapping() ); } public JaxbHbmDiscriminatorSubclassEntityType buildJaxbMapping() { final JaxbHbmDiscriminatorSubclassEntityType entity = new JaxbHbmDiscriminatorSubclassEntityType(); entity.setExtends( getExtends() ); // Set common stuff if ( getPersistentClass() != null ) { entity.setAbstract( getPersistentClass().isAbstract() ); } if ( !StringTools.isEmpty( getAuditTableData().getAuditEntityName() ) ) { entity.setEntityName( getAuditTableData().getAuditEntityName() ); } // Initialize attributes for ( Attribute attribute : attributes ) { entity.getAttributes().add( attribute.build() ); } if ( !StringTools.isEmpty( discriminatorValue ) ) { entity.setDiscriminatorValue( discriminatorValue ); } for ( Join join : joins ) { entity.getJoin().add( join.build() ); } return entity; } }
DiscriminatorPersistentEntity
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/TestOfflineImageViewerForErasureCodingPolicy.java
{ "start": 1800, "end": 6246 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(TestOfflineImageViewerForErasureCodingPolicy.class); private static File originalFsimage = null; private static File tempDir; /** * Create a populated namespace for later testing. Save its contents to a * data structure and store its fsimage location. */ @BeforeAll public static void createOriginalFSImage() throws IOException { MiniDFSCluster cluster = null; try { Configuration conf = new Configuration(); conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_ACLS_ENABLED_KEY, true); conf.setBoolean(DFSConfigKeys.DFS_STORAGE_POLICY_ENABLED_KEY, true); File[] nnDirs = MiniDFSCluster.getNameNodeDirectory( MiniDFSCluster.getBaseDirectory(), 0, 0); tempDir = nnDirs[0]; cluster = new MiniDFSCluster.Builder(conf).numDataNodes(10).build(); cluster.waitActive(); DistributedFileSystem hdfs = cluster.getFileSystem(); hdfs.enableErasureCodingPolicy("RS-6-3-1024k"); hdfs.enableErasureCodingPolicy("RS-3-2-1024k"); Path dir = new Path("/dir_wo_ec_rs63"); hdfs.mkdirs(dir); hdfs.setErasureCodingPolicy(dir, "RS-6-3-1024k"); dir = new Path("/dir_wo_ec_rs63/sub_dir_1"); hdfs.mkdirs(dir); dir = new Path("/dir_wo_ec_rs63/sub_dir_2"); hdfs.mkdirs(dir); Path file = new Path("/dir_wo_ec_rs63/file_wo_ec_1"); try (FSDataOutputStream o = hdfs.create(file)) { o.write(123); } file = new Path("/dir_wo_ec_rs63/file_wo_ec_2"); try (FSDataOutputStream o = hdfs.create(file)) { o.write(123); } dir = new Path("/dir_wo_ec_rs32"); hdfs.mkdirs(dir); hdfs.setErasureCodingPolicy(dir, "RS-3-2-1024k"); dir = new Path("/dir_wo_ec_rs32/sub_dir_1"); hdfs.mkdirs(dir); file = new Path("/dir_wo_ec_rs32/file_wo_ec"); try (FSDataOutputStream o = hdfs.create(file)) { o.write(123); } dir = new Path("/dir_wo_rep"); hdfs.mkdirs(dir); dir = new Path("/dir_wo_rep/sub_dir_1"); hdfs.mkdirs(dir); file = new Path("/dir_wo_rep/file_rep"); try (FSDataOutputStream o = hdfs.create(file)) { o.write(123); } // Write results to the fsimage file hdfs.setSafeMode(SafeModeAction.ENTER, false); hdfs.saveNamespace(); // Determine the location of the fsimage file originalFsimage = FSImageTestUtil.findLatestImageFile(FSImageTestUtil .getFSImage(cluster.getNameNode()).getStorage().getStorageDir(0)); if (originalFsimage == null) { throw new RuntimeException("Didn't generate or can't find fsimage"); } LOG.debug("original FS image file is " + originalFsimage); } finally { if (cluster != null) { cluster.shutdown(); } } } @AfterAll public static void deleteOriginalFSImage() throws IOException { if (originalFsimage != null && originalFsimage.exists()) { originalFsimage.delete(); } } @Test public void testPBDelimitedWriterForErasureCodingPolicy() throws Exception { String expected = DFSTestUtil.readResoucePlainFile( "testErasureCodingPolicy.csv"); String result = readECPolicyFromFsimageFile(); assertEquals(expected, result); } private String readECPolicyFromFsimageFile() throws Exception { StringBuilder builder = new StringBuilder(); String delemiter = "\t"; File delimitedOutput = new File(tempDir, "delimitedOutput"); if (OfflineImageViewerPB.run(new String[] {"-p", "Delimited", "-i", originalFsimage.getAbsolutePath(), "-o", delimitedOutput.getAbsolutePath(), "-ec"}) != 0) { throw new IOException("oiv returned failure creating " + "delimited output with ec."); } try (InputStream input = new FileInputStream(delimitedOutput); BufferedReader reader = new BufferedReader(new InputStreamReader(input))) { String line; boolean header = true; while ((line = reader.readLine()) != null) { String[] fields = line.split(delemiter); if (!header) { String path = fields[0]; String ecPolicy = fields[12]; builder.append(path).append(",").append(ecPolicy).append("\n"); } header = false; } } return builder.toString(); } }
TestOfflineImageViewerForErasureCodingPolicy
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/AppendersPlugin.java
{ "start": 1331, "end": 1920 }
class ____ { private AppendersPlugin() {} /** * Creates a Map of the Appenders. * @param appenders An array of Appenders. * @return The Appender Map. */ @PluginFactory public static ConcurrentMap<String, Appender> createAppenders( @PluginElement("Appenders") final Appender[] appenders) { final ConcurrentMap<String, Appender> map = new ConcurrentHashMap<>(appenders.length); for (final Appender appender : appenders) { map.put(appender.getName(), appender); } return map; } }
AppendersPlugin
java
redisson__redisson
redisson-spring-data/redisson-spring-data-20/src/main/java/org/redisson/spring/data/connection/RedissonReactiveGeoCommands.java
{ "start": 1982, "end": 10949 }
class ____ extends RedissonBaseReactive implements ReactiveGeoCommands { RedissonReactiveGeoCommands(CommandReactiveExecutor executorService) { super(executorService); } @Override public Flux<NumericResponse<GeoAddCommand, Long>> geoAdd(Publisher<GeoAddCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getGeoLocations(), "Locations must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); List<Object> args = new ArrayList<Object>(); args.add(keyBuf); for (GeoLocation<ByteBuffer> location : command.getGeoLocations()) { args.add(location.getPoint().getX()); args.add(location.getPoint().getY()); args.add(toByteArray(location.getName())); } Mono<Long> m = write(keyBuf, StringCodec.INSTANCE, RedisCommands.GEOADD, args.toArray()); return m.map(v -> new NumericResponse<>(command, v)); }); } @Override public Flux<CommandResponse<GeoDistCommand, Distance>> geoDist(Publisher<GeoDistCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getFrom(), "From member must not be null!"); Assert.notNull(command.getTo(), "To member must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); byte[] fromBuf = toByteArray(command.getFrom()); byte[] toBuf = toByteArray(command.getTo()); Metric metric = RedisGeoCommands.DistanceUnit.METERS; if (command.getMetric().isPresent()) { metric = command.getMetric().get(); } Mono<Distance> m = write(keyBuf, DoubleCodec.INSTANCE, new RedisCommand<Distance>("GEODIST", new DistanceConvertor(metric)), keyBuf, fromBuf, toBuf, metric.getAbbreviation()); return m.map(v -> new CommandResponse<>(command, v)); }); } private static final RedisCommand<List<Object>> GEOHASH = new RedisCommand<List<Object>>("GEOHASH", new ObjectListReplayDecoder<Object>()); @Override public Flux<MultiValueResponse<GeoHashCommand, String>> geoHash(Publisher<GeoHashCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getMembers(), "Members must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); List<Object> args = new ArrayList<Object>(command.getMembers().size() + 1); args.add(keyBuf); args.addAll(command.getMembers().stream().map(buf -> toByteArray(buf)).collect(Collectors.toList())); Mono<List<String>> m = read(keyBuf, StringCodec.INSTANCE, GEOHASH, args.toArray()); return m.map(v -> new MultiValueResponse<>(command, v)); }); } private final MultiDecoder<Map<Object, Object>> geoDecoder = new ListMultiDecoder2(new ObjectListReplayDecoder2(), new PointDecoder()); @Override public Flux<MultiValueResponse<GeoPosCommand, Point>> geoPos(Publisher<GeoPosCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getMembers(), "Members must not be null!"); RedisCommand<Map<Object, Object>> cmd = new RedisCommand<Map<Object, Object>>("GEOPOS", geoDecoder); byte[] keyBuf = toByteArray(command.getKey()); List<Object> args = new ArrayList<Object>(command.getMembers().size() + 1); args.add(keyBuf); args.addAll(command.getMembers().stream().map(buf -> toByteArray(buf)).collect(Collectors.toList())); Mono<List<Point>> m = read(keyBuf, StringCodec.INSTANCE, cmd, args.toArray()); return m.map(v -> new MultiValueResponse<>(command, v)); }); } private final MultiDecoder<GeoResults<GeoLocation<byte[]>>> postitionDecoder = new ListMultiDecoder2(new GeoResultsDecoder(), new CodecDecoder(), new PointDecoder(), new ObjectListReplayDecoder()); @Override public Flux<CommandResponse<GeoRadiusCommand, Flux<GeoResult<GeoLocation<ByteBuffer>>>>> geoRadius( Publisher<GeoRadiusCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getPoint(), "Point must not be null!"); Assert.notNull(command.getDistance(), "Distance must not be null!"); GeoRadiusCommandArgs args = command.getArgs().orElse(GeoRadiusCommandArgs.newGeoRadiusArgs()); byte[] keyBuf = toByteArray(command.getKey()); List<Object> params = new ArrayList<Object>(); params.add(keyBuf); params.add(BigDecimal.valueOf(command.getPoint().getX()).toPlainString()); params.add(BigDecimal.valueOf(command.getPoint().getY()).toPlainString()); params.add(command.getDistance().getValue()); params.add(command.getDistance().getMetric().getAbbreviation()); RedisCommand<GeoResults<GeoLocation<byte[]>>> cmd; if (args.getFlags().contains(GeoRadiusCommandArgs.Flag.WITHCOORD)) { cmd = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUS_RO", postitionDecoder); params.add("WITHCOORD"); } else { MultiDecoder<GeoResults<GeoLocation<byte[]>>> distanceDecoder = new ListMultiDecoder2(new ByteBufferGeoResultsDecoder(command.getDistance().getMetric()), new GeoDistanceDecoder()); cmd = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUS_RO", distanceDecoder); params.add("WITHDIST"); } if (args.getLimit() != null) { params.add("COUNT"); params.add(args.getLimit()); } if (args.getSortDirection() != null) { params.add(args.getSortDirection().name()); } Mono<GeoResults<GeoLocation<ByteBuffer>>> m = read(keyBuf, ByteArrayCodec.INSTANCE, cmd, params.toArray()); return m.map(v -> new CommandResponse<>(command, Flux.fromIterable(v.getContent()))); }); } @Override public Flux<CommandResponse<GeoRadiusByMemberCommand, Flux<GeoResult<GeoLocation<ByteBuffer>>>>> geoRadiusByMember( Publisher<GeoRadiusByMemberCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getMember(), "Member must not be null!"); Assert.notNull(command.getDistance(), "Distance must not be null!"); GeoRadiusCommandArgs args = command.getArgs().orElse(GeoRadiusCommandArgs.newGeoRadiusArgs()); byte[] keyBuf = toByteArray(command.getKey()); byte[] memberBuf = toByteArray(command.getMember()); List<Object> params = new ArrayList<Object>(); params.add(keyBuf); params.add(memberBuf); params.add(command.getDistance().getValue()); params.add(command.getDistance().getMetric().getAbbreviation()); RedisCommand<GeoResults<GeoLocation<byte[]>>> cmd; if (args.getFlags().contains(GeoRadiusCommandArgs.Flag.WITHCOORD)) { cmd = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUSBYMEMBER_RO", postitionDecoder); params.add("WITHCOORD"); } else { MultiDecoder<GeoResults<GeoLocation<byte[]>>> distanceDecoder = new ListMultiDecoder2(new ByteBufferGeoResultsDecoder(command.getDistance().getMetric()), new GeoDistanceDecoder()); cmd = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUSBYMEMBER_RO", distanceDecoder); params.add("WITHDIST"); } if (args.getLimit() != null) { params.add("COUNT"); params.add(args.getLimit()); } if (args.getSortDirection() != null) { params.add(args.getSortDirection().name()); } Mono<GeoResults<GeoLocation<ByteBuffer>>> m = read(keyBuf, ByteArrayCodec.INSTANCE, cmd, params.toArray()); return m.map(v -> new CommandResponse<>(command, Flux.fromIterable(v.getContent()))); }); } }
RedissonReactiveGeoCommands
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/internal/log/ConnectionInfoLogger.java
{ "start": 4383, "end": 4644 }
class ____", id = 10001022) void noConnectionCreatorFactoryClassSpecified(); @LogMessage(level = ERROR) @Message(value = "Connection leak detected: there are %s unclosed connections", id = 10001023) void connectionLeakDetected(int allocationCount); }
specified
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RHyperLogLogRx.java
{ "start": 976, "end": 2336 }
interface ____<V> extends RExpirableRx { /** * Adds element into this structure. * * @param obj - element to add * @return <code>true</code> if object has been added * or <code>false</code> if it was already added */ Single<Boolean> add(V obj); /** * Adds all elements contained in <code>objects</code> collection into this structure * * @param objects - elements to add * @return <code>true</code> if at least one object has been added * or <code>false</code> if all were already added */ Single<Boolean> addAll(Collection<V> objects); /** * Returns approximated number of unique elements added into this structure. * * @return approximated number of unique elements added into this structure */ Single<Long> count(); /** * Returns approximated number of unique elements * added into this instances and other instances defined through <code>otherLogNames</code>. * * @param otherLogNames - name of instances * @return number */ Single<Long> countWith(String... otherLogNames); /** * Merges multiple instances into this instance. * * @param otherLogNames - name of instances * @return void */ Completable mergeWith(String... otherLogNames); }
RHyperLogLogRx
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/cfg/PersistenceSettings.java
{ "start": 4409, "end": 4815 }
class ____ implements {@code Scanner}. * </ul> * * @see org.hibernate.boot.MetadataBuilder#applyScanner */ String SCANNER = "hibernate.archive.scanner"; /** * Specifies an {@link org.hibernate.boot.archive.spi.ArchiveDescriptorFactory} to use * in the scanning process, either: * <ul> * <li>an instance of {@code ArchiveDescriptorFactory}, * <li>a {@link Class} representing a
that
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithTryCatchTest.java
{ "start": 1187, "end": 2510 }
class ____ extends ContextTestSupport { @Test public void testTryCatch() throws Exception { AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { weaveById("foo").replace().process(new Processor() { @Override public void process(Exchange exchange) throws Exception { throw new IllegalArgumentException("Kaboom"); } }); } }); getMockEndpoint("mock:before").expectedMessageCount(1); getMockEndpoint("mock:after").expectedMessageCount(1); getMockEndpoint("mock:error").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").to("mock:before").doTry().to("mock:foo").id("foo").doCatch(Exception.class) .to("mock:error").end().to("mock:after"); } }; } }
AdviceWithTryCatchTest
java
google__guava
android/guava/src/com/google/common/escape/CharEscaperBuilder.java
{ "start": 1544, "end": 4027 }
class ____ extends CharEscaper { private final char[] @Nullable [] replacements; private final int replaceLength; CharArrayDecorator(char[] @Nullable [] replacements) { this.replacements = replacements; this.replaceLength = replacements.length; } /* * Overriding escape method to be slightly faster for this decorator. We test the replacements * array directly, saving a method call. */ @Override public String escape(String s) { int slen = s.length(); for (int index = 0; index < slen; index++) { char c = s.charAt(index); if (c < replacements.length && replacements[c] != null) { return escapeSlow(s, index); } } return s; } @Override protected char @Nullable [] escape(char c) { return c < replaceLength ? replacements[c] : null; } } // Replacement mappings. private final Map<Character, String> map; // The highest index we've seen so far. private int max = -1; /** Construct a new sparse array builder. */ public CharEscaperBuilder() { this.map = new HashMap<>(); } /** Add a new mapping from an index to an object to the escaping. */ @CanIgnoreReturnValue public CharEscaperBuilder addEscape(char c, String r) { map.put(c, checkNotNull(r)); if (c > max) { max = c; } return this; } /** Add multiple mappings at once for a particular index. */ @CanIgnoreReturnValue public CharEscaperBuilder addEscapes(char[] cs, String r) { checkNotNull(r); for (char c : cs) { addEscape(c, r); } return this; } /** * Convert this builder into an array of char[]s where the maximum index is the value of the * highest character that has been seen. The array will be sparse in the sense that any unseen * index will default to null. * * @return a "sparse" array that holds the replacement mappings. */ public char[] @Nullable [] toArray() { char[][] result = new char[max + 1][]; for (Entry<Character, String> entry : map.entrySet()) { result[entry.getKey()] = entry.getValue().toCharArray(); } return result; } /** * Convert this builder into a char escaper which is just a decorator around the underlying array * of replacement char[]s. * * @return an escaper that escapes based on the underlying array. */ public Escaper toEscaper() { return new CharArrayDecorator(toArray()); } }
CharArrayDecorator
java
quarkusio__quarkus
extensions/panache/hibernate-orm-panache-common/runtime/src/main/java/io/quarkus/hibernate/orm/panache/common/runtime/CommonPanacheQueryImpl.java
{ "start": 1094, "end": 1342 }
class ____<Entity> { /* * We use this complex caching mechanism to avoid recalculating projection queries * for recurring classes. In theory this gets stored in the Class object itself so * it is GCed when the
CommonPanacheQueryImpl
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlBaseParser.java
{ "start": 267957, "end": 270717 }
class ____ extends ParserRuleContext { public TerminalNode EQ() { return getToken(SqlBaseParser.EQ, 0); } public TerminalNode NULLEQ() { return getToken(SqlBaseParser.NULLEQ, 0); } public TerminalNode NEQ() { return getToken(SqlBaseParser.NEQ, 0); } public TerminalNode LT() { return getToken(SqlBaseParser.LT, 0); } public TerminalNode LTE() { return getToken(SqlBaseParser.LTE, 0); } public TerminalNode GT() { return getToken(SqlBaseParser.GT, 0); } public TerminalNode GTE() { return getToken(SqlBaseParser.GTE, 0); } public ComparisonOperatorContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_comparisonOperator; } @Override public void enterRule(ParseTreeListener listener) { if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).enterComparisonOperator(this); } @Override public void exitRule(ParseTreeListener listener) { if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).exitComparisonOperator(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if (visitor instanceof SqlBaseVisitor) return ((SqlBaseVisitor<? extends T>) visitor).visitComparisonOperator(this); else return visitor.visitChildren(this); } } public final ComparisonOperatorContext comparisonOperator() throws RecognitionException { ComparisonOperatorContext _localctx = new ComparisonOperatorContext(_ctx, getState()); enterRule(_localctx, 92, RULE_comparisonOperator); int _la; try { enterOuterAlt(_localctx, 1); { setState(797); _la = _input.LA(1); if (!(((((_la - 112)) & ~0x3f) == 0 && ((1L << (_la - 112)) & 127L) != 0))) { _errHandler.recoverInline(this); } else { if (_input.LA(1) == Token.EOF) matchedEOF = true; _errHandler.reportMatch(this); consume(); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } @SuppressWarnings("CheckReturnValue") public static
ComparisonOperatorContext
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_isSortedAccordingToComparator_Test.java
{ "start": 1062, "end": 1523 }
class ____ extends ObjectArrayAssertBaseTest { private Comparator<Object> comparator = alwaysEqual(); @Override protected ObjectArrayAssert<Object> invoke_api_method() { return assertions.isSortedAccordingTo(comparator); } @Override protected void verify_internal_effects() { verify(arrays).assertIsSortedAccordingToComparator(getInfo(assertions), getActual(assertions), comparator); } }
ObjectArrayAssert_isSortedAccordingToComparator_Test
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/optimizer/rules/logical/ReplaceAliasingEvalWithProjectTests.java
{ "start": 1249, "end": 22176 }
class ____ extends AbstractLogicalPlanOptimizerTests { /** * <pre>{@code * EsqlProject[[emp_no{f}#18, salary{f}#23, emp_no{f}#18 AS emp_no2#7, salary2{r}#10, emp_no{f}#18 AS emp_no3#13, salary3{r}#16]] * \_Eval[[salary{f}#23 * 2[INTEGER] AS salary2#10, salary2{r}#10 * 3[INTEGER] AS salary3#16]] * \_Limit[1000[INTEGER],false,false] * \_EsRelation[test][_meta_field{f}#24, emp_no{f}#18, first_name{f}#19, ..] * }</pre> */ public void testSimple() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(randomFrom(""" FROM test | KEEP emp_no, salary | EVAL emp_no2 = emp_no, salary2 = 2*salary, emp_no3 = emp_no2, salary3 = 3*salary2 | KEEP * """, """ FROM test | KEEP emp_no, salary | EVAL emp_no2 = emp_no, salary2 = 2*salary | EVAL emp_no3 = emp_no2, salary3 = 3*salary2 | KEEP * """)); var project = as(plan, Project.class); var eval = as(project.child(), Eval.class); var empNo = findFieldAttribute(plan, "emp_no"); var salary = findFieldAttribute(plan, "salary"); var salary2 = alias("salary2", mul(salary, of(2))); var salary3 = alias("salary3", mul(salary2.toAttribute(), of(3))); List<Expression> expectedEvalFields = new ArrayList<>(); expectedEvalFields.add(salary2); expectedEvalFields.add(salary3); assertEqualsIgnoringIds(expectedEvalFields, eval.fields()); List<Expression> expectedProjections = new ArrayList<>(); expectedProjections.add(empNo); expectedProjections.add(salary); expectedProjections.add(alias("emp_no2", empNo)); expectedProjections.add(salary2.toAttribute()); expectedProjections.add(alias("emp_no3", empNo)); expectedProjections.add(salary3.toAttribute()); assertEqualsIgnoringIds(expectedProjections, project.projections()); } /** * <pre>{@code * EsqlProject[[emp_no{f}#19, salary{f}#35, emp_no{f}#19 AS emp_no2#8, salary2{r}#11, emp_no{f}#19 AS emp_no3#14, salary3{r}#17]] * \_Eval[[salary{f}#35 * 2[INTEGER] AS salary2#11, salary2{r}#11 * 3[INTEGER] AS salary3#17]] * \_Limit[1000[INTEGER],true,false] * \_Join[LEFT,[emp_no{f}#19],[emp_no{f}#30],null] * |_Limit[1000[INTEGER],false,false] * | \_EsRelation[test][_meta_field{f}#25, emp_no{f}#19, first_name{f}#20, ..] * \_EsRelation[test_lookup][LOOKUP][emp_no{f}#30, salary{f}#35] * }</pre> */ public void testSimpleFieldFromLookup() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(""" FROM test | LOOKUP JOIN test_lookup ON emp_no | KEEP emp_no, salary | EVAL emp_no2 = emp_no, salary2 = 2*salary, emp_no3 = emp_no2, salary3 = 3*salary2 | KEEP * """); var project = as(plan, Project.class); var eval = as(project.child(), Eval.class); // the final emp_no is from the main index, the final salary from the lookup index var empNo = findFieldAttribute(plan, "emp_no", relation -> relation.indexMode() == IndexMode.STANDARD); var salary = findFieldAttribute(plan, "salary", relation -> relation.indexMode() == IndexMode.LOOKUP); var salary2 = alias("salary2", mul(salary, of(2))); var salary3 = alias("salary3", mul(salary2.toAttribute(), of(3))); List<Expression> expectedEvalFields = new ArrayList<>(); expectedEvalFields.add(salary2); expectedEvalFields.add(salary3); assertEqualsIgnoringIds(expectedEvalFields, eval.fields()); // assert using id to ensure we're pointing to the right salary assertEquals(eval.fields().get(0).child(), mul(salary, of(2))); List<Expression> expectedProjections = new ArrayList<>(); expectedProjections.add(empNo); expectedProjections.add(salary); expectedProjections.add(alias("emp_no2", empNo)); expectedProjections.add(salary2.toAttribute()); expectedProjections.add(alias("emp_no3", empNo)); expectedProjections.add(salary3.toAttribute()); assertEqualsIgnoringIds(expectedProjections, project.projections()); // assert using id to ensure we're pointing to the right emp_no and salary assertEquals(project.projections().get(0), empNo); assertEquals(project.projections().get(1), salary); } /** * <pre>{@code * EsqlProject[[emp_no{f}#24 AS emp_no2#7, salary{f}#29 AS salary2#10, emp_no{f}#24 AS emp_no3#13, emp_no{f}#24 AS salary#16, * salary{f}#29 AS salary3#19, salary{f}#29 AS emp_no#22]] * \_Limit[1000[INTEGER],false,false] * \_EsRelation[test][_meta_field{f}#30, emp_no{f}#24, first_name{f}#25, ..] * }</pre> */ public void testOnlyAliases() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(""" from test | KEEP emp_no, salary | EVAL emp_no2 = emp_no, salary2 = salary, emp_no3 = emp_no2, salary = emp_no3, salary3 = salary2, emp_no = salary3 | KEEP * """); var project = as(plan, Project.class); var limit = as(project.child(), Limit.class); var empNo = findFieldAttribute(plan, "emp_no"); var salary = findFieldAttribute(plan, "salary"); List<Expression> expectedProjections = new ArrayList<>(); expectedProjections.add(alias("emp_no2", empNo)); expectedProjections.add(alias("salary2", salary)); expectedProjections.add(alias("emp_no3", empNo)); expectedProjections.add(alias("salary", empNo)); expectedProjections.add(alias("salary3", salary)); expectedProjections.add(alias("emp_no", salary)); assertEqualsIgnoringIds(expectedProjections, project.projections()); } /** * <pre>{@code * EsqlProject[[emp_no{f}#26 AS b#21, emp_no{f}#26 AS a#24]] * \_Limit[1000[INTEGER],false,false] * \_EsRelation[test][_meta_field{f}#32, emp_no{f}#26, first_name{f}#27, ..] * }</pre> */ public void testAliasLoopTwoVars() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(""" from test | KEEP emp_no | RENAME emp_no AS a | EVAL b = a, a = b, b = a, a = b, b = a, a = b | KEEP * """); var project = as(plan, Project.class); var limit = as(project.child(), Limit.class); var empNo = findFieldAttribute(plan, "emp_no"); List<Expression> expectedProjections = new ArrayList<>(); expectedProjections.add(alias("b", empNo)); expectedProjections.add(alias("a", empNo)); assertEqualsIgnoringIds(expectedProjections, project.projections()); } /** * <pre>{@code * EsqlProject[[emp_no{f}#17 AS b#9, emp_no{f}#17 AS c#12, emp_no{f}#17 AS a#15]] * \_Limit[1000[INTEGER],false,false] * \_EsRelation[test][_meta_field{f}#23, emp_no{f}#17, first_name{f}#18, ..] * }</pre> */ public void testAliasLoopThreeVars() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(""" from test | KEEP emp_no | RENAME emp_no AS a | EVAL b = a, c = b, a = c | KEEP * """); var project = as(plan, Project.class); var limit = as(project.child(), Limit.class); var empNo = findFieldAttribute(plan, "emp_no"); List<Expression> expectedProjections = new ArrayList<>(); expectedProjections.add(alias("b", empNo)); expectedProjections.add(alias("c", empNo)); expectedProjections.add(alias("a", empNo)); assertEqualsIgnoringIds(expectedProjections, project.projections()); } /** * <pre>{@code * EsqlProject[[salary{f}#23, emp_no{f}#18 AS emp_no2#7, $$emp_no$temp_name$29{r}#30 AS emp_no#10, * emp_no{f}#18 AS emp_no3#13, salary3{r}#16]] * \_Eval[[salary{f}#23 * 2[INTEGER] AS $$emp_no$temp_name$29#30, $$emp_no$temp_name$29{r$}#30 * 2[INTEGER] AS salary3#16]] * \_Limit[1000[INTEGER],false,false] * \_EsRelation[test][_meta_field{f}#24, emp_no{f}#18, first_name{f}#19, ..] * }</pre> */ public void testNonAliasShadowingAliasedAttribute() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(randomFrom(""" from test | KEEP emp_no, salary | EVAL emp_no2 = emp_no, emp_no = 2*salary, emp_no3 = emp_no2, salary3 = 2*emp_no | KEEP * """)); var project = as(plan, Project.class); var eval = as(project.child(), Eval.class); var empNo = findFieldAttribute(plan, "emp_no"); var salary = findFieldAttribute(plan, "salary"); assertEquals(2, eval.fields().size()); var empNoTempName = eval.fields().get(0); assertThat(empNoTempName.name(), startsWith("$$emp_no$temp_name$")); assertEquals(mul(salary, of(2)), empNoTempName.child()); var salary3 = alias("salary3", mul(empNoTempName.toAttribute(), of(2))); assertEqualsIgnoringIds(salary3, eval.fields().get(1)); List<Expression> expectedProjections = new ArrayList<>(); expectedProjections.add(salary); expectedProjections.add(alias("emp_no2", empNo)); expectedProjections.add(alias("emp_no", empNoTempName.toAttribute())); expectedProjections.add(alias("emp_no3", empNo)); expectedProjections.add(salary3.toAttribute()); assertEqualsIgnoringIds(expectedProjections, project.projections()); } /** * <pre>{@code * Limit[1000[INTEGER],false,false] * \_Aggregate[[$$emp_no$temp_name$33{r$}#34, emp_no{f}#22, salary{f}#27, salary3{r}#16], * [$$emp_no$temp_name$33{r$}#34 AS emp_no#10, emp_no{f}#22 AS emp_no2#7, emp_no{f}#22 AS emp_no3#13, salary{f}#27, salary3{r}#16]] * \_Eval[[salary{f}#27 * 2[INTEGER] AS $$emp_no$temp_name$33#34, $$emp_no$temp_name$33{r$}#34 * 2[INTEGER] AS salary3#1 * 6]] * \_EsRelation[test][_meta_field{f}#28, emp_no{f}#22, first_name{f}#23, ..] * }</pre> */ public void testNonAliasShadowingAliasedAttributeWithAgg() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(randomFrom(""" from test | KEEP emp_no, salary | EVAL emp_no2 = emp_no, emp_no = 2*salary, emp_no3 = emp_no2, salary3 = 2*emp_no | STATS BY emp_no, emp_no2, emp_no3, salary, salary3 """)); var limit = as(plan, Limit.class); var agg = as(limit.child(), Aggregate.class); var eval = as(agg.child(), Eval.class); var empNo = findFieldAttribute(plan, "emp_no"); var salary = findFieldAttribute(plan, "salary"); assertEquals(2, eval.fields().size()); var empNoTempName = eval.fields().get(0); assertThat(empNoTempName.name(), startsWith("$$emp_no$temp_name$")); assertEquals(mul(salary, of(2)), empNoTempName.child()); var salary3 = alias("salary3", mul(empNoTempName.toAttribute(), of(2))); assertEqualsIgnoringIds(salary3, eval.fields().get(1)); List<Expression> expectedAggregates = new ArrayList<>(); expectedAggregates.add(alias("emp_no", empNoTempName.toAttribute())); expectedAggregates.add(alias("emp_no2", empNo)); expectedAggregates.add(alias("emp_no3", empNo)); expectedAggregates.add(salary); expectedAggregates.add(salary3.toAttribute()); assertEqualsIgnoringIds(expectedAggregates, agg.aggregates()); } /** * <pre>{@code * EsqlProject[[salary{f}#35, emp_no{f}#30 AS emp_no2#22, $$id$temp_name$41{r$}#42 AS emp_no#25, emp_no{f}#30 AS emp_no3#28, * salary3{r}#19]] * \_Eval[[salary{f}#35 * 2[INTEGER] AS $$id$temp_name$41#42, $$id$temp_name$41{r$}#42 * 2[INTEGER] AS salary3#19]] * \_Limit[1000[INTEGER],false,false] * \_EsRelation[test][_meta_field{f}#36, emp_no{f}#30, first_name{f}#31, ..] * }</pre> */ public void testNonAliasShadowingAliasedAttributeWithRename() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(randomFrom(""" from test | KEEP emp_no, salary | RENAME emp_no AS id | EVAL id2 = id, id = 2*salary, id3 = id2, salary3 = 2*id | RENAME id2 AS emp_no2, id AS emp_no, id3 AS emp_no3 | KEEP * """)); var project = as(plan, Project.class); var eval = as(project.child(), Eval.class); var empNo = findFieldAttribute(plan, "emp_no"); var salary = findFieldAttribute(plan, "salary"); assertEquals(2, eval.fields().size()); var idTempName = eval.fields().get(0); // The renaming to $$id$temp_name$ is not strictly necessary. If the eval pushdown past the first rename happened before the // alias extraction, the eval wouldn't shadow any input attributes anymore. assertThat(idTempName.name(), startsWith("$$id$temp_name$")); assertEquals(mul(salary, of(2)), idTempName.child()); var salary3 = alias("salary3", mul(idTempName.toAttribute(), of(2))); assertEqualsIgnoringIds(salary3, eval.fields().get(1)); List<Expression> expectedProjections = new ArrayList<>(); expectedProjections.add(salary); expectedProjections.add(alias("emp_no2", empNo)); expectedProjections.add(alias("emp_no", idTempName.toAttribute())); expectedProjections.add(alias("emp_no3", empNo)); expectedProjections.add(salary3.toAttribute()); assertEqualsIgnoringIds(expectedProjections, project.projections()); } /** * <pre>{@code * EsqlProject[[emp_no{f}#18, salary{f}#23, emp_no{f}#18 AS emp_no3#10, emp_no2{r}#13, salary3{r}#16]] * \_Eval[[salary{f}#23 * 2[INTEGER] AS emp_no2#13, emp_no2{r}#13 * 3[INTEGER] AS salary3#16]] * \_Limit[1000[INTEGER],false,false] * \_EsRelation[test][_meta_field{f}#24, emp_no{f}#18, first_name{f}#19, ..] * }</pre> */ public void testNonAliasShadowingAliasOfAliasedAttribute() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(""" from test | KEEP emp_no, salary | EVAL emp_no2 = emp_no, emp_no3 = emp_no2, emp_no2 = 2*salary, salary3 = 3*emp_no2 | KEEP * """); var project = as(plan, Project.class); var eval = as(project.child(), Eval.class); var empNo = findFieldAttribute(plan, "emp_no"); var salary = findFieldAttribute(plan, "salary"); var empNo2 = alias("emp_no2", mul(salary, of(2))); var salary3 = alias("salary3", mul(empNo2.toAttribute(), of(3))); assertEqualsIgnoringIds(List.of(empNo2, salary3), eval.fields()); List<Expression> expectedProjections = new ArrayList<>(); expectedProjections.add(empNo); expectedProjections.add(salary); expectedProjections.add(alias("emp_no3", empNo)); expectedProjections.add(empNo2.toAttribute()); expectedProjections.add(salary3.toAttribute()); assertEqualsIgnoringIds(expectedProjections, project.projections()); } /** * <pre>{@code * EsqlProject[[emp_no{f}#24, salary{f}#29, emp_no{f}#24 AS emp_no3#13, salary{f}#29 AS salary3#16, * salary{f}#29 AS emp_no2#19, emp_no{f}#24 AS salary2#22]] * \_Limit[1000[INTEGER],false,false] * \_EsRelation[test][_meta_field{f}#30, emp_no{f}#24, first_name{f}#25, ..] * }</pre> */ public void testAliasShadowingOtherAlias() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(""" from test | KEEP emp_no, salary | EVAL emp_no2 = emp_no, salary2 = salary, emp_no3 = emp_no2, salary3 = salary2, emp_no2 = salary, salary2 = emp_no | KEEP * """); var project = as(plan, Project.class); var empNo = findFieldAttribute(plan, "emp_no"); var salary = findFieldAttribute(plan, "salary"); List<Expression> expectedProjections = new ArrayList<>(); expectedProjections.add(empNo); expectedProjections.add(salary); expectedProjections.add(alias("emp_no3", empNo)); expectedProjections.add(alias("salary3", salary)); expectedProjections.add(alias("emp_no2", salary)); expectedProjections.add(alias("salary2", empNo)); assertEqualsIgnoringIds(expectedProjections, project.projections()); } /** * <pre>{@code * EsqlProject[[salary{f}#22, salary2{r}#6, salary2{r}#6 AS aliased_salary2#9, salary3{r}#12, salary2{r}#6 AS twice_aliased_salary2#15]] * \_Eval[[salary{f}#22 * 2[INTEGER] AS salary2#6, salary2{r}#6 * 3[INTEGER] AS salary3#12]] * \_Limit[1000[INTEGER],false,false] * \_EsRelation[test][_meta_field{f}#23, emp_no{f}#17, first_name{f}#18, ..] * }</pre> */ public void testAliasForNonAlias() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(""" from test | KEEP salary | EVAL salary2 = 2*salary, aliased_salary2 = salary2, salary3 = 3*salary2, twice_aliased_salary2 = aliased_salary2 | KEEP * """); var project = as(plan, Project.class); var eval = as(project.child(), Eval.class); var salary = findFieldAttribute(plan, "salary"); var salary2 = alias("salary2", mul(salary, of(2))); var salary3 = alias("salary3", mul(salary2.toAttribute(), of(3))); assertEqualsIgnoringIds(List.of(salary2, salary3), eval.fields()); List<Expression> expectedProjections = new ArrayList<>(); expectedProjections.add(salary); expectedProjections.add(salary2.toAttribute()); expectedProjections.add(alias("aliased_salary2", salary2.toAttribute())); expectedProjections.add(salary3.toAttribute()); expectedProjections.add(alias("twice_aliased_salary2", salary2.toAttribute())); assertEqualsIgnoringIds(expectedProjections, project.projections()); } /** * <pre>{@code * EsqlProject[[salary{f}#25, salary2{r}#6 AS aliased_salary2#9, $$salary2$temp_name$31{r$}#32 AS salary2#12, salary3{r}#15, * salary3{r}#15 AS salary4#18]] * \_Eval[[salary{f}#25 * 2[INTEGER] AS salary2#6, salary2{r}#6 * 3[INTEGER] AS $$salary2$temp_name$31#32, * $$salary2$temp_name$31{r$}#32 * 4[INTEGER] AS salary3#15]] * \_Limit[1000[INTEGER],false,false] * \_EsRelation[test][_meta_field{f}#26, emp_no{f}#20, first_name{f}#21, ..] * }</pre> */ public void testAliasForShadowedNonAlias() { // Rule only kicks in if there's a Project or Aggregate above, so we add a KEEP * var plan = plan(""" from test | KEEP salary | EVAL salary2 = 2*salary, aliased_salary2 = salary2, salary2 = 3*salary2, salary3 = 4*salary2, salary4 = salary3 | KEEP * """); var project = as(plan, Project.class); var eval = as(project.child(), Eval.class); var salary = findFieldAttribute(plan, "salary"); assertEquals(3, eval.fields().size()); var salary2 = alias("salary2", mul(salary, of(2))); assertEqualsIgnoringIds(salary2, eval.fields().get(0)); var salary2TempName = eval.fields().get(1); assertThat(salary2TempName.name(), startsWith("$$salary2$temp_name$")); assertEqualsIgnoringIds(mul(salary2.toAttribute(), of(3)), salary2TempName.child()); var salary3 = alias("salary3", mul(salary2TempName.toAttribute(), of(4))); assertEqualsIgnoringIds(salary3, eval.fields().get(2)); List<Expression> expectedProjections = new ArrayList<>(); expectedProjections.add(salary); expectedProjections.add(alias("aliased_salary2", salary2.toAttribute())); expectedProjections.add(alias("salary2", salary2TempName.toAttribute())); expectedProjections.add(salary3.toAttribute()); expectedProjections.add(alias("salary4", salary3.toAttribute())); assertEqualsIgnoringIds(expectedProjections, project.projections()); } }
ReplaceAliasingEvalWithProjectTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AlreadyCheckedTest.java
{ "start": 6986, "end": 7358 }
class ____ { public void test(boolean a, boolean b, boolean c) { if (!a || (b && c)) { } else if (b) { } } } """) .doTest(); } @Test public void notFinal_noFinding() { helper .addSourceLines( "Test.java", """
Test
java
alibaba__nacos
naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/OperatorControllerV2Test.java
{ "start": 1773, "end": 4024 }
class ____ { private OperatorControllerV2 operatorControllerV2; @Mock private SwitchDomain switchDomain; @Mock private SwitchManager switchManager; @Mock private ServerStatusManager serverStatusManager; @Mock private ClientManager clientManager; @Mock private Operator operatorV2Impl; @BeforeEach void setUp() { this.operatorControllerV2 = new OperatorControllerV2(operatorV2Impl); MockEnvironment environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); } @Test void testSwitches() { SwitchDomain switchDomain = new SwitchDomain(); switchDomain.setDefaultInstanceEphemeral(true); switchDomain.setDefaultPushCacheMillis(1000L); Mockito.when(operatorV2Impl.switches()).thenReturn(switchDomain); Result<SwitchDomain> result = operatorControllerV2.switches(); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals(1000L, result.getData().getDefaultPushCacheMillis()); assertEquals(true, result.getData().isDefaultInstanceEphemeral()); } @Test void testUpdateSwitches() { UpdateSwitchForm updateSwitchForm = new UpdateSwitchForm(); updateSwitchForm.setDebug(true); updateSwitchForm.setEntry("test"); updateSwitchForm.setValue("test"); try { Result<String> result = operatorControllerV2.updateSwitch(updateSwitchForm); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals("ok", result.getData()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test void testMetrics() { MetricsInfoVo metricsInfoVo = new MetricsInfoVo(); metricsInfoVo.setStatus(ServerStatus.UP.toString()); Mockito.when(operatorV2Impl.metrics(false)).thenReturn(metricsInfoVo); Result<MetricsInfoVo> result = operatorControllerV2.metrics(false); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals(ServerStatus.UP.toString(), result.getData().getStatus()); } }
OperatorControllerV2Test
java
google__guava
android/guava/src/com/google/common/collect/ImmutableSet.java
{ "start": 15249, "end": 17361 }
class ____ implements Serializable { final Object[] elements; SerializedForm(Object[] elements) { this.elements = elements; } Object readResolve() { return copyOf(elements); } @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0; } @Override @J2ktIncompatible Object writeReplace() { return new SerializedForm(toArray()); } @J2ktIncompatible private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } /** * Returns a new builder. The generated builder is equivalent to the builder created by the {@link * Builder} constructor. */ public static <E> Builder<E> builder() { return new Builder<>(); } /** * Returns a new builder, expecting the specified number of distinct elements to be added. * * <p>If {@code expectedSize} is exactly the number of distinct elements added to the builder * before {@link Builder#build} is called, the builder is likely to perform better than an unsized * {@link #builder()} would have. * * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to, * but not exactly, the number of distinct elements added to the builder. * * @since 23.1 */ public static <E> Builder<E> builderWithExpectedSize(int expectedSize) { checkNonnegative(expectedSize, "expectedSize"); return new Builder<>(expectedSize, true); } /** * A builder for creating {@code ImmutableSet} instances. Example: * * {@snippet : * static final ImmutableSet<Color> GOOGLE_COLORS = * ImmutableSet.<Color>builder() * .addAll(WEBSAFE_COLORS) * .add(new Color(0, 191, 255)) * .build(); * } * * <p>Elements appear in the resulting set in the same order they were first added to the builder. * * <p>Building does not change the state of the builder, so it is still possible to add more * elements and to build again. * * @since 2.0 */ public static
SerializedForm
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/UpdateMessageDigestInputStream.java
{ "start": 924, "end": 2092 }
class ____ extends InputStream { /** * Update the message digest with the rest of the bytes in this stream. * <p>Using this method is more optimized since it avoids creating new * byte arrays for each call. * @param messageDigest the message digest to update * @throws IOException when propagated from {@link #read()} */ public void updateMessageDigest(MessageDigest messageDigest) throws IOException { int data; while ((data = read()) != -1) { messageDigest.update((byte) data); } } /** * Update the message digest with the next len bytes in this stream. * <p>Using this method is more optimized since it avoids creating new * byte arrays for each call. * @param messageDigest the message digest to update * @param len how many bytes to read from this stream and use to update the message digest * @throws IOException when propagated from {@link #read()} */ public void updateMessageDigest(MessageDigest messageDigest, int len) throws IOException { int data; int bytesRead = 0; while (bytesRead < len && (data = read()) != -1) { messageDigest.update((byte) data); bytesRead++; } } }
UpdateMessageDigestInputStream
java
apache__camel
core/camel-util/src/test/java/org/apache/camel/util/CamelCaseOrderedPropertiesTest.java
{ "start": 997, "end": 3350 }
class ____ { @Test public void testOrdered() { Properties prop = new CamelCaseOrderedProperties(); prop.setProperty("hello-world", "Hi Camel"); prop.setProperty("camel.main.stream-caching-enabled", "true"); assertEquals(2, prop.size()); Iterator it = prop.keySet().iterator(); assertEquals("hello-world", it.next()); assertEquals("camel.main.stream-caching-enabled", it.next()); it = prop.values().iterator(); assertEquals("Hi Camel", it.next()); assertEquals("true", it.next()); assertEquals("Hi Camel", prop.getProperty("hello-world")); assertEquals("Hi Camel", prop.getProperty("helloWorld")); assertEquals("true", prop.getProperty("camel.main.stream-caching-enabled")); assertEquals("true", prop.getProperty("camel.main.streamCachingEnabled")); assertEquals("Davs", prop.getProperty("bye-world", "Davs")); } @Test public void testOrderedLoad() throws Exception { Properties prop = new CamelCaseOrderedProperties(); prop.load(CamelCaseOrderedPropertiesTest.class.getResourceAsStream("/application.properties")); assertEquals(4, prop.size()); Iterator it = prop.keySet().iterator(); assertEquals("hello", it.next()); assertEquals("camel.component.seda.concurrent-consumers", it.next()); assertEquals("camel.component.seda.queueSize", it.next()); assertEquals("camel.component.direct.timeout", it.next()); // should be ordered values it = prop.values().iterator(); assertEquals("World", it.next()); assertEquals("2", it.next()); assertEquals("500", it.next()); assertEquals("1234", it.next()); assertEquals("World", prop.getProperty("hello", "MyDefault")); assertEquals("2", prop.getProperty("camel.component.seda.concurrent-consumers", "MyDefault")); assertEquals("2", prop.getProperty("camel.component.seda.concurrentConsumers", "MyDefault")); assertEquals("500", prop.getProperty("camel.component.seda.queue-size", "MyDefault")); assertEquals("500", prop.getProperty("camel.component.seda.queueSize", "MyDefault")); assertEquals("1234", prop.getProperty("camel.component.direct.timeout", "MyDefault")); } }
CamelCaseOrderedPropertiesTest
java
google__guice
extensions/grapher/src/com/google/inject/grapher/BindingEdge.java
{ "start": 1029, "end": 1115 }
class ____ the binding's same type. */ NORMAL, /** Binding is to an instance or
of
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/HistogramAggregatorSupplier.java
{ "start": 987, "end": 1521 }
interface ____ { Aggregator build( String name, AggregatorFactories factories, double interval, double offset, BucketOrder order, boolean keyed, long minDocCount, DoubleBounds extendedBounds, DoubleBounds hardBounds, ValuesSourceConfig valuesSourceConfig, AggregationContext context, Aggregator parent, CardinalityUpperBound cardinality, Map<String, Object> metadata ) throws IOException; }
HistogramAggregatorSupplier
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/AvgFunction.java
{ "start": 2201, "end": 5467 }
class ____ extends AbstractSqmSelfRenderingFunctionDescriptor { private final SqlAstNodeRenderingMode defaultArgumentRenderingMode; private final CastFunction castFunction; private final BasicType<Double> doubleType; public AvgFunction( Dialect dialect, TypeConfiguration typeConfiguration, SqlAstNodeRenderingMode defaultArgumentRenderingMode) { super( "avg", FunctionKind.AGGREGATE, new Validator(), new ReturnTypeResolver( typeConfiguration ), StandardFunctionArgumentTypeResolvers.invariant( typeConfiguration, NUMERIC ) ); this.defaultArgumentRenderingMode = defaultArgumentRenderingMode; doubleType = typeConfiguration.getBasicTypeRegistry().resolve( StandardBasicTypes.DOUBLE ); //This is kinda wrong, we're supposed to use findFunctionDescriptor("cast"), not instantiate CastFunction //However, since no Dialects currently override the cast() function, it's OK for now castFunction = new CastFunction( dialect, dialect.getPreferredSqlTypeCodeForBoolean() ); } @Override public void render( SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, ReturnableType<?> returnType, SqlAstTranslator<?> walker) { render( sqlAppender, sqlAstArguments, null, returnType, walker ); } @Override public void render( SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, Predicate filter, ReturnableType<?> returnType, SqlAstTranslator<?> translator) { final boolean caseWrapper = filter != null && !filterClauseSupported( translator ); sqlAppender.appendSql( "avg(" ); final Expression arg; final var argNode = sqlAstArguments.get( 0 ); if ( argNode instanceof Distinct distinct ) { sqlAppender.appendSql( "distinct " ); arg = distinct.getExpression(); } else if ( argNode instanceof Expression expression ) { arg = expression; } else { throw new AssertionFailure( "Unexpected argument type" ); } if ( caseWrapper ) { translator.getCurrentClauseStack().push( Clause.WHERE ); sqlAppender.appendSql( "case when " ); filter.accept( translator ); translator.getCurrentClauseStack().pop(); sqlAppender.appendSql( " then " ); renderArgument( sqlAppender, translator, arg ); sqlAppender.appendSql( " else null end)" ); } else { renderArgument( sqlAppender, translator, arg ); sqlAppender.appendSql( ')' ); if ( filter != null ) { translator.getCurrentClauseStack().push( Clause.WHERE ); sqlAppender.appendSql( " filter (where " ); filter.accept( translator ); sqlAppender.appendSql( ')' ); translator.getCurrentClauseStack().pop(); } } } private void renderArgument(SqlAppender sqlAppender, SqlAstTranslator<?> translator, Expression realArg) { final JdbcMapping sourceMapping = realArg.getExpressionType().getSingleJdbcMapping(); // Only cast to float/double if this is an integer if ( sourceMapping.getJdbcType().isInteger() ) { castFunction.render( sqlAppender, asList( realArg, new CastTarget( doubleType ) ), doubleType, translator ); } else { translator.render( realArg, defaultArgumentRenderingMode ); } } @Override public String getArgumentListSignature() { return "(NUMERIC arg)"; } public static
AvgFunction
java
quarkusio__quarkus
extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/UniTest.java
{ "start": 2597, "end": 4543 }
class ____ { @Query public Uni<Book> getBook(String name) { return Uni.createFrom().item(() -> BOOKS.get(name)); } public Uni<String> getBuyLink(@Source Book book) { String title = book.title.replaceAll(" ", "+"); return Uni.createFrom().item(() -> String.format(AMAZON_SEARCH_FORMAT, title)); } public Uni<List<List<Author>>> getAsyncAuthors(@Source List<Book> books) { List<List<Author>> authorsOfAllBooks = new ArrayList<>(); for (Book book : books) { List<Author> authors = new ArrayList<>(); for (String name : book.authors) { authors.add(AUTHORS.get(name)); } authorsOfAllBooks.add(authors); } return Uni.createFrom().item(() -> authorsOfAllBooks); } private static final String AMAZON_SEARCH_FORMAT = "https://www.amazon.com/s?k=%s&i=stripbooks-intl-ship"; private static Map<String, Book> BOOKS = new HashMap<>(); private static Map<String, Author> AUTHORS = new HashMap<>(); static { Book book1 = new Book("0-571-05686-5", "Lord of the Flies", LocalDate.of(1954, Month.SEPTEMBER, 17), "William Golding"); BOOKS.put(book1.title, book1); AUTHORS.put("William Golding", new Author("William Golding", "William Gerald Golding", LocalDate.of(1911, Month.SEPTEMBER, 19), "Newquay, Cornwall, England")); Book book2 = new Book("0-582-53008-3", "Animal Farm", LocalDate.of(1945, Month.AUGUST, 17), "George Orwell"); BOOKS.put(book2.title, book2); AUTHORS.put("George Orwell", new Author("George Orwell", "Eric Arthur Blair", LocalDate.of(1903, Month.JUNE, 25), "Motihari, Bengal Presidency, British India")); } } public static
BookGraphQLApi
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/index/IndexesCreationTest.java
{ "start": 2638, "end": 3500 }
class ____ { private long id; private String field1; private String field2; private String field3; private String field4; @Id @Column public long getId() { return id; } public void setId(int id) { this.id = id; } @Column(name = "FIELD_1") public String getField1() { return field1; } public void setField1(String field1) { this.field1 = field1; } @Column(name = "FIELD_2") public String getField2() { return field2; } public void setField2(String field2) { this.field2 = field2; } @Column(name = "FIELD_3") public String getField3() { return field3; } public void setField3(String field3) { this.field3 = field3; } @Column(name = "FIELD_4") public String getField4() { return field4; } public void setField4(String field4) { this.field4 = field4; } } }
TestEntity
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/embeddedid/OneToOneMultiLevelEmbeddedId.java
{ "start": 2537, "end": 2793 }
class ____ { @EmbeddedId private TopId id; public Secondary() { } public Secondary(TopId id) { this.id = id; } public TopId getId() { return id; } } @Entity(name = "Primary") @Table(name = "primary_table") public static
Secondary
java
google__dagger
javatests/dagger/functional/binds/BindsCollectionsWithoutMultibindingsTest.java
{ "start": 1686, "end": 2068 }
interface ____ { Set<String> set(); Map<String, String> map(); } @Test public void works() { C component = DaggerBindsCollectionsWithoutMultibindingsTest_C.create(); assertThat(component.set()).containsExactly("binds", "set"); assertThat(component.map()) .containsExactly( "binds", "map", "without", "multibindings"); } }
C
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SmppEndpointBuilderFactory.java
{ "start": 93451, "end": 95070 }
interface ____ extends AdvancedSmppEndpointConsumerBuilder, AdvancedSmppEndpointProducerBuilder { default SmppEndpointBuilder basic() { return (SmppEndpointBuilder) this; } /** * Defines the interval in milliseconds between the confidence checks. * The confidence check is used to test the communication path between * an ESME and an SMSC. * * The option is a: <code>java.lang.Integer</code> type. * * Default: 60000 * Group: advanced * * @param enquireLinkTimer the value to set * @return the dsl builder */ default AdvancedSmppEndpointBuilder enquireLinkTimer(Integer enquireLinkTimer) { doSetProperty("enquireLinkTimer", enquireLinkTimer); return this; } /** * Defines the interval in milliseconds between the confidence checks. * The confidence check is used to test the communication path between * an ESME and an SMSC. * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Default: 60000 * Group: advanced * * @param enquireLinkTimer the value to set * @return the dsl builder */ default AdvancedSmppEndpointBuilder enquireLinkTimer(String enquireLinkTimer) { doSetProperty("enquireLinkTimer", enquireLinkTimer); return this; } /** * Defines the
AdvancedSmppEndpointBuilder
java
elastic__elasticsearch
x-pack/plugin/downsample/src/main/java/org/elasticsearch/xpack/downsample/DownsampleShardIndexer.java
{ "start": 3867, "end": 16300 }
class ____ { private static final Logger logger = LogManager.getLogger(DownsampleShardIndexer.class); private static final int DOCID_BUFFER_SIZE = 8096; public static final int DOWNSAMPLE_BULK_ACTIONS = 10000; public static final ByteSizeValue DOWNSAMPLE_BULK_SIZE = ByteSizeValue.of(1, ByteSizeUnit.MB); public static final ByteSizeValue DOWNSAMPLE_MAX_BYTES_IN_FLIGHT = ByteSizeValue.of(50, ByteSizeUnit.MB); private final IndexShard indexShard; private final Client client; private final DownsampleMetrics downsampleMetrics; private final String downsampleIndex; private final Engine.Searcher searcher; private final SearchExecutionContext searchExecutionContext; private final DateFieldMapper.DateFieldType timestampField; private final DocValueFormat timestampFormat; private final Rounding.Prepared rounding; private final List<FieldValueFetcher> fieldValueFetchers; private final DownsampleShardTask task; private final DownsampleShardPersistentTaskState state; private final String[] dimensions; private volatile boolean abort = false; ByteSizeValue downsampleBulkSize = DOWNSAMPLE_BULK_SIZE; ByteSizeValue downsampleMaxBytesInFlight = DOWNSAMPLE_MAX_BYTES_IN_FLIGHT; DownsampleShardIndexer( final DownsampleShardTask task, final Client client, final IndexService indexService, final DownsampleMetrics downsampleMetrics, final ShardId shardId, final String downsampleIndex, final DownsampleConfig config, final String[] metrics, final String[] labels, final String[] dimensions, final DownsampleShardPersistentTaskState state ) { this.task = task; this.client = client; this.downsampleMetrics = downsampleMetrics; this.indexShard = indexService.getShard(shardId.id()); this.downsampleIndex = downsampleIndex; this.searcher = indexShard.acquireSearcher("downsampling"); this.state = state; Closeable toClose = searcher; try { this.searchExecutionContext = indexService.newSearchExecutionContext( indexShard.shardId().id(), 0, searcher, () -> 0L, null, Collections.emptyMap() ); this.dimensions = dimensions; this.timestampField = (DateFieldMapper.DateFieldType) searchExecutionContext.getFieldType(config.getTimestampField()); this.timestampFormat = timestampField.docValueFormat(null, null); this.rounding = config.createRounding(); var samplingMethod = config.getSamplingMethodOrDefault(); List<FieldValueFetcher> fetchers = new ArrayList<>(metrics.length + labels.length + dimensions.length); fetchers.addAll(FieldValueFetcher.create(searchExecutionContext, metrics, samplingMethod)); // Labels are downsampled using the last value, they are not influenced by the requested sampling method fetchers.addAll(FieldValueFetcher.create(searchExecutionContext, labels, DownsampleConfig.SamplingMethod.LAST_VALUE)); fetchers.addAll(DimensionFieldValueFetcher.create(searchExecutionContext, dimensions)); this.fieldValueFetchers = Collections.unmodifiableList(fetchers); toClose = null; } finally { IOUtils.closeWhileHandlingException(toClose); } } public DownsampleIndexerAction.ShardDownsampleResponse execute() throws IOException { final Query initialStateQuery = createQuery(); if (initialStateQuery instanceof MatchNoDocsQuery) { return new DownsampleIndexerAction.ShardDownsampleResponse(indexShard.shardId(), task.getNumIndexed()); } long startTime = client.threadPool().relativeTimeInMillis(); task.setTotalShardDocCount(searcher.getDirectoryReader().numDocs()); task.setDownsampleShardIndexerStatus(DownsampleShardIndexerStatus.STARTED); task.updatePersistentTaskState( new DownsampleShardPersistentTaskState(DownsampleShardIndexerStatus.STARTED, null), ActionListener.noop() ); logger.info("Downsampling task [" + task.getPersistentTaskId() + " on shard " + indexShard.shardId() + " started"); BulkProcessor2 bulkProcessor = createBulkProcessor(); try (searcher; bulkProcessor) { final TimeSeriesIndexSearcher timeSeriesSearcher = new TimeSeriesIndexSearcher(searcher, List.of(this::checkCancelled)); TimeSeriesBucketCollector bucketCollector = new TimeSeriesBucketCollector(bulkProcessor, this.dimensions); bucketCollector.preCollection(); timeSeriesSearcher.search(initialStateQuery, bucketCollector); } TimeValue duration = TimeValue.timeValueMillis(client.threadPool().relativeTimeInMillis() - startTime); logger.info( "Shard [{}] successfully sent [{}], received source doc [{}], indexed downsampled doc [{}], failed [{}], took [{}]", indexShard.shardId(), task.getNumReceived(), task.getNumSent(), task.getNumIndexed(), task.getNumFailed(), duration ); if (task.getNumIndexed() != task.getNumSent()) { task.setDownsampleShardIndexerStatus(DownsampleShardIndexerStatus.FAILED); final String error = "Downsampling task [" + task.getPersistentTaskId() + "] on shard " + indexShard.shardId() + " failed indexing, " + " indexed [" + task.getNumIndexed() + "] sent [" + task.getNumSent() + "]"; logger.info(error); downsampleMetrics.recordShardOperation(duration.millis(), DownsampleMetrics.ActionStatus.MISSING_DOCS); throw new DownsampleShardIndexerException(error, false); } if (task.getNumFailed() > 0) { final String error = "Downsampling task [" + task.getPersistentTaskId() + "] on shard " + indexShard.shardId() + " failed indexing [" + task.getNumFailed() + "]"; logger.info(error); downsampleMetrics.recordShardOperation(duration.millis(), DownsampleMetrics.ActionStatus.FAILED); throw new DownsampleShardIndexerException(error, false); } task.setDownsampleShardIndexerStatus(DownsampleShardIndexerStatus.COMPLETED); task.updatePersistentTaskState( new DownsampleShardPersistentTaskState(DownsampleShardIndexerStatus.COMPLETED, null), ActionListener.noop() ); logger.info("Downsampling task [" + task.getPersistentTaskId() + " on shard " + indexShard.shardId() + " completed"); downsampleMetrics.recordShardOperation(duration.millis(), DownsampleMetrics.ActionStatus.SUCCESS); return new DownsampleIndexerAction.ShardDownsampleResponse(indexShard.shardId(), task.getNumIndexed()); } private Query createQuery() { if (this.state.started() && this.state.tsid() != null) { return SortedSetDocValuesField.newSlowRangeQuery(TimeSeriesIdFieldMapper.NAME, this.state.tsid(), null, true, false); } return new MatchAllDocsQuery(); } private void checkCancelled() { if (task.isCancelled()) { logger.warn( "Shard [{}] downsampled abort, sent [{}], indexed [{}], failed[{}]", indexShard.shardId(), task.getNumSent(), task.getNumIndexed(), task.getNumFailed() ); task.setDownsampleShardIndexerStatus(DownsampleShardIndexerStatus.CANCELLED); task.updatePersistentTaskState( new DownsampleShardPersistentTaskState(DownsampleShardIndexerStatus.CANCELLED, null), ActionListener.noop() ); logger.info("Downsampling task [" + task.getPersistentTaskId() + "] on shard " + indexShard.shardId() + " cancelled"); throw new DownsampleShardIndexerException( new TaskCancelledException(format("Shard %s downsample cancelled", indexShard.shardId())), format("Shard %s downsample cancelled", indexShard.shardId()), false ); } if (abort) { logger.warn( "Shard [{}] downsample abort, sent [{}], indexed [{}], failed[{}]", indexShard.shardId(), task.getNumSent(), task.getNumIndexed(), task.getNumFailed() ); task.setDownsampleShardIndexerStatus(DownsampleShardIndexerStatus.FAILED); task.updatePersistentTaskState( new DownsampleShardPersistentTaskState(DownsampleShardIndexerStatus.FAILED, null), ActionListener.noop() ); throw new DownsampleShardIndexerException("Bulk indexing failure", true); } } private BulkProcessor2 createBulkProcessor() { final BulkProcessor2.Listener listener = new BulkProcessor2.Listener() { @Override public void beforeBulk(long executionId, BulkRequest request) { task.addNumSent(request.numberOfActions()); task.setBeforeBulkInfo( new DownsampleBeforeBulkInfo( client.threadPool().absoluteTimeInMillis(), executionId, request.estimatedSizeInBytes(), request.numberOfActions() ) ); } @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { long bulkIngestTookMillis = response.getIngestTookInMillis() >= 0 ? response.getIngestTookInMillis() : 0; long bulkTookMillis = response.getTook().getMillis(); task.addNumIndexed(request.numberOfActions()); task.setAfterBulkInfo( new DownsampleAfterBulkInfo( client.threadPool().absoluteTimeInMillis(), executionId, bulkIngestTookMillis, bulkTookMillis, response.hasFailures(), RestStatus.OK.getStatus() ) ); task.updateBulkInfo(bulkIngestTookMillis, bulkTookMillis); if (response.hasFailures()) { List<BulkItemResponse> failedItems = Arrays.stream(response.getItems()).filter(BulkItemResponse::isFailed).toList(); task.addNumFailed(failedItems.size()); Map<String, String> failures = failedItems.stream() .collect( Collectors.toMap( BulkItemResponse::getId, BulkItemResponse::getFailureMessage, (msg1, msg2) -> Objects.equals(msg1, msg2) ? msg1 : msg1 + "," + msg2 ) ); logger.error("Shard [{}] failed to populate downsample index. Failures: [{}]", indexShard.shardId(), failures); abort = true; } } @Override public void afterBulk(long executionId, BulkRequest request, Exception failure) { if (failure != null) { long items = request.numberOfActions(); task.addNumFailed(items); logger.error(() -> format("Shard [%s] failed to populate downsample index.", indexShard.shardId()), failure); abort = true; } } }; return BulkProcessor2.builder(client::bulk, listener, client.threadPool()) .setBulkActions(DOWNSAMPLE_BULK_ACTIONS) .setBulkSize(DOWNSAMPLE_BULK_SIZE) .setMaxBytesInFlight(downsampleMaxBytesInFlight) .setMaxNumberOfRetries(3) .build(); } private
DownsampleShardIndexer
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/condition/ConditionFactory.java
{ "start": 490, "end": 855 }
interface ____ { /** * Parses the given xcontent and creates a concrete condition * @param watchId The id of the watch * @param parser The parsing that contains the condition content */ ExecutableCondition parse(Clock clock, String watchId, XContentParser parser) throws IOException; }
ConditionFactory
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_6_gzip.java
{ "start": 926, "end": 1013 }
class ____ { @JSONField(format = "gzip") public byte[] value; } }
Model
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/AddressFilterTest.java
{ "start": 1020, "end": 2640 }
class ____ { @Test public void filterAddresses() { Attributes.Key<String> key1 = Attributes.Key.create("key1"); Attributes attributes1 = Attributes.newBuilder().set(key1, "value1").build(); EquivalentAddressGroup eag0 = new EquivalentAddressGroup(new InetSocketAddress(8000)); EquivalentAddressGroup eag1 = new EquivalentAddressGroup(new InetSocketAddress(8001), attributes1); EquivalentAddressGroup eag2 = new EquivalentAddressGroup(new InetSocketAddress(8002)); EquivalentAddressGroup eag3 = new EquivalentAddressGroup( Arrays.<SocketAddress>asList(new InetSocketAddress(8003), new InetSocketAddress(8083))); eag0 = AddressFilter.setPathFilter(eag0, Arrays.asList("A", "C")); eag1 = AddressFilter.setPathFilter(eag1, Arrays.asList("A", "B")); eag2 = AddressFilter.setPathFilter(eag2, Arrays.asList("D", "C")); eag3 = AddressFilter.setPathFilter(eag3, Arrays.asList("A", "B")); List<EquivalentAddressGroup> addresses = AddressFilter.filter(Arrays.asList(eag0, eag1, eag2, eag3), "A"); assertThat(addresses).hasSize(3); addresses = AddressFilter.filter(addresses, "B"); assertThat(addresses).hasSize(2); EquivalentAddressGroup filteredAddress0 = addresses.get(0); EquivalentAddressGroup filteredAddress1 = addresses.get(1); assertThat(filteredAddress0.getAddresses()).containsExactlyElementsIn(eag1.getAddresses()); assertThat(filteredAddress0.getAttributes().get(key1)).isEqualTo("value1"); assertThat(filteredAddress1.getAddresses()).containsExactlyElementsIn(eag3.getAddresses()); } }
AddressFilterTest
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-data-r2dbc/src/main/java/smoketest/data/r2dbc/SampleR2dbcApplication.java
{ "start": 808, "end": 949 }
class ____ { public static void main(String[] args) { SpringApplication.run(SampleR2dbcApplication.class, args); } }
SampleR2dbcApplication
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/pipeline/CumulativeSumPipelineAggregationBuilder.java
{ "start": 1125, "end": 4507 }
class ____ extends AbstractPipelineAggregationBuilder<CumulativeSumPipelineAggregationBuilder> { public static final String NAME = "cumulative_sum"; private String format; @SuppressWarnings("unchecked") public static final ConstructingObjectParser<CumulativeSumPipelineAggregationBuilder, String> PARSER = new ConstructingObjectParser<>( NAME, false, (args, name) -> new CumulativeSumPipelineAggregationBuilder(name, (List<String>) args[0]) ); static { PARSER.declareStringArray(constructorArg(), BUCKETS_PATH_FIELD); PARSER.declareString(CumulativeSumPipelineAggregationBuilder::format, FORMAT); }; public CumulativeSumPipelineAggregationBuilder(String name, String bucketsPath) { super(name, NAME, new String[] { bucketsPath }); } CumulativeSumPipelineAggregationBuilder(String name, List<String> bucketsPath) { super(name, NAME, bucketsPath.toArray(new String[0])); } /** * Read from a stream. */ public CumulativeSumPipelineAggregationBuilder(StreamInput in) throws IOException { super(in, NAME); format = in.readOptionalString(); } @Override protected final void doWriteTo(StreamOutput out) throws IOException { out.writeOptionalString(format); } /** * Sets the format to use on the output of this aggregation. */ public CumulativeSumPipelineAggregationBuilder format(String format) { if (format == null) { throw new IllegalArgumentException("[format] must not be null: [" + name + "]"); } this.format = format; return this; } protected DocValueFormat formatter() { if (format != null) { return new DocValueFormat.Decimal(format); } else { return DocValueFormat.RAW; } } @Override protected PipelineAggregator createInternal(Map<String, Object> metadata) { return new CumulativeSumPipelineAggregator(name, bucketsPaths, formatter(), metadata); } @Override protected void validate(ValidationContext context) { if (bucketsPaths.length != 1) { context.addBucketPathValidationError("must contain a single entry for aggregation [" + name + "]"); } context.validateParentAggSequentiallyOrderedWithoutSkips(NAME, name); } @Override protected final XContentBuilder internalXContent(XContentBuilder builder, Params params) throws IOException { if (format != null) { builder.field(BucketMetricsParser.FORMAT.getPreferredName(), format); } return builder; } @Override public int hashCode() { return Objects.hash(super.hashCode(), format); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; if (super.equals(obj) == false) return false; CumulativeSumPipelineAggregationBuilder other = (CumulativeSumPipelineAggregationBuilder) obj; return Objects.equals(format, other.format); } @Override public String getWriteableName() { return NAME; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.zero(); } }
CumulativeSumPipelineAggregationBuilder
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryTranslator.java
{ "start": 21390, "end": 21605 }
class ____ extends SingleValueAggTranslator<Max> { @Override protected LeafAgg toAgg(String id, Max m) { return new MaxAgg(id, asFieldOrLiteralOrScript(m)); } } static
Maxes
java
elastic__elasticsearch
x-pack/plugin/security/qa/multi-cluster/src/javaRestTest/java/org/elasticsearch/xpack/remotecluster/RemoteClusterSecurityApiKeyRestIT.java
{ "start": 1351, "end": 17496 }
class ____ extends AbstractRemoteClusterSecurityTestCase { private static final AtomicReference<Map<String, Object>> API_KEY_MAP_REF = new AtomicReference<>(); static { fulfillingCluster = ElasticsearchCluster.local() .name("fulfilling-cluster") .apply(commonClusterConfig) .setting("remote_cluster_server.enabled", "true") .setting("remote_cluster.port", "0") .setting("xpack.security.remote_cluster_server.ssl.enabled", "true") .setting("xpack.security.remote_cluster_server.ssl.key", "remote-cluster.key") .setting("xpack.security.remote_cluster_server.ssl.certificate", "remote-cluster.crt") .keystore("xpack.security.remote_cluster_server.ssl.secure_key_passphrase", "remote-cluster-password") .build(); queryCluster = ElasticsearchCluster.local() .name("query-cluster") .apply(commonClusterConfig) .setting("xpack.security.remote_cluster_client.ssl.enabled", "true") .setting("xpack.security.remote_cluster_client.ssl.certificate_authorities", "remote-cluster-ca.crt") .keystore("cluster.remote.my_remote_cluster.credentials", () -> { if (API_KEY_MAP_REF.get() == null) { final Map<String, Object> apiKeyMap = createCrossClusterAccessApiKey(""" { "search": [ { "names": ["index*", "not_found_index"] } ] }"""); API_KEY_MAP_REF.set(apiKeyMap); } return (String) API_KEY_MAP_REF.get().get("encoded"); }) .keystore("cluster.remote.invalid_remote.credentials", randomEncodedApiKey()) .build(); } @ClassRule // Use a RuleChain to ensure that fulfilling cluster is started before query cluster public static TestRule clusterRule = RuleChain.outerRule(fulfillingCluster).around(queryCluster); public void testCrossClusterSearchWithApiKey() throws Exception { configureRemoteCluster(); final String remoteAccessApiKeyId = (String) API_KEY_MAP_REF.get().get("id"); // Fulfilling cluster { // Index some documents, so we can attempt to search them from the querying cluster final Request bulkRequest = new Request("POST", "/_bulk?refresh=true"); bulkRequest.setJsonEntity(Strings.format(""" { "index": { "_index": "index1" } } { "foo": "bar" } { "index": { "_index": "index2" } } { "bar": "foo" } { "index": { "_index": "prefixed_index" } } { "baz": "fee" }\n""")); assertOK(performRequestAgainstFulfillingCluster(bulkRequest)); } // Query cluster { // Index some documents, to use them in a mixed-cluster search final var indexDocRequest = new Request("POST", "/local_index/_doc?refresh=true"); indexDocRequest.setJsonEntity("{\"local_foo\": \"local_bar\"}"); assertOK(client().performRequest(indexDocRequest)); // Create user role with privileges for remote and local indices final var putRoleRequest = new Request("PUT", "/_security/role/" + REMOTE_SEARCH_ROLE); putRoleRequest.setJsonEntity(""" { "description": "role with privileges for remote and local indices", "cluster": ["manage_own_api_key"], "indices": [ { "names": ["local_index"], "privileges": ["read"] } ], "remote_indices": [ { "names": ["index1", "not_found_index", "prefixed_index"], "privileges": ["read", "read_cross_cluster"], "clusters": ["my_remote_cluster"] } ] }"""); assertOK(adminClient().performRequest(putRoleRequest)); final var putUserRequest = new Request("PUT", "/_security/user/" + REMOTE_SEARCH_USER); putUserRequest.setJsonEntity(""" { "password": "x-pack-test-password", "roles" : ["remote_search"] }"""); assertOK(adminClient().performRequest(putUserRequest)); // Create API key (with REMOTE_SEARCH_USER as owner) which can be used for remote cluster search final var createApiKeyRequest = new Request("PUT", "/_security/api_key"); // Note: index2 is added to remote_indices for the API key, // but it should be ignored when intersected since owner user does not have access to it. createApiKeyRequest.setJsonEntity(randomBoolean() ? """ { "name": "qc_api_key_with_remote_access", "role_descriptors": { "my_remote_access_role": { "indices": [ { "names": ["local_index"], "privileges": ["read"] } ], "remote_indices": [ { "names": ["index1", "not_found_index", "prefixed_index", "index2"], "privileges": ["read", "read_cross_cluster"], "clusters": ["my_remote_*", "non_existing_remote_cluster"] } ] } } }""" : """ { "name": "qc_api_key_with_remote_access", "role_descriptors": {} }"""); final var createApiKeyResponse = performRequestWithRemoteAccessUser(createApiKeyRequest); assertOK(createApiKeyResponse); var createApiKeyResponsePath = ObjectPath.createFromResponse(createApiKeyResponse); final String apiKeyEncoded = createApiKeyResponsePath.evaluate("encoded"); final String apiKeyId = createApiKeyResponsePath.evaluate("id"); assertThat(apiKeyEncoded, notNullValue()); assertThat(apiKeyId, notNullValue()); // Check that we can search the fulfilling cluster from the querying cluster final boolean alsoSearchLocally = randomBoolean(); final var searchRequest = new Request( "GET", String.format( Locale.ROOT, "/%s%s:%s/_search?ccs_minimize_roundtrips=%s", alsoSearchLocally ? "local_index," : "", randomFrom("my_remote_cluster", "*", "my_remote_*"), randomFrom("index1", "*"), randomBoolean() ) ); final Response response = performRequestWithApiKey(searchRequest, apiKeyEncoded); assertOK(response); final SearchResponse searchResponse; try (var parser = responseAsParser(response)) { searchResponse = SearchResponseUtils.parseSearchResponse(parser); } try { final List<String> actualIndices = Arrays.stream(searchResponse.getHits().getHits()) .map(SearchHit::getIndex) .collect(Collectors.toList()); if (alsoSearchLocally) { assertThat(actualIndices, containsInAnyOrder("index1", "local_index")); } else { assertThat(actualIndices, containsInAnyOrder("index1")); } } finally { searchResponse.decRef(); } // Check that access is denied because of API key privileges final Request index2SearchRequest = new Request("GET", "/my_remote_cluster:index2/_search"); final ResponseException exception = expectThrows( ResponseException.class, () -> performRequestWithApiKey(index2SearchRequest, apiKeyEncoded) ); assertThat(exception.getResponse().getStatusLine().getStatusCode(), equalTo(403)); assertThat( exception.getMessage(), containsString( "action [indices:data/read/search] towards remote cluster is unauthorized for API key id [" + apiKeyId + "] of user [" + REMOTE_SEARCH_USER + "] authenticated by API key id [" + remoteAccessApiKeyId + "] of user [test_user] on indices [index2]" ) ); // Check that access is denied because of cross cluster access API key privileges final Request prefixedIndexSearchRequest = new Request("GET", "/my_remote_cluster:prefixed_index/_search"); final ResponseException exception2 = expectThrows( ResponseException.class, () -> performRequestWithApiKey(prefixedIndexSearchRequest, apiKeyEncoded) ); assertThat(exception2.getResponse().getStatusLine().getStatusCode(), equalTo(403)); assertThat( exception2.getMessage(), containsString( "action [indices:data/read/search] towards remote cluster is unauthorized for API key id [" + apiKeyId + "] of user [" + REMOTE_SEARCH_USER + "] authenticated by API key id [" + remoteAccessApiKeyId + "] of user [test_user] on indices [prefixed_index]" ) ); // Check access is denied when user has no remote indices privileges final var putLocalSearchRoleRequest = new Request("PUT", "/_security/role/local_search"); putLocalSearchRoleRequest.setJsonEntity(Strings.format(""" { "cluster": ["manage_own_api_key"], "indices": [ { "names": ["local_index"], "privileges": ["read"] } ]%s }""", randomBoolean() ? "" : """ , "remote_indices": [ { "names": ["*"], "privileges": ["read", "read_cross_cluster"], "clusters": ["other_remote_*"] } ]""")); assertOK(adminClient().performRequest(putLocalSearchRoleRequest)); final var putlocalSearchUserRequest = new Request("PUT", "/_security/user/local_search_user"); putlocalSearchUserRequest.setJsonEntity(""" { "password": "x-pack-test-password", "roles" : ["local_search"] }"""); assertOK(adminClient().performRequest(putlocalSearchUserRequest)); final var createLocalApiKeyRequest = new Request("PUT", "/_security/api_key"); String localApiKeyRoleDescriptors = Strings.format(""" "my_local_access_role": { "indices": [ { "names": ["local_index"], "privileges": ["read"] } ]%s } """, randomBoolean() ? "" : """ , "remote_indices": [ { "names": ["*"], "privileges": ["read", "read_cross_cluster"], "clusters": ["other_remote_*"] } ]"""); createLocalApiKeyRequest.setJsonEntity(Strings.format(""" { "name": "qc_api_key_with_remote_access", "role_descriptors": { %s } }""", randomBoolean() ? localApiKeyRoleDescriptors : "")); final var createLocalApiKeyResponse = performRequestWithLocalSearchUser(createLocalApiKeyRequest); assertOK(createApiKeyResponse); var createLocalApiKeyResponsePath = ObjectPath.createFromResponse(createLocalApiKeyResponse); final String localApiKeyEncoded = createLocalApiKeyResponsePath.evaluate("encoded"); final String localApiKeyId = createLocalApiKeyResponsePath.evaluate("id"); assertThat(localApiKeyEncoded, notNullValue()); assertThat(localApiKeyId, notNullValue()); final Request randomRemoteSearch = new Request( "GET", "/" + randomFrom("my_remote_cluster:*", "*:*", "*,*:*", "my_*:*,local_index") + "/_search" ); final ResponseException exception3 = expectThrows( ResponseException.class, () -> performRequestWithApiKey(randomRemoteSearch, localApiKeyEncoded) ); assertThat(exception3.getResponse().getStatusLine().getStatusCode(), equalTo(403)); assertThat( exception3.getMessage(), containsString( "action [indices:data/read/search] towards remote cluster [my_remote_cluster] " + "is unauthorized for API key id [" + localApiKeyId + "] of user [local_search_user] because no remote indices privileges apply for the target cluster" ) ); // Check that authentication fails if we use a non-existent cross cluster access API key (when skip_unavailable=false) updateClusterSettings( randomBoolean() ? Settings.builder() .put("cluster.remote.invalid_remote.seeds", fulfillingCluster.getRemoteClusterServerEndpoint(0)) .put("cluster.remote.invalid_remote.skip_unavailable", "false") .build() : Settings.builder() .put("cluster.remote.invalid_remote.mode", "proxy") .put("cluster.remote.invalid_remote.skip_unavailable", "false") .put("cluster.remote.invalid_remote.proxy_address", fulfillingCluster.getRemoteClusterServerEndpoint(0)) .build() ); final ResponseException exception4 = expectThrows( ResponseException.class, () -> performRequestWithApiKey(new Request("GET", "/invalid_remote:index1/_search"), apiKeyEncoded) ); assertThat(exception4.getResponse().getStatusLine().getStatusCode(), equalTo(401)); assertThat(exception4.getMessage(), containsString("unable to find apikey")); } } private Response performRequestWithRemoteAccessUser(final Request request) throws IOException { request.setOptions(RequestOptions.DEFAULT.toBuilder().addHeader("Authorization", basicAuthHeaderValue(REMOTE_SEARCH_USER, PASS))); return client().performRequest(request); } private Response performRequestWithLocalSearchUser(final Request request) throws IOException { request.setOptions(RequestOptions.DEFAULT.toBuilder().addHeader("Authorization", basicAuthHeaderValue("local_search_user", PASS))); return client().performRequest(request); } private Response performRequestWithApiKey(final Request request, final String encoded) throws IOException { request.setOptions(RequestOptions.DEFAULT.toBuilder().addHeader("Authorization", "ApiKey " + encoded)); return client().performRequest(request); } }
RemoteClusterSecurityApiKeyRestIT
java
apache__camel
components/camel-aws/camel-aws2-sns/src/main/java/org/apache/camel/component/aws2/sns/client/Sns2ClientFactory.java
{ "start": 1327, "end": 2206 }
class ____ { private Sns2ClientFactory() { } /** * Return the correct aws SNS client (based on remote vs local). * * @param configuration configuration * @return SNSClient */ public static Sns2InternalClient getSnsClient(Sns2Configuration configuration) { if (Boolean.TRUE.equals(configuration.isUseDefaultCredentialsProvider())) { return new Sns2ClientIAMOptimized(configuration); } else if (Boolean.TRUE.equals(configuration.isUseProfileCredentialsProvider())) { return new Sns2ClientIAMProfileOptimized(configuration); } else if (Boolean.TRUE.equals(configuration.isUseSessionCredentials())) { return new Sns2ClientSessionTokenImpl(configuration); } else { return new Sns2ClientStandardImpl(configuration); } } }
Sns2ClientFactory
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plan/QuerySettings.java
{ "start": 5896, "end": 6056 }
interface ____<T> { /** * Parses an already validated literal. */ T parse(Literal value); } } }
Parser
java
alibaba__nacos
api/src/main/java/com/alibaba/nacos/api/ai/model/a2a/AgentInterface.java
{ "start": 749, "end": 1531 }
class ____ { private String url; private String transport; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTransport() { return transport; } public void setTransport(String transport) { this.transport = transport; } @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } AgentInterface that = (AgentInterface) o; return Objects.equals(url, that.url) && Objects.equals(transport, that.transport); } @Override public int hashCode() { return Objects.hash(url, transport); } }
AgentInterface
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/coordination/RemoveCustomsCommand.java
{ "start": 1235, "end": 5428 }
class ____ extends ElasticsearchNodeCommand { static final String CUSTOMS_REMOVED_MSG = "Customs were successfully removed from the cluster state"; static final String CONFIRMATION_MSG = DELIMITER + "\n" + "You should only run this tool if you have broken custom metadata in the\n" + "cluster state that prevents the cluster state from being loaded.\n" + "This tool can cause data loss and its use should be your last resort.\n" + "\n" + "Do you want to proceed?\n"; private final OptionSpec<String> arguments; public RemoveCustomsCommand() { super("Removes custom metadata from the cluster state"); arguments = parser.nonOptions("custom metadata names"); } @Override protected void processDataPaths(Terminal terminal, Path[] dataPaths, OptionSet options, Environment env) throws IOException, UserException { final List<String> customsToRemove = arguments.values(options); if (customsToRemove.isEmpty()) { throw new UserException(ExitCodes.USAGE, "Must supply at least one custom metadata name to remove"); } final PersistedClusterStateService persistedClusterStateService = createPersistedClusterStateService(env.settings(), dataPaths); terminal.println(Terminal.Verbosity.VERBOSE, "Loading cluster state"); final Tuple<Long, ClusterState> termAndClusterState = loadTermAndClusterState(persistedClusterStateService, env); final ClusterState oldClusterState = termAndClusterState.v2(); terminal.println( Terminal.Verbosity.VERBOSE, "cluster scoped custom metadata names: " + oldClusterState.metadata().customs().keySet() ); terminal.println( Terminal.Verbosity.VERBOSE, "project scoped custom metadata names: " + oldClusterState.metadata().getProject().customs().keySet() ); final Metadata.Builder metadataBuilder = Metadata.builder(oldClusterState.metadata()); @FixForMultiProject final ProjectMetadata.Builder projectBuilder = metadataBuilder.getProject(ProjectId.DEFAULT); for (String customToRemove : customsToRemove) { @FixForMultiProject boolean matched = false; // TODO[MultiProject]: Should we add a scope flag to the command, or just iterate through both maps? for (String customKey : oldClusterState.metadata().customs().keySet()) { if (Regex.simpleMatch(customToRemove, customKey)) { metadataBuilder.removeCustom(customKey); if (matched == false) { terminal.println("The following customs will be removed:"); } matched = true; terminal.println(customKey); } } for (String customKey : oldClusterState.metadata().getProject().customs().keySet()) { if (Regex.simpleMatch(customToRemove, customKey)) { projectBuilder.removeCustom(customKey); if (matched == false) { terminal.println("The following customs will be removed:"); } matched = true; terminal.println(customKey); } } if (matched == false) { throw new UserException(ExitCodes.USAGE, "No custom metadata matching [" + customToRemove + "] were found on this node"); } } final ClusterState newClusterState = ClusterState.builder(oldClusterState).metadata(metadataBuilder.build()).build(); terminal.println( Terminal.Verbosity.VERBOSE, "[old cluster state = " + oldClusterState + ", new cluster state = " + newClusterState + "]" ); confirm(terminal, CONFIRMATION_MSG); try (PersistedClusterStateService.Writer writer = persistedClusterStateService.createWriter()) { writer.writeFullStateAndCommit(termAndClusterState.v1(), newClusterState); } terminal.println(CUSTOMS_REMOVED_MSG); } }
RemoveCustomsCommand
java
apache__camel
components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpMapHeadersFalseTest.java
{ "start": 1374, "end": 3493 }
class ____ extends BaseNettyTest { @Test public void testHttpHeaderCase() throws Exception { HttpPost method = new HttpPost("http://localhost:" + getPort() + "/myapp/mytest"); method.addHeader("clientHeader", "fooBAR"); method.addHeader("OTHER", "123"); method.addHeader("beer", "Carlsberg"); try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(method)) { String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); assertEquals("Bye World", responseString); assertEquals("aBc123", response.getFirstHeader("MyCaseHeader").getValue()); assertEquals("456DEf", response.getFirstHeader("otherCaseHeader").getValue()); } } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("netty-http:http://localhost:{{port}}/myapp/mytest?mapHeaders=false").process(exchange -> { // these headers is not mapped assertNull(exchange.getIn().getHeader("clientHeader")); assertNull(exchange.getIn().getHeader("OTHER")); assertNull(exchange.getIn().getHeader("beer")); // but we can find them in the http request from netty assertEquals("fooBAR", exchange.getIn(NettyHttpMessage.class).getHttpRequest().headers().get("clientHeader")); assertEquals("123", exchange.getIn(NettyHttpMessage.class).getHttpRequest().headers().get("OTHER")); assertEquals("Carlsberg", exchange.getIn(NettyHttpMessage.class).getHttpRequest().headers().get("beer")); exchange.getMessage().setBody("Bye World"); exchange.getMessage().setHeader("MyCaseHeader", "aBc123"); exchange.getMessage().setHeader("otherCaseHeader", "456DEf"); }); } }; } }
NettyHttpMapHeadersFalseTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java
{ "start": 1658, "end": 4983 }
class ____ { @Test void importResource() { try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlConfig.class)) { assertThat(ctx.containsBean("javaDeclaredBean")).as("did not contain java-declared bean").isTrue(); assertThat(ctx.containsBean("xmlDeclaredBean")).as("did not contain xml-declared bean").isTrue(); TestBean tb = ctx.getBean("javaDeclaredBean", TestBean.class); assertThat(tb.getName()).isEqualTo("myName"); } } @Test void importResourceIsInheritedFromSuperclassDeclarations() { try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(FirstLevelSubConfig.class)) { assertThat(ctx.containsBean("xmlDeclaredBean")).isTrue(); } } @Test void importResourceIsMergedFromSuperclassDeclarations() { try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SecondLevelSubConfig.class)) { assertThat(ctx.containsBean("secondLevelXmlDeclaredBean")).as("failed to pick up second-level-declared XML bean").isTrue(); assertThat(ctx.containsBean("xmlDeclaredBean")).as("failed to pick up parent-declared XML bean").isTrue(); } } @Test void importResourceWithNamespaceConfig() { try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlWithAopNamespaceConfig.class)) { Object bean = ctx.getBean("proxiedXmlBean"); assertThat(AopUtils.isAopProxy(bean)).isTrue(); } } @Test void importResourceWithOtherConfigurationClass() { try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlWithConfigurationClass.class)) { assertThat(ctx.containsBean("javaDeclaredBean")).as("did not contain java-declared bean").isTrue(); assertThat(ctx.containsBean("xmlDeclaredBean")).as("did not contain xml-declared bean").isTrue(); TestBean tb = ctx.getBean("javaDeclaredBean", TestBean.class); assertThat(tb.getName()).isEqualTo("myName"); } } @Test void importWithPlaceholder() { try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) { ctx.getEnvironment().getPropertySources().addFirst(new MockPropertySource("test").withProperty("test", "springframework")); ctx.register(ImportXmlConfig.class); ctx.refresh(); assertThat(ctx.containsBean("xmlDeclaredBean")).as("did not contain xml-declared bean").isTrue(); } } @Test void importResourceWithAutowiredConfig() { try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlAutowiredConfig.class)) { String name = ctx.getBean("xmlBeanName", String.class); assertThat(name).isEqualTo("xml.declared"); } } @Test void importNonXmlResource() { try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportNonXmlResourceConfig.class)) { assertThat(ctx.containsBean("propertiesDeclaredBean")).isTrue(); } } @Test void importResourceWithPrivateReader() { try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportWithPrivateReaderConfig.class)) { assertThat(ctx.containsBean("propertiesDeclaredBean")).isTrue(); } } @Configuration @ImportResource("classpath:org/springframework/context/annotation/configuration/ImportXmlConfig-context.xml") static
ImportResourceTests
java
apache__dubbo
dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java
{ "start": 1069, "end": 3292 }
interface ____ extends org.apache.dubbo.rpc.Invocation { @Override Invoker<?> getInvoker(); default org.apache.dubbo.rpc.Invocation getOriginal() { return null; } @Override default void setAttachment(String key, String value) { setObjectAttachment(key, value); } @Override default void setAttachmentIfAbsent(String key, String value) { setObjectAttachmentIfAbsent(key, value); } @Override default void setObjectAttachmentIfAbsent(String key, Object value) {} @Override default void setObjectAttachment(String key, Object value) {} @Override default void setAttachment(String key, Object value) { setObjectAttachment(key, value); } @Override default void setAttachmentIfAbsent(String key, Object value) { setObjectAttachmentIfAbsent(key, value); } @Override default String getServiceName() { return null; } @Override default String getTargetServiceUniqueName() { return null; } @Override default String getAttachment(String key, String defaultValue) { return null; } @Override default void setServiceModel(ServiceModel serviceModel) {} @Override default ServiceModel getServiceModel() { return null; } @Override default Object put(Object key, Object value) { return null; } @Override default Object get(Object key) { return null; } @Override default Map<Object, Object> getAttributes() { return null; } @Override default Map<String, Object> getObjectAttachments() { return Collections.emptyMap(); } @Override default Map<String, Object> copyObjectAttachments() { return new HashMap<>(getObjectAttachments()); } @Override default void foreachAttachment(Consumer<Map.Entry<String, Object>> consumer) { getObjectAttachments().entrySet().forEach(consumer); } @Override default Object getObjectAttachment(String key) { return null; } @Override default Object getObjectAttachment(String key, Object defaultValue) { return null; }
Invocation
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/integration/MockitoBeanWithMultipleExistingBeansAndExplicitBeanNameIntegrationTests.java
{ "start": 2701, "end": 3024 }
class ____ { @Bean StringExampleGenericService one() { return new StringExampleGenericService("one"); } @Bean // "stringService" matches the constructor argument name in ExampleGenericServiceCaller StringExampleGenericService stringService() { return new StringExampleGenericService("two"); } } }
Config
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/DiskValidator.java
{ "start": 1230, "end": 1440 }
interface ____ { /** * Check the status of a file/dir. * @param dir a file/dir * @throws DiskErrorException if any disk error */ void checkStatus(File dir) throws DiskErrorException; }
DiskValidator
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/annotation/Testable.java
{ "start": 3531, "end": 3672 }
class ____. * * @since 1.0 */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @API(status = STABLE, since = "1.0") public @
elements
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/observers/BlockingMultiObserverTest.java
{ "start": 900, "end": 2420 }
class ____ extends RxJavaTest { @Test public void dispose() { BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<>(); bmo.dispose(); Disposable d = Disposable.empty(); bmo.onSubscribe(d); } @Test public void blockingGetDefault() { final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<>(); Schedulers.single().scheduleDirect(new Runnable() { @Override public void run() { bmo.onSuccess(1); } }, 100, TimeUnit.MILLISECONDS); assertEquals(1, bmo.blockingGet(0).intValue()); } @Test public void blockingAwait() { final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<>(); Schedulers.single().scheduleDirect(new Runnable() { @Override public void run() { bmo.onSuccess(1); } }, 100, TimeUnit.MILLISECONDS); assertTrue(bmo.blockingAwait(1, TimeUnit.MINUTES)); } @Test public void blockingGetDefaultInterrupt() { final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<>(); Thread.currentThread().interrupt(); try { bmo.blockingGet(0); fail("Should have thrown"); } catch (RuntimeException ex) { assertTrue(ex.getCause() instanceof InterruptedException); } finally { Thread.interrupted(); } } }
BlockingMultiObserverTest
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-data-r2dbc-liquibase/src/main/java/smoketest/data/r2dbc/SampleR2dbcLiquibaseApplication.java
{ "start": 808, "end": 967 }
class ____ { public static void main(String[] args) { SpringApplication.run(SampleR2dbcLiquibaseApplication.class, args); } }
SampleR2dbcLiquibaseApplication
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/converters/IntegerConverter.java
{ "start": 1520, "end": 1727 }
class ____ extends NumberConverter<Integer> { public IntegerConverter() { super("integer", Schema.OPTIONAL_INT32_SCHEMA, new IntegerSerializer(), new IntegerDeserializer()); } }
IntegerConverter
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/failover/ExponentialDelayRestartBackoffTimeStrategyTest.java
{ "start": 1477, "end": 16321 }
class ____ { private final Exception failure = new Exception(); @Test void testMaxAttempts() { int maxAttempts = 13; ManualClock clock = new ManualClock(); long maxBackoffMS = 3L; final ExponentialDelayRestartBackoffTimeStrategy restartStrategy = new ExponentialDelayRestartBackoffTimeStrategy( clock, 1L, maxBackoffMS, 1.2, 10L, 0.25, maxAttempts); for (int i = 0; i <= maxAttempts; i++) { assertThat(restartStrategy.canRestart()).isTrue(); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); clock.advanceTime(Duration.ofMillis(maxBackoffMS + 1)); } assertThat(restartStrategy.canRestart()).isFalse(); } @Test void testNotCallNotifyFailure() { long initialBackoffMS = 42L; final ExponentialDelayRestartBackoffTimeStrategy restartStrategy = new ExponentialDelayRestartBackoffTimeStrategy( new ManualClock(), initialBackoffMS, 45L, 2.0, 8L, 0, 10); assertThatThrownBy(restartStrategy::getBackoffTime) .isInstanceOf(IllegalStateException.class) .hasMessage("Please call notifyFailure first."); } @Test void testInitialBackoff() { long initialBackoffMS = 42L; final ExponentialDelayRestartBackoffTimeStrategy restartStrategy = new ExponentialDelayRestartBackoffTimeStrategy( new ManualClock(), initialBackoffMS, 45L, 2.0, 8L, 0, Integer.MAX_VALUE); restartStrategy.notifyFailure(failure); assertThat(restartStrategy.getBackoffTime()).isEqualTo(initialBackoffMS); } @Test void testMaxBackoff() { final long maxBackoffMS = 6L; final ExponentialDelayRestartBackoffTimeStrategy restartStrategy = new ExponentialDelayRestartBackoffTimeStrategy( new ManualClock(), 1L, maxBackoffMS, 2.0, 8L, 0.25, Integer.MAX_VALUE); for (int i = 0; i < 10; i++) { restartStrategy.notifyFailure(failure); assertThat(restartStrategy.getBackoffTime()).isLessThanOrEqualTo(maxBackoffMS); } } @Test void testResetBackoff() { final long initialBackoffMS = 1L; final long resetBackoffThresholdMS = 8L; final ManualClock clock = new ManualClock(); final ExponentialDelayRestartBackoffTimeStrategy restartStrategy = new ExponentialDelayRestartBackoffTimeStrategy( clock, initialBackoffMS, 5L, 2.0, resetBackoffThresholdMS, 0.25, Integer.MAX_VALUE); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); clock.advanceTime( resetBackoffThresholdMS + restartStrategy.getBackoffTime() - 1, TimeUnit.MILLISECONDS); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); assertThat(restartStrategy.getBackoffTime()) .as("Backoff should be increased") .isEqualTo(2L); clock.advanceTime( resetBackoffThresholdMS + restartStrategy.getBackoffTime(), TimeUnit.MILLISECONDS); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); assertThat(restartStrategy.getBackoffTime()) .as("Backoff should be reset") .isEqualTo(initialBackoffMS); } @Test void testBackoffMultiplier() { long initialBackoffMS = 4L; double jitterFactor = 0; double backoffMultiplier = 2.3; long maxBackoffMS = 300L; ManualClock clock = new ManualClock(); final ExponentialDelayRestartBackoffTimeStrategy restartStrategy = new ExponentialDelayRestartBackoffTimeStrategy( clock, initialBackoffMS, maxBackoffMS, backoffMultiplier, Integer.MAX_VALUE, jitterFactor, 10); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); assertThat(restartStrategy.getBackoffTime()).isEqualTo(4L); // 4 clock.advanceTime(Duration.ofMillis(maxBackoffMS + 1)); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); assertThat(restartStrategy.getBackoffTime()).isEqualTo(9L); // 4 * 2.3 clock.advanceTime(Duration.ofMillis(maxBackoffMS + 1)); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); assertThat(restartStrategy.getBackoffTime()).isEqualTo(21L); // 4 * 2.3 * 2.3 clock.advanceTime(Duration.ofMillis(maxBackoffMS + 1)); } @Test void testJitter() throws Exception { final long initialBackoffMS = 2L; final long maxBackoffMS = 7L; ManualClock clock = new ManualClock(); final ExponentialDelayRestartBackoffTimeStrategyFactory restartStrategyFactory = new ExponentialDelayRestartBackoffTimeStrategyFactory( clock, initialBackoffMS, maxBackoffMS, 2.0, Integer.MAX_VALUE, 0.25, Integer.MAX_VALUE); assertCorrectRandomRangeWithFailureCount( restartStrategyFactory, clock, maxBackoffMS + 1, 2, 3L, 4L, 5L); assertCorrectRandomRangeWithFailureCount( restartStrategyFactory, clock, maxBackoffMS + 1, 3, 6L, 7L); assertCorrectRandomRangeWithFailureCount( restartStrategyFactory, clock, maxBackoffMS + 1, 4, 7L); } @Test void testJitterNoHigherThanMax() throws Exception { double jitterFactor = 1; long maxBackoffMS = 7L; ManualClock clock = new ManualClock(); final ExponentialDelayRestartBackoffTimeStrategyFactory restartStrategyFactory = new ExponentialDelayRestartBackoffTimeStrategyFactory( clock, 1L, maxBackoffMS, 2.0, Integer.MAX_VALUE, jitterFactor, Integer.MAX_VALUE); assertCorrectRandomRangeWithFailureCount( restartStrategyFactory, clock, maxBackoffMS + 1, 1, 1L, 2L); assertCorrectRandomRangeWithFailureCount( restartStrategyFactory, clock, maxBackoffMS + 1, 2, 1L, 2L, 3L, 4L); assertCorrectRandomRangeWithFailureCount( restartStrategyFactory, clock, maxBackoffMS + 1, 3, 1L, 2L, 3L, 4L, 5L, 6L, 7L); } private void assertCorrectRandomRangeWithFailureCount( ExponentialDelayRestartBackoffTimeStrategyFactory factory, ManualClock clock, long advanceMsEachFailure, int failureCount, Long... expectedNumbers) throws Exception { assertCorrectRandomRange( () -> { RestartBackoffTimeStrategy restartStrategy = factory.create(); for (int i = 0; i < failureCount; i++) { clock.advanceTime(Duration.ofMillis(advanceMsEachFailure)); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); } return restartStrategy.getBackoffTime(); }, expectedNumbers); } @Test void testMultipleSettings() { ManualClock clock = new ManualClock(); final long initialBackoffMS = 1L; final long maxBackoffMS = 9L; double backoffMultiplier = 2.0; final long resetBackoffThresholdMS = 80L; double jitterFactor = 0.25; final ExponentialDelayRestartBackoffTimeStrategy restartStrategy = new ExponentialDelayRestartBackoffTimeStrategy( clock, initialBackoffMS, maxBackoffMS, backoffMultiplier, resetBackoffThresholdMS, jitterFactor, Integer.MAX_VALUE); // ensure initial data assertThat(restartStrategy.notifyFailure(failure)).isTrue(); assertThat(restartStrategy.canRestart()).isTrue(); assertThat(restartStrategy.getBackoffTime()).isEqualTo(initialBackoffMS); // ensure backoff time is initial after the first failure clock.advanceTime(resetBackoffThresholdMS + 1, TimeUnit.MILLISECONDS); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); assertThat(restartStrategy.canRestart()).isTrue(); assertThat(restartStrategy.getBackoffTime()).isEqualTo(initialBackoffMS); // ensure backoff increases until threshold is reached clock.advanceTime(4, TimeUnit.MILLISECONDS); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); assertThat(restartStrategy.canRestart()).isTrue(); assertThat(restartStrategy.getBackoffTime()).isEqualTo(2L); // ensure backoff is reset after threshold is reached clock.advanceTime(resetBackoffThresholdMS + 9 + 1, TimeUnit.MILLISECONDS); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); assertThat(restartStrategy.canRestart()).isTrue(); assertThat(restartStrategy.getBackoffTime()).isOne(); clock.advanceTime(Duration.ofMillis(maxBackoffMS + 1)); // ensure backoff still increases assertThat(restartStrategy.notifyFailure(failure)).isTrue(); assertThat(restartStrategy.canRestart()).isTrue(); assertThat(restartStrategy.getBackoffTime()).isEqualTo(2L); } @Test void testMergeMultipleExceptionsIntoOneAttempt() { ManualClock clock = new ManualClock(); long initialBackoffMS = 2L; double backoffMultiplier = 2.0d; final long maxBackoffMS = 6L; final long resetBackoffThresholdMS = 80L; final ExponentialDelayRestartBackoffTimeStrategy restartStrategy = new ExponentialDelayRestartBackoffTimeStrategy( clock, initialBackoffMS, maxBackoffMS, backoffMultiplier, resetBackoffThresholdMS, 0.d, 3); // All exceptions merged into one attempt if the time is same. long currentBackOffMs = initialBackoffMS; checkMultipleExceptionsAreMerged(clock, currentBackOffMs, restartStrategy); // After advance time it's a new round, so new exception will be a new attempt. clock.advanceTime(1, TimeUnit.MILLISECONDS); currentBackOffMs *= backoffMultiplier; checkMultipleExceptionsAreMerged(clock, currentBackOffMs, restartStrategy); // After advance time it's a new round, so new exception will be a new attempt. clock.advanceTime(1, TimeUnit.MILLISECONDS); currentBackOffMs = maxBackoffMS; checkMultipleExceptionsAreMerged(clock, currentBackOffMs, restartStrategy); // After advance time it's a new round, and it reaches the maxAttempts. clock.advanceTime(1, TimeUnit.MILLISECONDS); assertThat(restartStrategy.notifyFailure(failure)).isTrue(); assertThat(restartStrategy.canRestart()).isFalse(); } @Test void testMergingExceptionsWorksWithResetting() { ManualClock clock = new ManualClock(); long initialBackoffMS = 2L; double backoffMultiplier = 2.0d; final long maxBackoffMS = 6L; final long resetBackoffThresholdMS = 80L; final ExponentialDelayRestartBackoffTimeStrategy restartStrategy = new ExponentialDelayRestartBackoffTimeStrategy( clock, initialBackoffMS, maxBackoffMS, backoffMultiplier, resetBackoffThresholdMS, 0.d, 3); // Test the merging logic works well after a series of resetting. for (int i = 0; i < 10; i++) { // All exceptions merged into one attempt if the time is same. long currentBackOffMs = initialBackoffMS; checkMultipleExceptionsAreMerged(clock, currentBackOffMs, restartStrategy); // After advance time it's a new round, so new exception will be a new attempt. clock.advanceTime(1, TimeUnit.MILLISECONDS); currentBackOffMs *= backoffMultiplier; checkMultipleExceptionsAreMerged(clock, currentBackOffMs, restartStrategy); // After advance time it's a new round, so new exception will be a new attempt. clock.advanceTime(1, TimeUnit.MILLISECONDS); currentBackOffMs = maxBackoffMS; checkMultipleExceptionsAreMerged(clock, currentBackOffMs, restartStrategy); // After resetBackoffThresholdMS, the restartStrategy should be reset. clock.advanceTime(resetBackoffThresholdMS, TimeUnit.MILLISECONDS); } } private void checkMultipleExceptionsAreMerged( ManualClock clock, long expectedBackoffMS, ExponentialDelayRestartBackoffTimeStrategy restartStrategy) { boolean expectedNewAttempt = true; for (int advanceMs = 0; advanceMs < expectedBackoffMS; advanceMs++) { for (int i = 0; i < 10; i++) { assertThat(restartStrategy.notifyFailure(failure)).isEqualTo(expectedNewAttempt); if (expectedNewAttempt) { // Only the first one is new attempt, all rest of failures aren't new attempt. expectedNewAttempt = false; } assertThat(restartStrategy.canRestart()).isTrue(); assertThat(restartStrategy.getBackoffTime()) .isEqualTo(expectedBackoffMS - advanceMs); } clock.advanceTime(1, TimeUnit.MILLISECONDS); } } private void assertCorrectRandomRange(Callable<Long> numberGenerator, Long... expectedNumbers) throws Exception { Set<Long> generatedNumbers = new HashSet<>(); for (int i = 0; i < 1000; i++) { long generatedNumber = numberGenerator.call(); generatedNumbers.add(generatedNumber); } assertThat(generatedNumbers).isEqualTo(new HashSet<>(Arrays.asList(expectedNumbers))); } }
ExponentialDelayRestartBackoffTimeStrategyTest
java
apache__flink
flink-connectors/flink-connector-datagen/src/main/java/org/apache/flink/connector/datagen/functions/FromElementsGeneratorFunction.java
{ "start": 2256, "end": 7543 }
class ____<OUT> implements GeneratorFunction<Long, OUT>, OutputTypeConfigurable<OUT> { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(FromElementsGeneratorFunction.class); /** The (de)serializer to be used for the data elements. */ private @Nullable TypeSerializer<OUT> serializer; /** The actual data elements, in serialized form. */ private byte[] elementsSerialized; /** The number of elements emitted already. */ private int numElementsEmitted; private transient Iterable<OUT> elements; private transient DataInputView input; @SafeVarargs public FromElementsGeneratorFunction(TypeInformation<OUT> typeInfo, OUT... elements) { this(typeInfo, new ExecutionConfig(), Arrays.asList(elements)); } public FromElementsGeneratorFunction( TypeInformation<OUT> typeInfo, ExecutionConfig config, Iterable<OUT> elements) { // must not have null elements and mixed elements checkIterable(elements, typeInfo.getTypeClass()); this.serializer = typeInfo.createSerializer(config.getSerializerConfig()); this.elements = elements; trySerialize(elements); } @VisibleForTesting @Nullable public TypeSerializer<OUT> getSerializer() { return serializer; } private void serializeElements(Iterable<OUT> elements) throws IOException { Preconditions.checkState(serializer != null, "serializer not set"); LOG.info("Serializing elements using {}", serializer); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputViewStreamWrapper wrapper = new DataOutputViewStreamWrapper(baos); try { for (OUT element : elements) { serializer.serialize(element, wrapper); } } catch (Exception e) { throw new IOException("Serializing the source elements failed: " + e.getMessage(), e); } this.elementsSerialized = baos.toByteArray(); } @Override public void open(SourceReaderContext readerContext) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(elementsSerialized); this.input = new DataInputViewStreamWrapper(bais); } @Override public OUT map(Long nextIndex) throws Exception { // Move iterator to the required position in case of failure recovery while (numElementsEmitted < nextIndex) { numElementsEmitted++; tryDeserialize(serializer, input); } numElementsEmitted++; return tryDeserialize(serializer, input); } private OUT tryDeserialize(TypeSerializer<OUT> serializer, DataInputView input) throws IOException { try { return serializer.deserialize(input); } catch (EOFException eof) { throw new NoSuchElementException( "Reached the end of the collection. This could be caused by issues with the serializer or by calling the map() function more times than there are elements in the collection. Make sure that you set the number of records to be produced by the DataGeneratorSource equal to the number of elements in the collection."); } catch (Exception e) { throw new IOException( "Failed to deserialize an element from the source. " + "If you are using user-defined serialization (Value and Writable types), check the " + "serialization functions.\nSerializer is " + serializer, e); } } // For backward compatibility: Supports legacy usage of // StreamExecutionEnvironment#fromElements() which lacked type information and relied on the // returns() method. See FLINK-21386 for details. @Override public void setOutputType(TypeInformation<OUT> outTypeInfo, ExecutionConfig executionConfig) { Preconditions.checkState( elements != null, "The output type should've been specified before shipping the graph to the cluster"); checkIterable(elements, outTypeInfo.getTypeClass()); TypeSerializer<OUT> newSerializer = outTypeInfo.createSerializer(executionConfig.getSerializerConfig()); if (Objects.equals(serializer, newSerializer)) { return; } serializer = newSerializer; try { serializeElements(elements); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } private void trySerialize(Iterable<OUT> elements) { try { serializeElements(elements); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } // ------------------------------------------------------------------------ // Utilities // ------------------------------------------------------------------------ /** * Verifies that all elements in the iterable are non-null, and are of the given class, or a * subclass thereof. * * @param elements The iterable to check. * @param viewedAs The
FromElementsGeneratorFunction
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/StateBackendLoader.java
{ "start": 18467, "end": 18547 }
class ____ not meant to be instantiated. */ private StateBackendLoader() {} }
is
java
mapstruct__mapstruct
integrationtest/src/test/resources/targetTypeGenerationTest/generator/src/main/java/org/mapstruct/itest/targettypegeneration/DtoGenerationProcessor.java
{ "start": 1427, "end": 2319 }
class ____ {" ); writer.append( "\n" ); writer.append( " private String item;" ); writer.append( "\n" ); writer.append( " public String getItem() {" ); writer.append( " return item;" ); writer.append( " }" ); writer.append( "\n" ); writer.append( " public void setItem(String item) {" ); writer.append( " this.item = item;" ); writer.append( " }" ); writer.append( "}" ); writer.flush(); writer.close(); } catch (IOException e) { throw new RuntimeException( e ); } hasRun = true; } return false; } }
OrderDto
java
google__auto
common/src/test/java/com/google/auto/common/MoreElementsTest.java
{ "start": 15053, "end": 19249 }
class ____<M extends AbstractMessageLite<M, B>, B extends Builder<M, B>> { @SuppressWarnings("unchecked") B internalMergeFrom(M other) { return (B) this; } } } @Test public void getAllMethods() { Types types = compilation.getTypes(); TypeMirror intMirror = types.getPrimitiveType(TypeKind.INT); TypeMirror longMirror = types.getPrimitiveType(TypeKind.LONG); TypeElement childType = elements.getTypeElement(Child.class.getCanonicalName()); @SuppressWarnings("deprecation") Set<ExecutableElement> childTypeMethods = MoreElements.getAllMethods(childType, types, elements); Set<ExecutableElement> objectMethods = allMethodsFromObject(); assertThat(childTypeMethods).containsAtLeastElementsIn(objectMethods); Set<ExecutableElement> nonObjectMethods = Sets.difference(childTypeMethods, objectMethods); assertThat(nonObjectMethods) .containsExactly( getMethod(ParentInterface.class, "staticMethod"), getMethod(ParentInterface.class, "bar", longMirror), getMethod(ParentClass.class, "staticMethod"), getMethod(ParentClass.class, "foo"), getMethod(ParentClass.class, "privateMethod"), getMethod(Child.class, "staticMethod"), getMethod(Child.class, "bar"), getMethod(Child.class, "baz"), getMethod(Child.class, "buh", intMirror), getMethod(Child.class, "buh", intMirror, intMirror)) .inOrder(); } private Set<ExecutableElement> visibleMethodsFromObject() { Types types = compilation.getTypes(); TypeMirror intMirror = types.getPrimitiveType(TypeKind.INT); TypeMirror longMirror = types.getPrimitiveType(TypeKind.LONG); Set<ExecutableElement> methods = new HashSet<ExecutableElement>(); for (ExecutableElement method : ElementFilter.methodsIn(objectElement.getEnclosedElements())) { if (method.getModifiers().contains(Modifier.PUBLIC) || method.getModifiers().contains(Modifier.PROTECTED)) { methods.add(method); } } assertThat(methods) .containsAtLeast( getMethod(Object.class, "clone"), getMethod(Object.class, "finalize"), getMethod(Object.class, "wait"), getMethod(Object.class, "wait", longMirror), getMethod(Object.class, "wait", longMirror, intMirror)); return methods; } private Set<ExecutableElement> allMethodsFromObject() { Types types = compilation.getTypes(); TypeMirror intMirror = types.getPrimitiveType(TypeKind.INT); TypeMirror longMirror = types.getPrimitiveType(TypeKind.LONG); Set<ExecutableElement> methods = new HashSet<>(); methods.addAll(ElementFilter.methodsIn(objectElement.getEnclosedElements())); assertThat(methods) .containsAtLeast( getMethod(Object.class, "clone"), getMethod(Object.class, "finalize"), getMethod(Object.class, "wait"), getMethod(Object.class, "wait", longMirror), getMethod(Object.class, "wait", longMirror, intMirror)); return methods; } private ExecutableElement getMethod(Class<?> c, String methodName, TypeMirror... parameterTypes) { TypeElement type = elements.getTypeElement(c.getCanonicalName()); Types types = compilation.getTypes(); ExecutableElement found = null; for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) { if (method.getSimpleName().contentEquals(methodName) && method.getParameters().size() == parameterTypes.length) { boolean match = true; for (int i = 0; i < parameterTypes.length; i++) { TypeMirror expectedType = parameterTypes[i]; TypeMirror actualType = method.getParameters().get(i).asType(); match &= types.isSameType(types.erasure(expectedType), types.erasure(actualType)); } if (match) { assertThat(found).isNull(); found = method; } } } assertWithMessage(methodName + Arrays.toString(parameterTypes)).that(found).isNotNull(); return requireNonNull(found); } private abstract static
Builder
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/util/UriBuilderFactory.java
{ "start": 959, "end": 1322 }
interface ____ extends UriTemplateHandler { /** * Initialize a builder with the given URI template. * @param uriTemplate the URI template to use * @return the builder instance */ UriBuilder uriString(String uriTemplate); /** * Create a URI builder with default settings. * @return the builder instance */ UriBuilder builder(); }
UriBuilderFactory
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-mawo/hadoop-yarn-applications-mawo-core/src/test/java/org/apache/hadoop/applications/mawo/server/common/TestMaWoConfiguration.java
{ "start": 1069, "end": 2035 }
class ____ { /** * Validate default MaWo Configurations. */ @Test void testMaWoConfiguration() { MawoConfiguration mawoConf = new MawoConfiguration(); // validate Rpc server port assertEquals(5120, mawoConf.getRpcServerPort()); // validate Rpc hostname assertEquals("localhost", mawoConf.getRpcHostName()); // validate job queue storage conf boolean jobQueueStorage = mawoConf.getJobQueueStorageEnabled(); assertTrue(jobQueueStorage); // validate default teardownWorkerValidity Interval assertEquals(120000, mawoConf.getTeardownWorkerValidityInterval()); // validate Zk related configs assertEquals("/tmp/mawoRoot", mawoConf.getZKParentPath()); assertEquals("localhost:2181", mawoConf.getZKAddress()); assertEquals(1000, mawoConf.getZKRetryIntervalMS()); assertEquals(10000, mawoConf.getZKSessionTimeoutMS()); assertEquals(1000, mawoConf.getZKRetriesNum()); } }
TestMaWoConfiguration
java
elastic__elasticsearch
x-pack/plugin/security/qa/consistency-checks/src/test/java/org/elasticsearch/xpack/security/CrossClusterShardTests.java
{ "start": 2407, "end": 2790 }
class ____ extends ESSingleNodeTestCase { Set<String> MANUALLY_CHECKED_SHARD_ACTIONS = Set.of( // The request types for these actions are all subtypes of SingleShardRequest, and have been evaluated to make sure their // `shards()` methods return the correct thing. TransportSearchShardsAction.NAME, // These types have had the
CrossClusterShardTests
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/DummyDataCountsReporter.java
{ "start": 884, "end": 2382 }
class ____ extends DataCountsReporter { int logStatusCallCount = 0; DummyDataCountsReporter() { super(createJob(), new DataCounts("DummyJobId"), mock(JobDataCountsPersister.class)); } /** * It's difficult to use mocking to get the number of calls to {@link #logStatus(long)} * and Mockito.spy() doesn't work due to the lambdas used in {@link DataCountsReporter}. * Override the method here an count the calls */ @Override protected boolean logStatus(long totalRecords) { boolean messageLogged = super.logStatus(totalRecords); if (messageLogged) { ++logStatusCallCount; } return messageLogged; } /** * @return Then number of times {@link #logStatus(long)} was called. */ public int getLogStatusCallCount() { return logStatusCallCount; } private static Job createJob() { AnalysisConfig.Builder acBuilder = new AnalysisConfig.Builder(Arrays.asList(new Detector.Builder("metric", "field").build())); acBuilder.setBucketSpan(TimeValue.timeValueSeconds(300)); acBuilder.setLatency(TimeValue.ZERO); acBuilder.setDetectors(Arrays.asList(new Detector.Builder("metric", "field").build())); Job.Builder builder = new Job.Builder("dummy_job_id"); builder.setDataDescription(new DataDescription.Builder()); builder.setAnalysisConfig(acBuilder); return builder.build(new Date()); } }
DummyDataCountsReporter
java
apache__camel
components/camel-file/src/main/java/org/apache/camel/component/file/FileOperations.java
{ "start": 2045, "end": 23481 }
class ____ implements GenericFileOperations<File> { private static final Logger LOG = LoggerFactory.getLogger(FileOperations.class); private final Lock lock = new ReentrantLock(); private FileEndpoint endpoint; public FileOperations() { } public FileOperations(FileEndpoint endpoint) { this.endpoint = endpoint; } @Override public GenericFile<File> newGenericFile() { return new GenericFile<>(); } @Override public void setEndpoint(GenericFileEndpoint<File> endpoint) { this.endpoint = (FileEndpoint) endpoint; } @Override public boolean deleteFile(String name) throws GenericFileOperationFailedException { File file = new File(name); return FileUtil.deleteFile(file); } @Override public boolean renameFile(String from, String to) throws GenericFileOperationFailedException { boolean renamed; File file = new File(from); File target = new File(to); try { if (endpoint.isRenameUsingCopy()) { renamed = FileUtil.renameFileUsingCopy(file, target); } else { renamed = FileUtil.renameFile(file, target, endpoint.isCopyAndDeleteOnRenameFail()); } } catch (IOException e) { throw new GenericFileOperationFailedException("Error renaming file from " + from + " to " + to, e); } return renamed; } @Override public boolean existsFile(String name) throws GenericFileOperationFailedException { File file = new File(name); return file.exists(); } protected boolean buildDirectory(File dir, Set<PosixFilePermission> permissions, boolean absolute, boolean stepwise) { if (dir.exists()) { return true; } boolean hasPermissions = permissions != null && !permissions.isEmpty(); if (!stepwise && !hasPermissions) { return dir.mkdirs(); } // create directory one part of a time and set permissions try { String[] parts = dir.getPath().split("\\" + File.separatorChar); File base; // reusing absolute flag to handle relative and absolute paths if (absolute) { base = new File(""); } else { base = new File("."); } for (String part : parts) { File subDir = new File(base, part); if (!subDir.exists()) { if (subDir.mkdir()) { if (hasPermissions) { if (LOG.isTraceEnabled()) { LOG.trace("Setting chmod: {} on directory: {}", PosixFilePermissions.toString(permissions), subDir); } Files.setPosixFilePermissions(subDir.toPath(), permissions); } } else { return false; } } base = new File(base, subDir.getName()); } } catch (IOException e) { throw new GenericFileOperationFailedException("Error setting chmod on directory: " + dir, e); } return true; } @Override public boolean buildDirectory(String directory, boolean absolute) throws GenericFileOperationFailedException { ObjectHelper.notNull(endpoint, "endpoint"); // always create endpoint defined directory if (endpoint.isAutoCreate() && !endpoint.getFile().exists()) { LOG.trace("Building starting directory: {}", endpoint.getFile()); buildDirectory(endpoint.getFile(), endpoint.getDirectoryPermissions(), absolute, endpoint.isAutoCreateStepwise()); } if (ObjectHelper.isEmpty(directory)) { // no directory to build so return true to indicate ok return true; } File endpointPath = endpoint.getFile(); File target = new File(directory); // check if directory is a path boolean isPath = directory.contains("/") || directory.contains("\\"); File path; if (absolute) { // absolute path path = target; } else if (endpointPath.equals(target)) { // its just the root of the endpoint path path = endpointPath; } else if (isPath) { // relative after the endpoint path String afterRoot = StringHelper.after(directory, endpointPath.getPath() + File.separator); if (ObjectHelper.isNotEmpty(afterRoot)) { // dir is under the root path path = new File(endpoint.getFile(), afterRoot); } else { // dir path is relative to the root path path = new File(directory); } } else { // dir is a child of the root path path = new File(endpoint.getFile(), directory); } // We need to make sure that this is thread-safe and only one thread // tries to create the path directory at the same time. lock.lock(); try { if (path.isDirectory() && path.exists()) { // the directory already exists return true; } else { LOG.trace("Building directory: {}", path); return buildDirectory(path, endpoint.getDirectoryPermissions(), absolute, endpoint.isAutoCreateStepwise()); } } finally { lock.unlock(); } } @Override public File[] listFiles() throws GenericFileOperationFailedException { // noop return null; } @Override public File[] listFiles(String path) throws GenericFileOperationFailedException { // noop return null; } @Override public void changeCurrentDirectory(String path) throws GenericFileOperationFailedException { // noop } @Override public void changeToParentDirectory() throws GenericFileOperationFailedException { // noop } @Override public String getCurrentDirectory() throws GenericFileOperationFailedException { // noop return null; } @Override public boolean retrieveFile(String name, Exchange exchange, long size) throws GenericFileOperationFailedException { // noop as we use type converters to read the body content for // java.io.File return true; } @Override public void releaseRetrievedFileResources(Exchange exchange) throws GenericFileOperationFailedException { // noop as we used type converters to read the body content for // java.io.File } @Override public boolean storeFile(String fileName, Exchange exchange, long size) throws GenericFileOperationFailedException { ObjectHelper.notNull(endpoint, "endpoint"); File file = new File(fileName); // if an existing file already exists what should we do? if (file.exists()) { if (applyExistingFilePolicy(fileName, file)) { return true; } } // Do an explicit test for a null body and decide what to do if (exchange.getIn().getBody() == null) { return handleNullBody(file); } // we can write the file by 3 different techniques // 1. write file to file // 2. rename a file from a local work path // 3. write stream to file try { // is there an explicit charset configured we must write the file as String charset = endpoint.getCharset(); // we can optimize and use file based if no charset must be used, // and the input body is a file // however optimization cannot be applied when content should be // appended to target file File source = null; boolean fileBased = false; if (charset == null && endpoint.getFileExist() != GenericFileExist.Append) { // if no charset and not in appending mode, then we can try // using file directly (optimized) final Object body = extractBodyFromExchange(exchange); if (body instanceof File fileBody) { source = fileBody; fileBased = true; } } if (fileBased) { // okay we know the body is a file based // so try to see if we can optimize by renaming the local work // path file instead of doing // a full file to file copy, as the local work copy is to be // deleted afterwards anyway // local work path if (handleFileAsFileSource(exchange, file, source)) { return true; } } if (charset != null) { // charset configured so we must use a reader so we can write // with encoding handleReaderAsFileSource(exchange, file, charset); } else if (exchange.getIn().getBody() instanceof String) { // If the body is a string, write it directly handleStringAsFileSource(exchange, file); } else { // fallback and use stream based handleStreamAsFileSource(exchange, file); } // try to keep last modified timestamp if configured to do so keepLastModified(exchange, file); // set permissions if the chmod option was set setPermissions(file); return true; } catch (InvalidPayloadException | IOException e) { throw new GenericFileOperationFailedException("Cannot store file: " + file, e); } } private void handleStreamAsFileSource(Exchange exchange, File file) throws InvalidPayloadException, IOException { InputStream in = exchange.getIn().getMandatoryBody(InputStream.class); writeFileByStream(in, file); } private void handleStringAsFileSource(Exchange exchange, File file) throws IOException { String stringBody = (String) exchange.getIn().getBody(); writeFileByString(stringBody, file); } private void handleReaderAsFileSource(Exchange exchange, File file, String charset) throws InvalidPayloadException, IOException { Reader in = exchange.getContext().getTypeConverter().tryConvertTo(Reader.class, exchange, exchange.getIn().getBody()); if (in == null) { // okay no direct reader conversion, so use an input stream // (which a lot can be converted as) InputStream is = exchange.getIn().getMandatoryBody(InputStream.class); in = new InputStreamReader(is); } // buffer the reader in = IOHelper.buffered(in); writeFileByReaderWithCharset(in, file, charset); } private boolean handleFileAsFileSource(Exchange exchange, File file, File source) throws IOException { String local = exchange.getIn().getHeader(FileConstants.FILE_LOCAL_WORK_PATH, String.class); if (local != null) { File f = new File(local); if (f.exists()) { boolean renamed = writeFileByLocalWorkPath(f, file); if (renamed) { // try to keep last modified timestamp if configured to // do so keepLastModified(exchange, file); // set permissions if the chmod option was set setPermissions(file); // clear header as we have renamed the file exchange.getIn().setHeader(FileConstants.FILE_LOCAL_WORK_PATH, null); // return as the operation is complete, we just renamed // the local work file // to the target. return true; } } } else if (source != null && source.exists()) { // no there is no local work file so use file to file copy // if the source exists writeFileByFile(source, file, exchange); // try to keep last modified timestamp if configured to do // so keepLastModified(exchange, file); // set permissions if the chmod option was set setPermissions(file); return true; } return false; } private static Object extractBodyFromExchange(Exchange exchange) { Object body = exchange.getIn().getBody(); if (body instanceof WrappedFile<?> wrapped) { body = wrapped.getFile(); if (!(body instanceof File)) { // the wrapped file may be from remote (FTP) which then can store // a local java.io.File handle if storing to local work-dir so check for that Object maybeFile = wrapped.getBody(); if (maybeFile instanceof File) { body = maybeFile; } } } return body; } private boolean handleNullBody(File file) { if (endpoint.isAllowNullBody()) { LOG.trace("Writing empty file."); try { writeFileEmptyBody(file); return true; } catch (IOException e) { throw new GenericFileOperationFailedException("Cannot store file: " + file, e); } } else { throw new GenericFileOperationFailedException("Cannot write null body to file: " + file); } } private boolean applyExistingFilePolicy(String fileName, File file) { if (endpoint.getFileExist() == GenericFileExist.Ignore) { // ignore but indicate that the file was written LOG.trace("An existing file already exists: {}. Ignore and do not override it.", file); return true; } else if (endpoint.getFileExist() == GenericFileExist.Fail) { throw new GenericFileOperationFailedException("File already exist: " + file + ". Cannot write new file."); } else if (endpoint.getFileExist() == GenericFileExist.Move) { // move any existing file first this.endpoint.getMoveExistingFileStrategy().moveExistingFile(endpoint, this, fileName); } return false; } private void setPermissions(File file) throws IOException { if (ObjectHelper.isNotEmpty(endpoint.getChmod())) { Set<PosixFilePermission> permissions = endpoint.getPermissions(); if (!permissions.isEmpty()) { if (LOG.isTraceEnabled()) { LOG.trace("Setting chmod: {} on file: {}", PosixFilePermissions.toString(permissions), file); } Files.setPosixFilePermissions(file.toPath(), permissions); } } } private void keepLastModified(Exchange exchange, File file) { if (endpoint.isKeepLastModified()) { Long last; Date date = exchange.getIn().getHeader(FileConstants.FILE_LAST_MODIFIED, Date.class); if (date != null) { last = date.getTime(); } else { // fallback and try a long last = exchange.getIn().getHeader(FileConstants.FILE_LAST_MODIFIED, Long.class); } if (last != null) { boolean result = file.setLastModified(last); if (LOG.isTraceEnabled()) { LOG.trace("Keeping last modified timestamp: {} on file: {} with result: {}", last, file, result); } } } } private boolean writeFileByLocalWorkPath(File source, File file) throws IOException { LOG.trace("writeFileByFile using local work file being renamed from: {} to: {}", source, file); return FileUtil.renameFile(source, file, endpoint.isCopyAndDeleteOnRenameFail()); } private void writeFileByFile(File source, File target, Exchange exchange) throws IOException { // in case we are using file locks as read-locks then we need to use // file channels for copying to support this String path = source.getAbsolutePath(); FileChannel channel = exchange.getProperty(asExclusiveReadLockKey(path, Exchange.FILE_LOCK_CHANNEL_FILE), FileChannel.class); if (channel != null) { try (FileOutputStream fos = new FileOutputStream(target); FileChannel out = fos.getChannel()) { LOG.trace("writeFileByFile using FileChannel: {} -> {}", source, target); channel.transferTo(0, channel.size(), out); } } else { // use regular file copy LOG.trace("writeFileByFile using Files.copy: {} -> {}", source, target); Files.copy(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); } } private void writeFileByStream(InputStream in, File target) throws IOException { try (SeekableByteChannel out = prepareOutputFileChannel(target)) { LOG.debug("Using InputStream to write file: {}", target); int size = endpoint.getBufferSize(); byte[] buffer = new byte[size]; ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { if (bytesRead < size) { ((Buffer) byteBuffer).limit(bytesRead); } out.write(byteBuffer); ((Buffer) byteBuffer).clear(); } boolean append = endpoint.getFileExist() == GenericFileExist.Append; if (append && endpoint.getAppendChars() != null) { byteBuffer = ByteBuffer.wrap(endpoint.getAppendChars().getBytes()); out.write(byteBuffer); Buffer buf = byteBuffer; buf.clear(); } } finally { IOHelper.close(in, target.getName(), LOG); } } private void writeFileByReaderWithCharset(Reader in, File target, String charset) throws IOException { boolean append = endpoint.getFileExist() == GenericFileExist.Append; try (Writer out = Files.newBufferedWriter(target.toPath(), Charset.forName(charset), StandardOpenOption.WRITE, append ? StandardOpenOption.APPEND : StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE)) { LOG.debug("Using Reader to write file: {} with charset: {}", target, charset); int size = endpoint.getBufferSize(); IOHelper.copy(in, out, size); if (append && endpoint.getAppendChars() != null) { out.write(endpoint.getAppendChars()); } } finally { IOHelper.close(in, target.getName(), LOG); } } private void writeFileByString(String body, File target) throws IOException { boolean append = endpoint.getFileExist() == GenericFileExist.Append; Files.writeString(target.toPath(), body, StandardOpenOption.WRITE, append ? StandardOpenOption.APPEND : StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); if (append && endpoint.getAppendChars() != null) { Files.writeString(target.toPath(), endpoint.getAppendChars(), StandardOpenOption.WRITE, StandardOpenOption.APPEND); } } /** * Creates a new file if the file doesn't exist. If the endpoint's existing file logic is set to 'Override' then the * target file will be truncated */ private void writeFileEmptyBody(File target) throws IOException { if (!target.exists()) { LOG.debug("Creating new empty file: {}", target); FileUtil.createNewFile(target); } else if (endpoint.getFileExist() == GenericFileExist.Override) { LOG.debug("Truncating existing file: {}", target); Files.write(target.toPath(), new byte[0], StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); } } /** * Creates and prepares the output file channel. Will position itself in correct position if the file is writable * eg. it should append or override any existing content. * * NOTE: the client of this factory method is in charge to close the resource. */ private SeekableByteChannel prepareOutputFileChannel(File target) throws IOException { if (endpoint.getFileExist() == GenericFileExist.Append) { // NOTE: we open the channel and seek the position at the end of the channel. As we return // this stream, we must not close it (letting the client doing so). SeekableByteChannel out = Files.newByteChannel(target.toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); // NOSONAR return out.position(out.size()); } return Files.newByteChannel(target.toPath(), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } }
FileOperations
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/S3AFileSystem.java
{ "start": 18896, "end": 55494 }
class ____ problems. */ private static final LogExactlyOnce STORAGE_CLASS_WARNING = new LogExactlyOnce(LOG); private String cannedACL; /** * This must never be null; until initialized it just declares that there * is no encryption. */ private EncryptionSecrets encryptionSecrets = new EncryptionSecrets(); /** The core instrumentation. */ private S3AInstrumentation instrumentation; /** Accessors to statistics for this FS. */ private S3AStatisticsContext statisticsContext; /** Storage Statistics Bonded to the instrumentation. */ private S3AStorageStatistics storageStatistics; /** * Performance flags. */ private FlagSet<PerformanceFlagEnum> performanceFlags; /** * Default input policy; may be overridden in * {@code openFile()}. */ private S3AInputPolicy inputPolicy; /** Vectored IO context. */ private VectoredIOContext vectoredIOContext; private long readAhead; private ChangeDetectionPolicy changeDetectionPolicy; private final AtomicBoolean closed = new AtomicBoolean(false); private volatile boolean isClosed = false; /** Delegation token integration; non-empty when DT support is enabled. */ private Optional<S3ADelegationTokens> delegationTokens = Optional.empty(); /** Principal who created the FS; recorded during initialization. */ private UserGroupInformation owner; private String blockOutputBuffer; private S3ADataBlocks.BlockFactory blockFactory; private int blockOutputActiveBlocks; private boolean useListV1; private MagicCommitIntegration committerIntegration; private AWSCredentialProviderList credentials; private SignerManager signerManager; private S3AInternals s3aInternals; /** * Do directory operations purge pending uploads? */ private boolean dirOperationsPurgeUploads; /** * Page size for deletions. */ private int pageSize; private final ListingOperationCallbacks listingOperationCallbacks = new ListingOperationCallbacksImpl(); /** * Helper for the openFile() method. */ private OpenFileSupport openFileHelper; /** * Context accessors for re-use. */ private final ContextAccessors contextAccessors = new ContextAccessorsImpl(); /** * Factory for AWS requests. */ private RequestFactory requestFactory; /** * Audit manager (service lifecycle). * Creates the audit service and manages the binding of different audit spans * to different threads. * Initially this is a no-op manager; once the service is initialized it will * be replaced with a configured one. */ private AuditManagerS3A auditManager = AuditIntegration.stubAuditManager(); /** * Is this S3A FS instance using S3 client side encryption? */ private boolean isCSEEnabled; /** * Is this S3A FS instance using analytics accelerator? */ private boolean isAnalyticsAcceleratorEnabled; /** * Bucket AccessPoint. */ private ArnResource accessPoint; /** * Handler for certain filesystem operations. */ private S3AFileSystemOperations fsHandler; /** * Does this S3A FS instance have multipart upload enabled? */ private boolean isMultipartUploadEnabled = DEFAULT_MULTIPART_UPLOAD_ENABLED; /** * Should file copy operations use the S3 transfer manager? * True unless multipart upload is disabled. */ private boolean isMultipartCopyEnabled; /** * Is FIPS enabled? */ private boolean fipsEnabled; /** * A cache of files that should be deleted when the FileSystem is closed * or the JVM is exited. */ private final Set<Path> deleteOnExit = new TreeSet<>(); /** * Scheme for the current filesystem. */ private String scheme = FS_S3A; /** * Flag to indicate that the higher performance copyFromLocalFile implementation * should be used. */ private boolean optimizedCopyFromLocal; /** * Is this an S3 Express store? */ private boolean s3ExpressStore; /** * Store endpoint from configuration info or access point ARN. */ private String endpoint; /** * Region from configuration info or access point ARN. */ private String configuredRegion; /** * Are S3 Access Grants Enabled? */ private boolean s3AccessGrantsEnabled; /** * Are the conditional create operations enabled? */ private boolean conditionalCreateEnabled; /** Add any deprecated keys. */ @SuppressWarnings("deprecation") private static void addDeprecatedKeys() { Configuration.DeprecationDelta[] deltas = { new Configuration.DeprecationDelta( FS_S3A_COMMITTER_STAGING_ABORT_PENDING_UPLOADS, FS_S3A_COMMITTER_ABORT_PENDING_UPLOADS), new Configuration.DeprecationDelta( SERVER_SIDE_ENCRYPTION_ALGORITHM, S3_ENCRYPTION_ALGORITHM), new Configuration.DeprecationDelta( SERVER_SIDE_ENCRYPTION_KEY, S3_ENCRYPTION_KEY) }; if (deltas.length > 0) { Configuration.addDeprecations(deltas); Configuration.reloadExistingConfigurations(); } } static { addDeprecatedKeys(); } /** * Initialize the filesystem. * <p> * This is called after a new FileSystem instance is constructed -but * within the filesystem cache creation process. * A slow start here while multiple threads are calling * will result in multiple * instances of the filesystem being created -and all but one deleted. * <i>Keep this as fast as possible, and avoid network IO</i>. * <p> * This performs the majority of the filesystem setup, and as things * are intermixed the ordering of operations is very sensitive. * Be very careful when moving things. * <p> * To help identify where filesystem instances are created, * the full stack is logged at TRACE. * <p> * Also, ignore checkstyle complaints about method length. * @param name a uri whose authority section names the host, port, etc. * for this FileSystem * @param originalConf the configuration to use for the FS. The * bucket-specific options are patched over the base ones before any use is * made of the config. */ public void initialize(URI name, Configuration originalConf) throws IOException { // get the host; this is guaranteed to be non-null, non-empty bucket = name.getHost(); AuditSpan span = null; // track initialization duration; will only be set after // statistics are set up. Optional<DurationTracker> trackInitialization = Optional.empty(); try { LOG.debug("Initializing S3AFileSystem for {}", bucket); if (LOG.isTraceEnabled()) { // log a full trace for deep diagnostics of where an object is created, // for tracking down memory leak issues. LOG.trace("Filesystem for {} created; fs.s3a.impl.disable.cache = {}", name, originalConf.getBoolean("fs.s3a.impl.disable.cache", false), new RuntimeException(super.toString())); } // clone the configuration into one with propagated bucket options Configuration conf = propagateBucketOptions(originalConf, bucket); // HADOOP-17894. remove references to s3a stores in JCEKS credentials. conf = ProviderUtils.excludeIncompatibleCredentialProviders( conf, S3AFileSystem.class); String arn = String.format(ARN_BUCKET_OPTION, bucket); String configuredArn = conf.getTrimmed(arn, ""); if (!configuredArn.isEmpty()) { accessPoint = ArnResource.accessPointFromArn(configuredArn); LOG.info("Using AccessPoint ARN \"{}\" for bucket {}", configuredArn, bucket); bucket = accessPoint.getFullArn(); } else if (conf.getBoolean(AWS_S3_ACCESSPOINT_REQUIRED, false)) { LOG.warn("Access Point usage is required because \"{}\" is enabled," + " but not configured for the bucket: {}", AWS_S3_ACCESSPOINT_REQUIRED, bucket); throw new PathIOException(bucket, AP_REQUIRED_EXCEPTION); } // fix up the classloader of the configuration to be whatever // classloader loaded this filesystem. // See: HADOOP-17372 and follow-up on HADOOP-18993 S3AUtils.maybeIsolateClassloader(conf, this.getClass().getClassLoader()); // patch the Hadoop security providers patchSecurityCredentialProviders(conf); // look for delegation token support early. boolean delegationTokensEnabled = hasDelegationTokenBinding(conf); if (delegationTokensEnabled) { LOG.debug("Using delegation tokens"); } // set the URI, this will do any fixup of the URI to remove secrets, // canonicalize. setUri(name, delegationTokensEnabled); super.initialize(uri, conf); setConf(conf); // initialize statistics, after which statistics // can be collected. instrumentation = new S3AInstrumentation(uri); initializeStatisticsBinding(); // track initialization duration. // this should really be done in a onceTrackingDuration() call, // but then all methods below would need to be in the lambda and // it would create a merge/backport headache for all. trackInitialization = Optional.of( instrumentation.trackDuration(FileSystemStatisticNames.FILESYSTEM_INITIALIZATION)); s3aInternals = createS3AInternals(); // look for encryption data // DT Bindings may override this setEncryptionSecrets( buildEncryptionSecrets(bucket, conf)); invoker = new Invoker(new S3ARetryPolicy(getConf()), onRetry); // If encryption method is set to CSE-KMS or CSE-CUSTOM then CSE is enabled. isCSEEnabled = CSEUtils.isCSEEnabled(getS3EncryptionAlgorithm().getMethod()); isAnalyticsAcceleratorEnabled = StreamIntegration.determineInputStreamType(conf) .equals(InputStreamType.Analytics); // Create the appropriate fsHandler instance using a factory method fsHandler = createFileSystemHandler(); fsHandler.setCSEGauge((IOStatisticsStore) getIOStatistics()); // Username is the current user at the time the FS was instantiated. owner = UserGroupInformation.getCurrentUser(); username = owner.getShortUserName(); workingDir = new Path("/user", username) .makeQualified(this.uri, this.getWorkingDirectory()); maxKeys = intOption(conf, MAX_PAGING_KEYS, DEFAULT_MAX_PAGING_KEYS, 1); partSize = getMultipartSizeProperty(conf, MULTIPART_SIZE, DEFAULT_MULTIPART_SIZE); multiPartThreshold = getMultipartSizeProperty(conf, MIN_MULTIPART_THRESHOLD, DEFAULT_MIN_MULTIPART_THRESHOLD); //check but do not store the block size longBytesOption(conf, FS_S3A_BLOCK_SIZE, DEFAULT_BLOCKSIZE, 1); enableMultiObjectsDelete = conf.getBoolean(ENABLE_MULTI_DELETE, true); // determine and cache the endpoints endpoint = accessPoint == null ? conf.getTrimmed(ENDPOINT, DEFAULT_ENDPOINT) : accessPoint.getEndpoint(); configuredRegion = accessPoint == null ? conf.getTrimmed(AWS_REGION) : accessPoint.getRegion(); fipsEnabled = conf.getBoolean(FIPS_ENDPOINT, ENDPOINT_FIPS_DEFAULT); // is this an S3Express store? s3ExpressStore = isS3ExpressStore(bucket, endpoint); // should the delete also purge uploads? dirOperationsPurgeUploads = conf.getBoolean(DIRECTORY_OPERATIONS_PURGE_UPLOADS, DIRECTORY_OPERATIONS_PURGE_UPLOADS_DEFAULT); this.isMultipartUploadEnabled = conf.getBoolean(MULTIPART_UPLOADS_ENABLED, DEFAULT_MULTIPART_UPLOAD_ENABLED); // multipart copy and upload are the same; this just makes it explicit this.isMultipartCopyEnabled = isMultipartUploadEnabled; int listVersion = conf.getInt(LIST_VERSION, DEFAULT_LIST_VERSION); if (listVersion < 1 || listVersion > 2) { LOG.warn("Configured fs.s3a.list.version {} is invalid, forcing " + "version 2", listVersion); } useListV1 = (listVersion == 1); if (accessPoint != null && useListV1) { LOG.warn("V1 list configured in fs.s3a.list.version. This is not supported in by" + " access points. Upgrading to V2"); useListV1 = false; } conditionalCreateEnabled = conf.getBoolean(FS_S3A_CONDITIONAL_CREATE_ENABLED, DEFAULT_FS_S3A_CONDITIONAL_CREATE_ENABLED); signerManager = new SignerManager(bucket, this, conf, owner); signerManager.initCustomSigners(); // start auditing // extra configuration will be passed down later. initializeAuditService(); // create the requestFactory. // requires the audit manager to be initialized. requestFactory = createRequestFactory(); // create an initial span for all other operations. span = createSpan(INITIALIZE_SPAN, bucket, null); // creates the AWS client, including overriding auth chain if // the FS came with a DT // this may do some patching of the configuration (e.g. setting // the encryption algorithms) // requires the audit manager to be initialized. ClientManager clientManager = createClientManager(name, delegationTokensEnabled); inputPolicy = S3AInputPolicy.getPolicy( conf.getTrimmed(INPUT_FADVISE, Options.OpenFileOptions.FS_OPTION_OPENFILE_READ_POLICY_DEFAULT), S3AInputPolicy.Normal); LOG.debug("Input fadvise policy = {}", inputPolicy); changeDetectionPolicy = ChangeDetectionPolicy.getPolicy(conf); LOG.debug("Change detection policy = {}", changeDetectionPolicy); boolean magicCommitterEnabled = conf.getBoolean( CommitConstants.MAGIC_COMMITTER_ENABLED, CommitConstants.DEFAULT_MAGIC_COMMITTER_ENABLED); LOG.debug("Filesystem support for magic committers {} enabled", magicCommitterEnabled ? "is" : "is not"); committerIntegration = new MagicCommitIntegration( this, magicCommitterEnabled); boolean blockUploadEnabled = conf.getBoolean(FAST_UPLOAD, true); if (!blockUploadEnabled) { LOG.warn("The \"slow\" output stream is no longer supported"); } blockOutputBuffer = conf.getTrimmed(FAST_UPLOAD_BUFFER, DEFAULT_FAST_UPLOAD_BUFFER); blockFactory = S3ADataBlocks.createFactory(createStoreContext(), blockOutputBuffer); blockOutputActiveBlocks = intOption(conf, FAST_UPLOAD_ACTIVE_BLOCKS, DEFAULT_FAST_UPLOAD_ACTIVE_BLOCKS, 1); // If CSE is enabled, do multipart uploads serially. if (isCSEEnabled) { blockOutputActiveBlocks = 1; } LOG.debug("Using S3ABlockOutputStream with buffer = {}; block={};" + " queue limit={}; multipart={}", blockOutputBuffer, partSize, blockOutputActiveBlocks, isMultipartUploadEnabled); // verify there's no S3Guard in the store config. checkNoS3Guard(this.getUri(), getConf()); // read in performance options and parse them to a list of flags. performanceFlags = buildFlagSet( PerformanceFlagEnum.class, conf, FS_S3A_PERFORMANCE_FLAGS, true); // performance creation flag for code which wants performance // at the risk of overwrites. // this uses the performance flags as the default and then // updates the performance flags to match. // a bit convoluted. boolean performanceCreation = conf.getBoolean(FS_S3A_CREATE_PERFORMANCE, performanceFlags.enabled(PerformanceFlagEnum.Create)); performanceFlags.set(PerformanceFlagEnum.Create, performanceCreation); // freeze. performanceFlags.makeImmutable(); LOG.debug("{} = {}", FS_S3A_CREATE_PERFORMANCE, performanceCreation); pageSize = intOption(getConf(), BULK_DELETE_PAGE_SIZE, BULK_DELETE_PAGE_SIZE_DEFAULT, 0); checkArgument(pageSize <= InternalConstants.MAX_ENTRIES_TO_DELETE, "page size out of range: %s", pageSize); listing = new Listing(listingOperationCallbacks, createStoreContext()); // now the open file logic openFileHelper = new OpenFileSupport( changeDetectionPolicy, longBytesOption(conf, READAHEAD_RANGE, DEFAULT_READAHEAD_RANGE, 0), username, intOption(conf, IO_FILE_BUFFER_SIZE_KEY, IO_FILE_BUFFER_SIZE_DEFAULT, 0), longBytesOption(conf, ASYNC_DRAIN_THRESHOLD, DEFAULT_ASYNC_DRAIN_THRESHOLD, 0), inputPolicy); scheme = (this.uri != null && this.uri.getScheme() != null) ? this.uri.getScheme() : FS_S3A; optimizedCopyFromLocal = conf.getBoolean(OPTIMIZED_COPY_FROM_LOCAL, OPTIMIZED_COPY_FROM_LOCAL_DEFAULT); LOG.debug("Using optimized copyFromLocal implementation: {}", optimizedCopyFromLocal); s3AccessGrantsEnabled = conf.getBoolean(AWS_S3_ACCESS_GRANTS_ENABLED, false); int rateLimitCapacity = intOption(conf, S3A_IO_RATE_LIMIT, DEFAULT_S3A_IO_RATE_LIMIT, 0); // now create and initialize the store store = createS3AStore(clientManager, rateLimitCapacity); // the s3 client is created through the store, rather than // directly through the client manager. // this is to aid mocking. s3Client = getStore().getOrCreateS3Client(); // get the input stream factory requirements. final StreamFactoryRequirements factoryRequirements = getStore().factoryRequirements(); // If the input stream can issue get requests outside spans, // the auditor is forced to disable rejection of unaudited requests. final EnumSet<AuditorFlags> flags = EnumSet.noneOf(AuditorFlags.class); if (factoryRequirements.requires(ExpectUnauditedGetRequests)) { flags.add(AuditorFlags.PermitOutOfBandOperations); } getAuditManager().setAuditFlags(flags); // get the vector IO context from the factory. vectoredIOContext = factoryRequirements.vectoredIOContext(); // thread pool init requires store to be created and // the stream factory requirements to include its own requirements. initThreadPools(); // The filesystem is now ready to perform operations against // S3 // This initiates a probe against S3 for the bucket existing. doBucketProbing(); initMultipartUploads(conf); trackInitialization.ifPresent(DurationTracker::close); } catch (SdkException e) { // amazon client exception: stop all services then throw the translation cleanupWithLogger(LOG, span); stopAllServices(); trackInitialization.ifPresent(DurationTracker::failed); throw translateException("initializing ", new Path(name), e); } catch (IOException | RuntimeException e) { // other exceptions: stop the services. cleanupWithLogger(LOG, span); stopAllServices(); trackInitialization.ifPresent(DurationTracker::failed); throw e; } } /** * Creates and returns an instance of the appropriate S3AFileSystemOperations. * Creation is baaed on the client-side encryption (CSE) settings. * * @return An instance of the appropriate S3AFileSystemOperations implementation. */ private S3AFileSystemOperations createFileSystemHandler() { if (isCSEEnabled) { if (getConf().getBoolean(S3_ENCRYPTION_CSE_V1_COMPATIBILITY_ENABLED, S3_ENCRYPTION_CSE_V1_COMPATIBILITY_ENABLED_DEFAULT)) { return new CSEV1CompatibleS3AFileSystemOperations(); } else { return new CSES3AFileSystemOperations(); } } else { return new BaseS3AFileSystemOperations(); } } /** * Create and start the S3AStore instance. * This is protected so that tests can override it. * @param clientManager client manager * @param rateLimitCapacity rate limit * @return a new store instance */ @VisibleForTesting protected S3AStore createS3AStore(final ClientManager clientManager, final int rateLimitCapacity) { final S3AStore st = new S3AStoreBuilder() .withAuditSpanSource(getAuditManager()) .withClientManager(clientManager) .withDurationTrackerFactory(getDurationTrackerFactory()) .withFsStatistics(getFsStatistics()) .withInstrumentation(getInstrumentation()) .withStatisticsContext(statisticsContext) .withStoreContextFactory(this) .withStorageStatistics(getStorageStatistics()) .withReadRateLimiter(unlimitedRate()) .withWriteRateLimiter(RateLimitingFactory.create(rateLimitCapacity)) .build(); st.init(getConf()); st.start(); return st; } /** * Test bucket existence in S3. * When the value of {@link Constants#S3A_BUCKET_PROBE} is set to 0, * bucket existence check is not done to improve performance of * S3AFileSystem initialization. When set to 1 or 2, bucket existence check * will be performed which is potentially slow. * If 3 or higher: warn and skip check. * Also logging DNS address of the s3 endpoint if the bucket probe value is * greater than 0 else skipping it for increased performance. * @throws UnknownStoreException the bucket is absent * @throws IOException any other problem talking to S3 */ @Retries.RetryTranslated private void doBucketProbing() throws IOException { int bucketProbe = getConf() .getInt(S3A_BUCKET_PROBE, S3A_BUCKET_PROBE_DEFAULT); Preconditions.checkArgument(bucketProbe >= 0, "Value of " + S3A_BUCKET_PROBE + " should be >= 0"); switch (bucketProbe) { case 0: LOG.debug("skipping check for bucket existence"); break; case 1: case 2: logDnsLookup(getConf()); verifyBucketExists(); break; default: // we have no idea what this is, assume it is from a later release. LOG.warn("Unknown bucket probe option {}: {}; skipping check for bucket existence", S3A_BUCKET_PROBE, bucketProbe); break; } } /** * Initialize the statistics binding. * This is done by creating an {@code IntegratedS3AStatisticsContext} * with callbacks to get the FS's instrumentation and FileSystem.statistics * field; the latter may change after {@link #initialize(URI, Configuration)}, * so needs to be dynamically adapted. * Protected so that (mock) subclasses can replace it with a * different statistics binding, if desired. */ protected void initializeStatisticsBinding() { storageStatistics = createStorageStatistics( requireNonNull(getIOStatistics())); statisticsContext = new BondedS3AStatisticsContext( new BondedS3AStatisticsContext.S3AFSStatisticsSource() { @Override public S3AInstrumentation getInstrumentation() { return S3AFileSystem.this.getInstrumentation(); } @Override public Statistics getInstanceStatistics() { return S3AFileSystem.this.statistics; } }); } /** * Initialize the thread pools. * <p> * This must be re-invoked after replacing the S3Client during test * runs. * <p> * It requires the S3Store to have been instantiated. * @param conf configuration. */ private void initThreadPools() { Configuration conf = getConf(); final String name = "s3a-transfer-" + getBucket(); int maxThreads = conf.getInt(MAX_THREADS, DEFAULT_MAX_THREADS); if (maxThreads < 2) { LOG.warn(MAX_THREADS + " must be at least 2: forcing to 2."); maxThreads = 2; } int totalTasks = intOption(conf, MAX_TOTAL_TASKS, DEFAULT_MAX_TOTAL_TASKS, 1); // keepalive time takes a time suffix; default unit is seconds long keepAliveTime = ConfigurationHelper.getDuration(conf, KEEPALIVE_TIME, Duration.ofSeconds(DEFAULT_KEEPALIVE_TIME), TimeUnit.SECONDS, Duration.ZERO).getSeconds(); final StreamFactoryRequirements factoryRequirements = getStore().factoryRequirements(); int numPrefetchThreads = factoryRequirements.sharedThreads(); int activeTasksForBoundedThreadPool = maxThreads; int waitingTasksForBoundedThreadPool = maxThreads + totalTasks + numPrefetchThreads; boundedThreadPool = BlockingThreadPoolExecutorService.newInstance( activeTasksForBoundedThreadPool, waitingTasksForBoundedThreadPool, keepAliveTime, TimeUnit.SECONDS, name + "-bounded"); unboundedThreadPool = new ThreadPoolExecutor( maxThreads, Integer.MAX_VALUE, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), BlockingThreadPoolExecutorService.newDaemonThreadFactory( name + "-unbounded")); unboundedThreadPool.allowCoreThreadTimeOut(true); executorCapacity = intOption(conf, EXECUTOR_CAPACITY, DEFAULT_EXECUTOR_CAPACITY, 1); if (factoryRequirements.requiresFuturePool()) { // create a future pool. final S3AInputStreamStatistics s3AInputStreamStatistics = statisticsContext.newInputStreamStatistics(); futurePool = new ExecutorServiceFuturePool( new SemaphoredDelegatingExecutor( boundedThreadPool, activeTasksForBoundedThreadPool + waitingTasksForBoundedThreadPool, true, s3AInputStreamStatistics)); } } /** * Create the storage statistics or bind to an existing one. * @param ioStatistics IOStatistics to build the storage statistics from. * @return a storage statistics instance; expected to be that of the FS. */ protected static S3AStorageStatistics createStorageStatistics( final IOStatistics ioStatistics) { return (S3AStorageStatistics) GlobalStorageStatistics.INSTANCE .put(S3AStorageStatistics.NAME, () -> new S3AStorageStatistics(ioStatistics)); } /** * Verify that the bucket exists. * Retry policy: retrying, translated. * @throws UnknownStoreException the bucket is absent * @throws IOException any other problem talking to S3 */ @Retries.RetryTranslated protected void verifyBucketExists() throws UnknownStoreException, IOException { if(!trackDurationAndSpan( STORE_EXISTS_PROBE, bucket, null, () -> invoker.retry("doesBucketExist", bucket, true, () -> { try { getS3Client().headBucket(HeadBucketRequest.builder().bucket(bucket).build()); return true; } catch (AwsServiceException ex) { int statusCode = ex.statusCode(); if (statusCode == SC_404_NOT_FOUND || (statusCode == SC_403_FORBIDDEN && accessPoint != null)) { return false; } } return true; }))) { throw new UnknownStoreException("s3a://" + bucket + "/", " Bucket does " + "not exist. " + "Accessing with " + ENDPOINT + " set to " + getConf().getTrimmed(ENDPOINT, null)); } } /** * Get S3A Instrumentation. For test purposes. * @return this instance's instrumentation. */ @VisibleForTesting public S3AInstrumentation getInstrumentation() { return instrumentation; } /** * Get FS Statistic for this S3AFS instance. * * @return FS statistic instance. */ @VisibleForTesting public FileSystem.Statistics getFsStatistics() { return statistics; } /** * Get current listing instance. * @return this instance's listing. */ public Listing getListing() { return listing; } /** * Set up the client bindings. * If delegation tokens are enabled, the FS first looks for a DT * ahead of any other bindings. * If there is a DT it uses that to do the auth * and switches to the DT authenticator automatically (and exclusively). * <p> * Delegation tokens are configured and started, but the actual * S3 clients are not: instead a {@link ClientManager} is created * and returned, from which they can be created on demand. * This is to reduce delays in FS initialization, especially * for features (transfer manager, async client) which are not * always used. * @param fsURI URI of the FS * @param dtEnabled are delegation tokens enabled? * @return the client manager which can generate the clients. * @throws IOException failure. */ private ClientManager createClientManager(URI fsURI, boolean dtEnabled) throws IOException { Configuration conf = getConf(); credentials = null; String uaSuffix = ""; if (dtEnabled) { // Delegation support. // Create and start the DT integration. // Then look for an existing DT for this bucket, switch to authenticating // with it if so. LOG.debug("Using delegation tokens"); S3ADelegationTokens tokens = new S3ADelegationTokens(); this.delegationTokens = Optional.of(tokens); tokens.bindToFileSystem(getCanonicalUri(), createStoreContext(), createDelegationOperations()); tokens.init(conf); tokens.start(); // switch to the DT provider and bypass all other configured // providers. if (tokens.isBoundToDT()) { // A DT was retrieved. LOG.debug("Using existing delegation token"); // and use the encryption settings from that client, whatever they were } else { LOG.debug("No delegation token for this instance"); } // Get new credential chain credentials = tokens.getCredentialProviders(); // and any encryption secrets which came from a DT tokens.getEncryptionSecrets() .ifPresent(this::setEncryptionSecrets); // and update the UA field with any diagnostics provided by // the DT binding. uaSuffix = tokens.getUserAgentField(); } else { // DT support is disabled, so create the normal credential chain credentials = createAWSCredentialProviderList(fsURI, conf); } LOG.debug("Using credential provider {}", credentials); S3ClientFactory clientFactory = fsHandler.getS3ClientFactory(conf); S3ClientFactory unencryptedClientFactory = fsHandler.getUnencryptedS3ClientFactory(conf); CSEMaterials cseMaterials = fsHandler.getClientSideEncryptionMaterials(conf, bucket, getS3EncryptionAlgorithm()); S3ClientFactory.S3ClientCreationParameters parameters = new S3ClientFactory.S3ClientCreationParameters() .withCredentialSet(credentials) .withPathUri(fsURI) .withEndpoint(endpoint) .withMetrics(statisticsContext.newStatisticsFromAwsSdk()) .withPathStyleAccess(conf.getBoolean(PATH_STYLE_ACCESS, false)) .withUserAgentSuffix(uaSuffix) .withRequesterPays(conf.getBoolean(ALLOW_REQUESTER_PAYS, DEFAULT_ALLOW_REQUESTER_PAYS)) .withExecutionInterceptors(auditManager.createExecutionInterceptors()) .withMinimumPartSize(partSize) .withMultipartCopyEnabled(isMultipartCopyEnabled) .withMultipartThreshold(multiPartThreshold) .withTransferManagerExecutor(unboundedThreadPool) .withRegion(configuredRegion) .withFipsEnabled(fipsEnabled) .withS3ExpressStore(s3ExpressStore) .withExpressCreateSession( conf.getBoolean(S3EXPRESS_CREATE_SESSION, S3EXPRESS_CREATE_SESSION_DEFAULT)) .withChecksumValidationEnabled( conf.getBoolean(CHECKSUM_VALIDATION, CHECKSUM_VALIDATION_DEFAULT)) .withChecksumCalculationEnabled( conf.getBoolean(CHECKSUM_GENERATION, DEFAULT_CHECKSUM_GENERATION)) .withMd5HeaderEnabled(conf.getBoolean(REQUEST_MD5_HEADER, DEFAULT_REQUEST_MD5_HEADER)) .withClientSideEncryptionEnabled(isCSEEnabled) .withClientSideEncryptionMaterials(cseMaterials) .withAnalyticsAcceleratorEnabled(isAnalyticsAcceleratorEnabled) .withKMSRegion(conf.get(S3_ENCRYPTION_CSE_KMS_REGION)); // this is where clients and the transfer manager are created on demand. return createClientManager(clientFactory, unencryptedClientFactory, parameters, getDurationTrackerFactory()); } /** * Create the Client Manager; protected to allow for mocking. * Requires {@link #unboundedThreadPool} to be initialized. * @param clientFactory (reflection-bonded) client factory. * @param unencryptedClientFactory (reflection-bonded) client factory. * @param clientCreationParameters parameters for client creation. * @param durationTrackerFactory factory for duration tracking. * @return a client manager instance. */ @VisibleForTesting protected ClientManager createClientManager( final S3ClientFactory clientFactory, final S3ClientFactory unencryptedClientFactory, final S3ClientFactory.S3ClientCreationParameters clientCreationParameters, final DurationTrackerFactory durationTrackerFactory) { return new ClientManagerImpl(clientFactory, unencryptedClientFactory, clientCreationParameters, durationTrackerFactory ); } /** * Initialize and launch the audit manager and service. * As this takes the FS IOStatistics store, it must be invoked * after instrumentation is initialized. * @throws IOException failure to instantiate/initialize. */ protected void initializeAuditService() throws IOException { auditManager = AuditIntegration.createAndStartAuditManager( getConf(), instrumentation.createMetricsUpdatingStore()); } /** * The audit manager. * @return the audit manager */ @InterfaceAudience.Private public AuditManagerS3A getAuditManager() { return auditManager; } /** * Get the auditor; valid once initialized. * @return the auditor. */ @InterfaceAudience.Private public OperationAuditor getAuditor() { return getAuditManager().getAuditor(); } /** * Get the active audit span. * @return the span. */ @InterfaceAudience.Private @Override public AuditSpanS3A getActiveAuditSpan() { return getAuditManager().getActiveAuditSpan(); } /** * Get the audit span source; allows for components like the committers * to have a source of spans without being hard coded to the FS only. * @return the source of spans -base implementation is this instance. */ @InterfaceAudience.Private public AuditSpanSource getAuditSpanSource() { return this; } /** * Start an operation; this informs the audit service of the event * and then sets it as the active span. * @param operation operation name. * @param path1 first path of operation * @param path2 second path of operation * @return a span for the audit * @throws IOException failure */ public AuditSpanS3A createSpan(String operation, @Nullable String path1, @Nullable String path2) throws IOException { return getAuditManager().createSpan(operation, path1, path2); } /** * Build the request factory. * MUST be called after reading encryption secrets from settings/ * delegation token. * Protected, in case test/mock classes want to implement their * own variants. * @return request factory. */ protected RequestFactory createRequestFactory() { long partCountLimit = longOption(getConf(), UPLOAD_PART_COUNT_LIMIT, DEFAULT_UPLOAD_PART_COUNT_LIMIT, 1); if (partCountLimit != DEFAULT_UPLOAD_PART_COUNT_LIMIT) { LOG.warn("Configuration property {} shouldn't be overridden by client", UPLOAD_PART_COUNT_LIMIT); } // ACLs; this is passed to the // request factory. initCannedAcls(getConf()); // Any encoding type String contentEncoding = getConf().getTrimmed(CONTENT_ENCODING, null); if (contentEncoding != null) { LOG.debug("Using content encoding set in {} = {}", CONTENT_ENCODING, contentEncoding); } String storageClassConf = getConf() .getTrimmed(STORAGE_CLASS, "") .toUpperCase(Locale.US); StorageClass storageClass = null; if (!storageClassConf.isEmpty()) { storageClass = StorageClass.fromValue(storageClassConf); LOG.debug("Using storage class {}", storageClass); if (storageClass.equals(StorageClass.UNKNOWN_TO_SDK_VERSION)) { STORAGE_CLASS_WARNING.warn("Unknown storage class \"{}\" from option: {};" + " falling back to default storage class", storageClassConf, STORAGE_CLASS); storageClass = null; } } else { LOG.debug("Unset storage
configuration
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/lookup/InstanceLookupDependentLifecycleExtensionTest.java
{ "start": 757, "end": 3250 }
class ____ { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .beanClasses(MyService.class, MyDependency.class, MyTransitiveDependency.class) .beanRegistrars(new InvokerHelperRegistrar(MyService.class, (bean, factory, invokers) -> { MethodInfo method = bean.getImplClazz().firstMethod("hello"); invokers.put(method.name(), factory.createInvoker(bean, method) .withInstanceLookup() .build()); })) .build(); @Test public void test() throws Exception { InvokerHelper helper = Arc.container().instance(InvokerHelper.class).get(); Invoker<MyService, CompletionStage<String>> invoker = helper.getInvoker("hello"); assertInvocation(invoker, 0); assertInvocation(invoker, 1); assertInvocation(invoker, 2); } private void assertInvocation(Invoker<MyService, CompletionStage<String>> invoker, int counter) throws Exception { assertEquals(counter, MyService.CREATED); assertEquals(counter, MyService.DESTROYED); assertEquals(counter, MyDependency.CREATED); assertEquals(counter, MyDependency.DESTROYED); assertEquals(counter, MyTransitiveDependency.CREATED); assertEquals(counter, MyTransitiveDependency.DESTROYED); Barrier barrier = new Barrier(); CompletionStage<String> completionStage = invoker.invoke(null, new Object[] { barrier }); assertEquals(counter + 1, MyService.CREATED); assertEquals(counter, MyService.DESTROYED); assertEquals(counter + 1, MyDependency.CREATED); assertEquals(counter, MyDependency.DESTROYED); assertEquals(counter + 1, MyTransitiveDependency.CREATED); assertEquals(counter, MyTransitiveDependency.DESTROYED); barrier.open(); String result = completionStage.toCompletableFuture().get(); assertEquals("foobar" + counter + "_" + counter + "_" + counter, result); assertEquals(counter + 1, MyService.CREATED); assertEquals(counter + 1, MyService.DESTROYED); assertEquals(counter + 1, MyDependency.CREATED); assertEquals(counter + 1, MyDependency.DESTROYED); assertEquals(counter + 1, MyTransitiveDependency.CREATED); assertEquals(counter + 1, MyTransitiveDependency.DESTROYED); } @Dependent static
InstanceLookupDependentLifecycleExtensionTest
java
elastic__elasticsearch
x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleRegistryTests.java
{ "start": 881, "end": 5653 }
class ____ extends ScheduleTestCase { private ScheduleRegistry registry; @Before public void init() throws Exception { Set<Schedule.Parser<? extends Schedule>> parsers = new HashSet<>(); parsers.add(new IntervalSchedule.Parser()); parsers.add(new CronSchedule.Parser()); parsers.add(new HourlySchedule.Parser()); parsers.add(new DailySchedule.Parser()); parsers.add(new WeeklySchedule.Parser()); parsers.add(new MonthlySchedule.Parser()); registry = new ScheduleRegistry(parsers); } public void testParserInterval() throws Exception { IntervalSchedule interval = randomIntervalSchedule(); XContentBuilder builder = jsonBuilder().startObject().field(IntervalSchedule.TYPE, interval).endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); Schedule schedule = registry.parse("ctx", parser); assertThat(schedule, notNullValue()); assertThat(schedule, instanceOf(IntervalSchedule.class)); assertThat((IntervalSchedule) schedule, is(interval)); } public void testParseCron() throws Exception { var cron = randomBoolean() ? Schedules.cron("* 0/5 * * * ?") : Schedules.cron("* 0/2 * * * ?", "* 0/3 * * * ?", "* 0/5 * * * ?"); ZoneId timeZone = null; XContentBuilder builder = jsonBuilder().startObject().field(CronSchedule.TYPE, cron); if (randomBoolean()) { timeZone = randomTimeZone().toZoneId(); cron.setTimeZone(timeZone); builder.field(ScheduleTrigger.TIMEZONE_FIELD, timeZone.getId()); } builder.endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); CronnableSchedule schedule = (CronnableSchedule) registry.parse("ctx", parser); assertThat(schedule, notNullValue()); assertThat(schedule, instanceOf(CronSchedule.class)); assertThat(schedule, is(cron)); assertThat(schedule.getTimeZone(), equalTo(timeZone)); } public void testParseHourly() throws Exception { HourlySchedule hourly = randomHourlySchedule(); XContentBuilder builder = jsonBuilder().startObject().field(HourlySchedule.TYPE, hourly).endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); Schedule schedule = registry.parse("ctx", parser); assertThat(schedule, notNullValue()); assertThat(schedule, instanceOf(HourlySchedule.class)); assertThat((HourlySchedule) schedule, equalTo(hourly)); } public void testParseDaily() throws Exception { DailySchedule daily = randomDailySchedule(); XContentBuilder builder = jsonBuilder().startObject().field(DailySchedule.TYPE, daily).endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); Schedule schedule = registry.parse("ctx", parser); assertThat(schedule, notNullValue()); assertThat(schedule, instanceOf(DailySchedule.class)); assertThat((DailySchedule) schedule, equalTo(daily)); } public void testParseWeekly() throws Exception { WeeklySchedule weekly = randomWeeklySchedule(); XContentBuilder builder = jsonBuilder().startObject().field(WeeklySchedule.TYPE, weekly).endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); Schedule schedule = registry.parse("ctx", parser); assertThat(schedule, notNullValue()); assertThat(schedule, instanceOf(WeeklySchedule.class)); assertThat((WeeklySchedule) schedule, equalTo(weekly)); } public void testParseMonthly() throws Exception { MonthlySchedule monthly = randomMonthlySchedule(); XContentBuilder builder = jsonBuilder().startObject().field(MonthlySchedule.TYPE, monthly).endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); Schedule schedule = registry.parse("ctx", parser); assertThat(schedule, notNullValue()); assertThat(schedule, instanceOf(MonthlySchedule.class)); assertThat((MonthlySchedule) schedule, equalTo(monthly)); } }
ScheduleRegistryTests
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_withIntrospectionStrategy_Test.java
{ "start": 6310, "end": 6797 }
class ____ { String firstName; String lastName; int age; String phoneNumber1; String phoneNumber2; String profileURL; Author(String firstName, String lastName, int age, String phoneNumber1, String phoneNumber2, String profileUrl) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.phoneNumber1 = phoneNumber1; this.phoneNumber2 = phoneNumber2; this.profileURL = profileUrl; } } static
Author
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointRecipientList4Test.java
{ "start": 1174, "end": 2906 }
class ____ extends ContextTestSupport { private static long beforeThreadId; private static long afterThreadId; @Test public void testAsyncEndpoint() throws Exception { getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel"); getMockEndpoint("mock:after").expectedBodiesReceived("Bye Camel"); getMockEndpoint("mock:result").expectedBodiesReceived("Bye Camel"); String reply = template.requestBody("direct:start", "Hello Camel", String.class); assertEquals("Bye Camel", reply); assertMockEndpointsSatisfied(); assertNotEquals(beforeThreadId, afterThreadId, "Should use different threads " + beforeThreadId + ":" + afterThreadId); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { context.addComponent("async", new MyAsyncComponent()); from("direct:start").to("mock:before").to("log:before").process(new Processor() { public void process(Exchange exchange) { beforeThreadId = Thread.currentThread().getId(); } }).recipientList(constant("async:hi:camel,async:hi:world,direct:foo")); from("direct:foo").process(new Processor() { public void process(Exchange exchange) { afterThreadId = Thread.currentThread().getId(); exchange.getMessage().setBody("Bye Camel"); } }).to("log:after").to("mock:after").to("mock:result"); } }; } }
AsyncEndpointRecipientList4Test
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/GenericArrayTypeImpl.java
{ "start": 170, "end": 1472 }
class ____ implements GenericArrayType { private Type genericComponentType; public GenericArrayTypeImpl(Type genericComponentType) { this.genericComponentType = genericComponentType; } public GenericArrayTypeImpl(Class<?> rawType, Type... actualTypeArguments) { this.genericComponentType = new ParameterizedTypeImpl(rawType, actualTypeArguments); } @Override public Type getGenericComponentType() { return genericComponentType; } @Override public int hashCode() { return ((genericComponentType == null) ? 0 : genericComponentType.hashCode()); } @Override public boolean equals(Object obj) { if (obj instanceof GenericArrayType) { GenericArrayType that = (GenericArrayType) obj; if (genericComponentType == null) { return that.getGenericComponentType() == null; } else { return genericComponentType.equals(that.getGenericComponentType()); } } else { return false; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(genericComponentType.toString()); sb.append("[]"); return sb.toString(); } }
GenericArrayTypeImpl
java
apache__camel
components/camel-lumberjack/src/main/java/org/apache/camel/component/lumberjack/io/LumberjackServer.java
{ "start": 1505, "end": 4427 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(LumberjackServer.class); private static final int WORKER_THREADS = 16; private final String host; private final int port; private final SSLContext sslContext; private final ThreadFactory threadFactory; private final LumberjackMessageProcessor messageProcessor; private EventExecutorGroup executorService; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private Channel channel; public LumberjackServer(String host, int port, SSLContext sslContext, ThreadFactory threadFactory, LumberjackMessageProcessor messageProcessor) { this.host = host; this.port = port; this.sslContext = sslContext; this.threadFactory = threadFactory; this.messageProcessor = messageProcessor; } /** * Starts the server. * * @throws InterruptedException when interrupting while connecting the socket */ public void start() throws InterruptedException { LOG.info("Starting the LUMBERJACK server (host={}, port={}).", host, port); // Create the group that will listen for incoming connections bossGroup = new NioEventLoopGroup(1); // Create the group that will process the connections workerGroup = new NioEventLoopGroup(WORKER_THREADS); // Create the executor service that will process the payloads without blocking netty threads executorService = new DefaultEventExecutorGroup(WORKER_THREADS, threadFactory); // Create the channel initializer ChannelHandler initializer = new LumberjackChannelInitializer(sslContext, executorService, messageProcessor); // Bootstrap the netty server ServerBootstrap serverBootstrap = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .childHandler(initializer); // Connect the socket channel = serverBootstrap.bind(host, port).sync().channel(); LOG.info("LUMBERJACK server is started (host={}, port={}).", host, port); } /** * Stops the server. * * @throws InterruptedException when interrupting while stopping the socket */ public void stop() throws InterruptedException { LOG.info("Stopping the LUMBERJACK server (host={}, port={}).", host, port); try { // Wait for the channel to be indeed closed before shutting the groups & service channel.close().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); executorService.shutdownGracefully(); } LOG.info("LUMBERJACK server is stopped (host={}, port={}).", host, port); } }
LumberjackServer
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUpgrade.java
{ "start": 2855, "end": 20621 }
class ____ { // TODO: Avoid hard-coding expected_txid. The test should be more robust. private static final int EXPECTED_TXID = 61; private static final Logger LOG = LoggerFactory.getLogger(TestDFSUpgrade.class.getName()); private Configuration conf; private int testCounter = 0; private MiniDFSCluster cluster = null; /** * Writes an INFO log message containing the parameters. */ void log(String label, int numDirs) { LOG.info("============================================================"); LOG.info("***TEST " + (testCounter++) + "*** " + label + ":" + " numDirs="+numDirs); } /** * For namenode, Verify that the current and previous directories exist. * Verify that previous hasn't been modified by comparing the checksum of all * its files with their original checksum. It is assumed that the * server has recovered and upgraded. */ void checkNameNode(String[] baseDirs, long imageTxId) throws IOException { for (String baseDir : baseDirs) { LOG.info("Checking namenode directory " + baseDir); LOG.info("==== Contents ====:\n " + Joiner.on(" \n").join(new File(baseDir, "current").list())); LOG.info("=================="); assertExists(new File(baseDir,"current")); assertExists(new File(baseDir,"current/VERSION")); assertExists(new File(baseDir,"current/" + getInProgressEditsFileName(imageTxId + 1))); assertExists(new File(baseDir,"current/" + getImageFileName(imageTxId))); assertExists(new File(baseDir,"current/seen_txid")); File previous = new File(baseDir, "previous"); assertExists(previous); assertEquals(UpgradeUtilities.checksumContents(NAME_NODE, previous, false), UpgradeUtilities.checksumMasterNameNodeContents()); } } /** * For datanode, for a block pool, verify that the current and previous * directories exist. Verify that previous hasn't been modified by comparing * the checksum of all its files with their original checksum. It * is assumed that the server has recovered and upgraded. */ void checkDataNode(String[] baseDirs, String bpid) throws IOException { for (int i = 0; i < baseDirs.length; i++) { File current = new File(baseDirs[i], "current/" + bpid + "/current"); assertEquals(UpgradeUtilities.checksumContents(DATA_NODE, current, false), UpgradeUtilities.checksumMasterDataNodeContents()); // block files are placed under <sd>/current/<bpid>/current/finalized File currentFinalized = MiniDFSCluster.getFinalizedDir(new File(baseDirs[i]), bpid); assertEquals(UpgradeUtilities.checksumContents(DATA_NODE, currentFinalized, true), UpgradeUtilities.checksumMasterBlockPoolFinalizedContents()); File previous = new File(baseDirs[i], "current/" + bpid + "/previous"); assertTrue(previous.isDirectory()); assertEquals(UpgradeUtilities.checksumContents(DATA_NODE, previous, false), UpgradeUtilities.checksumMasterDataNodeContents()); File previousFinalized = new File(baseDirs[i], "current/" + bpid + "/previous"+"/finalized"); assertEquals(UpgradeUtilities.checksumContents(DATA_NODE, previousFinalized, true), UpgradeUtilities.checksumMasterBlockPoolFinalizedContents()); } } /** * Attempts to start a NameNode with the given operation. Starting * the NameNode should throw an exception. */ void startNameNodeShouldFail(StartupOption operation) { startNameNodeShouldFail(operation, null, null); } /** * Attempts to start a NameNode with the given operation. Starting * the NameNode should throw an exception. * @param operation - NameNode startup operation * @param exceptionClass - if non-null, will check that the caught exception * is assignment-compatible with exceptionClass * @param messagePattern - if non-null, will check that a substring of the * message from the caught exception matches this pattern, via the * {@link Matcher#find()} method. */ void startNameNodeShouldFail(StartupOption operation, Class<? extends Exception> exceptionClass, Pattern messagePattern) { try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0) .startupOption(operation) .format(false) .manageDataDfsDirs(false) .manageNameDfsDirs(false) .build(); // should fail fail("NameNode should have failed to start"); } catch (Exception e) { // expect exception if (exceptionClass != null) { assertTrue(exceptionClass.isInstance(e), "Caught exception is not of expected class " + exceptionClass.getSimpleName() + ": " + StringUtils.stringifyException(e)); } if (messagePattern != null) { assertTrue(messagePattern.matcher(e.getMessage()).find(), "Caught exception message string does not match expected pattern \"" + messagePattern.pattern() + "\" : " + StringUtils.stringifyException(e)); } LOG.info("Successfully detected expected NameNode startup failure."); } } /** * Attempts to start a DataNode with the given operation. Starting * the given block pool should fail. * @param operation startup option * @param bpid block pool Id that should fail to start * @throws IOException */ void startBlockPoolShouldFail(StartupOption operation, String bpid) throws IOException { cluster.startDataNodes(conf, 1, false, operation, null); // should fail assertFalse(cluster.getDataNodes().get(0).isBPServiceAlive(bpid), "Block pool " + bpid + " should have failed to start"); } /** * Create an instance of a newly configured cluster for testing that does * not manage its own directories or files */ private MiniDFSCluster createCluster() throws IOException { return new MiniDFSCluster.Builder(conf).numDataNodes(0) .format(false) .manageDataDfsDirs(false) .manageNameDfsDirs(false) .startupOption(StartupOption.UPGRADE) .build(); } @BeforeAll public static void initialize() throws Exception { UpgradeUtilities.initialize(); } /** * This test attempts to upgrade the NameNode and DataNode under * a number of valid and invalid conditions. */ @SuppressWarnings("checkstyle:MethodLength") @Test @Timeout(value = 60) public void testUpgrade() throws Exception { File[] baseDirs; StorageInfo storageInfo = null; for (int numDirs = 1; numDirs <= 2; numDirs++) { conf = new HdfsConfiguration(); conf = UpgradeUtilities.initializeStorageStateConf(numDirs, conf); String[] nameNodeDirs = conf.getStrings(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY); String[] dataNodeDirs = conf.getStrings(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY); conf.setBoolean(DFSConfigKeys.DFS_DATANODE_DUPLICATE_REPLICA_DELETION, false); log("Normal NameNode upgrade", numDirs); UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); cluster = createCluster(); // make sure that rolling upgrade cannot be started try { final DistributedFileSystem dfs = cluster.getFileSystem(); dfs.setSafeMode(SafeModeAction.ENTER); dfs.rollingUpgrade(RollingUpgradeAction.PREPARE); fail(); } catch(RemoteException re) { assertEquals(InconsistentFSStateException.class.getName(), re.getClassName()); LOG.info("The exception is expected.", re); } checkNameNode(nameNodeDirs, EXPECTED_TXID); if (numDirs > 1) TestParallelImageWrite.checkImages(cluster.getNamesystem(), numDirs); cluster.shutdown(); UpgradeUtilities.createEmptyDirs(nameNodeDirs); log("Normal DataNode upgrade", numDirs); UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); cluster = createCluster(); UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current"); cluster.startDataNodes(conf, 1, false, StartupOption.REGULAR, null); checkDataNode(dataNodeDirs, UpgradeUtilities.getCurrentBlockPoolID(null)); cluster.shutdown(); UpgradeUtilities.createEmptyDirs(nameNodeDirs); UpgradeUtilities.createEmptyDirs(dataNodeDirs); log("NameNode upgrade with existing previous dir", numDirs); UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous"); startNameNodeShouldFail(StartupOption.UPGRADE); UpgradeUtilities.createEmptyDirs(nameNodeDirs); log("DataNode upgrade with existing previous dir", numDirs); UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); cluster = createCluster(); UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current"); UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "previous"); cluster.startDataNodes(conf, 1, false, StartupOption.REGULAR, null); checkDataNode(dataNodeDirs, UpgradeUtilities.getCurrentBlockPoolID(null)); cluster.shutdown(); UpgradeUtilities.createEmptyDirs(nameNodeDirs); UpgradeUtilities.createEmptyDirs(dataNodeDirs); log("DataNode upgrade with future stored layout version in current", numDirs); UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); cluster = createCluster(); baseDirs = UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current"); storageInfo = new StorageInfo(Integer.MIN_VALUE, UpgradeUtilities.getCurrentNamespaceID(cluster), UpgradeUtilities.getCurrentClusterID(cluster), UpgradeUtilities.getCurrentFsscTime(cluster), NodeType.DATA_NODE); UpgradeUtilities.createDataNodeVersionFile(baseDirs, storageInfo, UpgradeUtilities.getCurrentBlockPoolID(cluster), conf); startBlockPoolShouldFail(StartupOption.REGULAR, UpgradeUtilities .getCurrentBlockPoolID(null)); cluster.shutdown(); UpgradeUtilities.createEmptyDirs(nameNodeDirs); UpgradeUtilities.createEmptyDirs(dataNodeDirs); log("DataNode upgrade with newer fsscTime in current", numDirs); UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); cluster = createCluster(); baseDirs = UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current"); storageInfo = new StorageInfo( DataNodeLayoutVersion.getCurrentLayoutVersion(), UpgradeUtilities.getCurrentNamespaceID(cluster), UpgradeUtilities.getCurrentClusterID(cluster), Long.MAX_VALUE, NodeType.DATA_NODE); UpgradeUtilities.createDataNodeVersionFile(baseDirs, storageInfo, UpgradeUtilities.getCurrentBlockPoolID(cluster), conf); // Ensure corresponding block pool failed to initialized startBlockPoolShouldFail(StartupOption.REGULAR, UpgradeUtilities .getCurrentBlockPoolID(null)); cluster.shutdown(); UpgradeUtilities.createEmptyDirs(nameNodeDirs); UpgradeUtilities.createEmptyDirs(dataNodeDirs); log("NameNode upgrade with no edits file", numDirs); UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); deleteStorageFilesWithPrefix(nameNodeDirs, "edits_"); startNameNodeShouldFail(StartupOption.UPGRADE); UpgradeUtilities.createEmptyDirs(nameNodeDirs); log("NameNode upgrade with no image file", numDirs); UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); deleteStorageFilesWithPrefix(nameNodeDirs, "fsimage_"); startNameNodeShouldFail(StartupOption.UPGRADE); UpgradeUtilities.createEmptyDirs(nameNodeDirs); log("NameNode upgrade with corrupt version file", numDirs); baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); for (File f : baseDirs) { UpgradeUtilities.corruptFile( new File(f,"VERSION"), "layoutVersion".getBytes(StandardCharsets.UTF_8), "xxxxxxxxxxxxx".getBytes(StandardCharsets.UTF_8)); } startNameNodeShouldFail(StartupOption.UPGRADE); UpgradeUtilities.createEmptyDirs(nameNodeDirs); log("NameNode upgrade with old layout version in current", numDirs); baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); storageInfo = new StorageInfo(Storage.LAST_UPGRADABLE_LAYOUT_VERSION + 1, UpgradeUtilities.getCurrentNamespaceID(null), UpgradeUtilities.getCurrentClusterID(null), UpgradeUtilities.getCurrentFsscTime(null), NodeType.NAME_NODE); UpgradeUtilities.createNameNodeVersionFile(conf, baseDirs, storageInfo, UpgradeUtilities.getCurrentBlockPoolID(null)); startNameNodeShouldFail(StartupOption.UPGRADE); UpgradeUtilities.createEmptyDirs(nameNodeDirs); log("NameNode upgrade with future layout version in current", numDirs); baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); storageInfo = new StorageInfo(Integer.MIN_VALUE, UpgradeUtilities.getCurrentNamespaceID(null), UpgradeUtilities.getCurrentClusterID(null), UpgradeUtilities.getCurrentFsscTime(null), NodeType.NAME_NODE); UpgradeUtilities.createNameNodeVersionFile(conf, baseDirs, storageInfo, UpgradeUtilities.getCurrentBlockPoolID(null)); startNameNodeShouldFail(StartupOption.UPGRADE); UpgradeUtilities.createEmptyDirs(nameNodeDirs); } // end numDir loop // One more check: normal NN upgrade with 4 directories, concurrent write int numDirs = 4; { conf = new HdfsConfiguration(); conf.setInt(DFSConfigKeys.DFS_DATANODE_SCAN_PERIOD_HOURS_KEY, -1); conf.setBoolean(DFSConfigKeys.DFS_DATANODE_DUPLICATE_REPLICA_DELETION, false); conf = UpgradeUtilities.initializeStorageStateConf(numDirs, conf); String[] nameNodeDirs = conf.getStrings(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY); log("Normal NameNode upgrade", numDirs); UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); cluster = createCluster(); // make sure that rolling upgrade cannot be started try { final DistributedFileSystem dfs = cluster.getFileSystem(); dfs.setSafeMode(SafeModeAction.ENTER); dfs.rollingUpgrade(RollingUpgradeAction.PREPARE); fail(); } catch(RemoteException re) { assertEquals(InconsistentFSStateException.class.getName(), re.getClassName()); LOG.info("The exception is expected.", re); } checkNameNode(nameNodeDirs, EXPECTED_TXID); TestParallelImageWrite.checkImages(cluster.getNamesystem(), numDirs); cluster.shutdown(); UpgradeUtilities.createEmptyDirs(nameNodeDirs); } } /* * Stand-alone test to detect failure of one SD during parallel upgrade. * At this time, can only be done with manual hack of {@link FSImage.doUpgrade()} */ @Disabled public void testUpgrade4() throws Exception { int numDirs = 4; conf = new HdfsConfiguration(); conf.setInt(DFSConfigKeys.DFS_DATANODE_SCAN_PERIOD_HOURS_KEY, -1); conf.setBoolean(DFSConfigKeys.DFS_DATANODE_DUPLICATE_REPLICA_DELETION, false); conf = UpgradeUtilities.initializeStorageStateConf(numDirs, conf); String[] nameNodeDirs = conf.getStrings(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY); log("NameNode upgrade with one bad storage dir", numDirs); UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current"); try { // assert("storage dir has been prepared for failure before reaching this point"); startNameNodeShouldFail(StartupOption.UPGRADE, IOException.class, Pattern.compile("failed in 1 storage")); } finally { // assert("storage dir shall be returned to normal state before exiting"); UpgradeUtilities.createEmptyDirs(nameNodeDirs); } } private void deleteStorageFilesWithPrefix(String[] nameNodeDirs, String prefix) throws Exception { for (String baseDirStr : nameNodeDirs) { File baseDir = new File(baseDirStr); File currentDir = new File(baseDir, "current"); for (File f : currentDir.listFiles()) { if (f.getName().startsWith(prefix)) { assertTrue(f.delete(), "Deleting " + f); } } } } @Test public void testUpgradeFromPreUpgradeLVFails() throws IOException { assertThrows(IOException.class, () -> { Storage.checkVersionUpgradable(Storage.LAST_PRE_UPGRADE_LAYOUT_VERSION + 1); fail("Expected IOException is not thrown"); }); // Upgrade from versions prior to Storage#LAST_UPGRADABLE_LAYOUT_VERSION } @Disabled public void test203LayoutVersion() { for (int lv : Storage.LAYOUT_VERSIONS_203) { assertTrue(Storage.is203LayoutVersion(lv)); } } public static void main(String[] args) throws Exception { TestDFSUpgrade t = new TestDFSUpgrade(); TestDFSUpgrade.initialize(); t.testUpgrade(); } }
TestDFSUpgrade
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/EmptyImmutableTest.java
{ "start": 163, "end": 350 }
class ____ extends TestCase { public void test_0() throws Exception { VO vo = JSON.parseObject("{\"values\":[],\"map\":{}}", VO.class); } public static
EmptyImmutableTest
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/mixedmode/Location.java
{ "start": 399, "end": 1167 }
class ____ { @Id private long id; private String description; // implicitly embedded private Coordinates coordinates; @Embedded private ZeroCoordinates zeroCoordinates; public Coordinates getCoordinates() { return coordinates; } public void setCoordinates(Coordinates coordinates) { this.coordinates = coordinates; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public long getId() { return id; } public void setId(long id) { this.id = id; } public ZeroCoordinates getZeroCoordinates() { return zeroCoordinates; } public void setZeroCoordinates(ZeroCoordinates zeroCoordinates) { this.zeroCoordinates = zeroCoordinates; } }
Location
java
netty__netty
codec-base/src/main/java/io/netty/handler/codec/base64/Base64Decoder.java
{ "start": 1832, "end": 2378 }
class ____ extends MessageToMessageDecoder<ByteBuf> { private final Base64Dialect dialect; public Base64Decoder() { this(Base64Dialect.STANDARD); } public Base64Decoder(Base64Dialect dialect) { super(ByteBuf.class); this.dialect = ObjectUtil.checkNotNull(dialect, "dialect"); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { out.add(Base64.decode(msg, msg.readerIndex(), msg.readableBytes(), dialect)); } }
Base64Decoder