language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
micronaut-projects__micronaut-core
inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java
{ "start": 1678, "end": 5921 }
class ____ { private final Elements elementUtils; private final Types typeUtils; /** * @param elementUtils The {@link Elements} * @param typeUtils The {@link Types} */ protected ModelUtils(Elements elementUtils, Types typeUtils) { this.elementUtils = elementUtils; this.typeUtils = typeUtils; } /** * @return The type utilities */ public Types getTypeUtils() { return typeUtils; } /** * Resolves type elements from the provided annotated elements. * * @param annotatedElements The elements to process * @return the type elements */ public Stream<TypeElement> resolveTypeElements(Set<? extends Element> annotatedElements) { return annotatedElements .stream() .flatMap(element -> { if (element instanceof ExecutableElement executableElement) { return Stream.of(executableElement.getEnclosingElement()); } if (element instanceof VariableElement variableElement) { return Stream.of(variableElement.getEnclosingElement()); } if (element instanceof PackageElement packageElement) { return packageElement.getEnclosedElements().stream(); } return Stream.of(element); }) .filter(element -> JavaModelUtils.isClassOrInterface(element) || JavaModelUtils.isEnum(element) || JavaModelUtils.isRecord(element)) .map(this::classElementFor) .filter(Objects::nonNull) .filter(element -> element.getAnnotation(Generated.class) == null); } /** * Obtains the {@link TypeElement} for a given element. * * @param element The element * @return The {@link TypeElement} */ @Nullable public final TypeElement classElementFor(Element element) { while (element != null && !(JavaModelUtils.isClassOrInterface(element) || JavaModelUtils.isRecord(element) || JavaModelUtils.isEnum(element))) { element = element.getEnclosingElement(); } if (element instanceof TypeElement e) { return e; } return null; } /** * Resolves a type name for the given name. * * @param type The type * @return The type reference */ String resolveTypeName(TypeMirror type) { TypeMirror typeMirror = resolveTypeReference(type); if (typeMirror.getKind().isPrimitive()) { return typeMirror.toString(); } TypeElement typeElement = (TypeElement) typeUtils.asElement(typeMirror); if (typeElement != null) { return elementUtils.getBinaryName(typeElement).toString(); } else { return typeUtils.erasure(typeMirror).toString(); } } /** * Resolves a type reference for the given type mirror. A type reference is either a reference to the concrete * {@link Class} or a String representing the type name. * * @param type The type * @return The type reference */ TypeMirror resolveTypeReference(TypeMirror type) { TypeKind typeKind = type.getKind(); if (typeKind.isPrimitive()) { return type; } else if (typeKind == TypeKind.DECLARED) { DeclaredType dt = (DeclaredType) type; if (dt.getTypeArguments().isEmpty()) { return dt; } return typeUtils.erasure(type); } else { return typeUtils.erasure(type); } } /** * Return whether the element is abstract. * * @param element The element * @return True if it is abstract */ boolean isAbstract(Element element) { return element.getModifiers().contains(ABSTRACT); } /** * Return whether the element is static. * * @param element The element * @return True if it is static */ boolean isStatic(Element element) { return element.getModifiers().contains(STATIC); } /** * The Java APT throws an internal exception {code com.sun.tools.javac.code.Symbol$CompletionFailure} if a
ModelUtils
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/tls/HttpTLSTest.java
{ "start": 84652, "end": 85937 }
class ____ extends KeyManagerFactorySpi { private final KeyManagerFactory delegate; private final BiConsumer<String, Integer> peerHostVerifier; KeyManagerFactorySpiWrapper(KeyManagerFactory delegate, BiConsumer<String, Integer> peerHostVerifier) { super(); this.delegate = delegate; this.peerHostVerifier = peerHostVerifier; } @Override protected void engineInit(KeyStore keyStore, char[] chars) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { delegate.init(keyStore, chars); } @Override protected void engineInit(ManagerFactoryParameters managerFactoryParameters) throws InvalidAlgorithmParameterException { delegate.init(managerFactoryParameters); } @Override protected KeyManager[] engineGetKeyManagers() { KeyManager[] keyManagers = delegate.getKeyManagers().clone(); for (int i = 0; i < keyManagers.length; ++i) { KeyManager km = keyManagers[i]; if (km instanceof X509KeyManager) { keyManagers[i] = new VerifyServerPeerHostKeyManager((X509KeyManager) km, peerHostVerifier); } } return keyManagers; } } } private static
KeyManagerFactorySpiWrapper
java
apache__camel
components/camel-bean/src/main/java/org/apache/camel/component/bean/MethodInfo.java
{ "start": 2749, "end": 3516 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(MethodInfo.class); private final CamelContext camelContext; private final Class<?> type; private final Method method; private final List<ParameterInfo> parameters; private final List<ParameterInfo> bodyParameters; private final boolean hasCustomAnnotation; private final boolean hasHandlerAnnotation; private final Expression parametersExpression; private ExchangePattern pattern = ExchangePattern.InOut; private AsyncProcessor recipientList; private AsyncProcessor routingSlip; private AsyncProcessor dynamicRouter; /** * Adapter to invoke the method which has been annotated with the @DynamicRouter */ private final
MethodInfo
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/language/Hl7TerserExpression.java
{ "start": 2055, "end": 2255 }
class ____ extends AbstractBuilder<Builder, Hl7TerserExpression> { @Override public Hl7TerserExpression end() { return new Hl7TerserExpression(this); } } }
Builder
java
apache__camel
components/camel-keycloak/src/test/java/org/apache/camel/component/keycloak/security/KeycloakTokenBindingSecurityIT.java
{ "start": 2898, "end": 19796 }
class ____ extends CamelTestSupport { private static final Logger log = LoggerFactory.getLogger(KeycloakTokenBindingSecurityIT.class); @RegisterExtension static KeycloakService keycloakService = KeycloakServiceFactory.createService(); // Test data - use unique names private static final String TEST_REALM_NAME = "token-binding-realm-" + UUID.randomUUID().toString().substring(0, 8); private static final String TEST_CLIENT_ID = "token-binding-client-" + UUID.randomUUID().toString().substring(0, 8); private static String TEST_CLIENT_SECRET = null; // Test users private static final String ADMIN_USER = "admin-" + UUID.randomUUID().toString().substring(0, 8); private static final String ADMIN_PASSWORD = "admin123"; private static final String NORMAL_USER = "user-" + UUID.randomUUID().toString().substring(0, 8); private static final String NORMAL_PASSWORD = "user123"; private static final String ATTACKER_USER = "attacker-" + UUID.randomUUID().toString().substring(0, 8); private static final String ATTACKER_PASSWORD = "attacker123"; // Test roles private static final String ADMIN_ROLE = "admin"; private static final String USER_ROLE = "user"; private static Keycloak keycloakAdminClient; private static RealmResource realmResource; @BeforeAll static void setupKeycloakRealm() { log.info("Setting up Keycloak realm for token binding tests"); keycloakAdminClient = KeycloakBuilder.builder() .serverUrl(keycloakService.getKeycloakServerUrl()) .realm(keycloakService.getKeycloakRealm()) .username(keycloakService.getKeycloakUsername()) .password(keycloakService.getKeycloakPassword()) .clientId("admin-cli") .build(); createTestRealm(); realmResource = keycloakAdminClient.realm(TEST_REALM_NAME); createTestClient(); createTestRoles(); createTestUsers(); assignRolesToUsers(); log.info("Keycloak realm setup completed: {}", TEST_REALM_NAME); } @AfterAll static void cleanupKeycloakRealm() { if (keycloakAdminClient != null) { try { keycloakAdminClient.realm(TEST_REALM_NAME).remove(); log.info("Deleted test realm: {}", TEST_REALM_NAME); } catch (Exception e) { log.warn("Failed to cleanup test realm: {}", e.getMessage()); } finally { keycloakAdminClient.close(); } } } private static void createTestRealm() { RealmRepresentation realm = new RealmRepresentation(); realm.setId(TEST_REALM_NAME); realm.setRealm(TEST_REALM_NAME); realm.setDisplayName("Token Binding Security Test Realm"); realm.setEnabled(true); realm.setAccessTokenLifespan(3600); keycloakAdminClient.realms().create(realm); } private static void createTestClient() { ClientRepresentation client = new ClientRepresentation(); client.setClientId(TEST_CLIENT_ID); client.setName("Token Binding Test Client"); client.setDescription("Client for token binding security testing"); client.setEnabled(true); client.setPublicClient(false); client.setDirectAccessGrantsEnabled(true); client.setStandardFlowEnabled(true); client.setFullScopeAllowed(true); Response response = realmResource.clients().create(client); if (response.getStatus() == 201) { String clientId = response.getHeaderString("Location").substring(response.getHeaderString("Location").lastIndexOf('/') + 1); ClientResource clientResource = realmResource.clients().get(clientId); TEST_CLIENT_SECRET = clientResource.getSecret().getValue(); log.info("Created test client: {} with secret", TEST_CLIENT_ID); } else { throw new RuntimeException("Failed to create client. Status: " + response.getStatus()); } response.close(); } private static void createTestRoles() { RoleRepresentation adminRole = new RoleRepresentation(); adminRole.setName(ADMIN_ROLE); realmResource.roles().create(adminRole); RoleRepresentation userRole = new RoleRepresentation(); userRole.setName(USER_ROLE); realmResource.roles().create(userRole); } private static void createTestUsers() { createUser(ADMIN_USER, ADMIN_PASSWORD, "Admin", "User", ADMIN_USER + "@test.com"); createUser(NORMAL_USER, NORMAL_PASSWORD, "Normal", "User", NORMAL_USER + "@test.com"); createUser(ATTACKER_USER, ATTACKER_PASSWORD, "Attacker", "User", ATTACKER_USER + "@test.com"); } private static void createUser(String username, String password, String firstName, String lastName, String email) { UserRepresentation user = new UserRepresentation(); user.setUsername(username); user.setFirstName(firstName); user.setLastName(lastName); user.setEmail(email); user.setEnabled(true); user.setEmailVerified(true); Response response = realmResource.users().create(user); if (response.getStatus() == 201) { String userId = response.getHeaderString("Location").substring(response.getHeaderString("Location").lastIndexOf('/') + 1); UserResource userResource = realmResource.users().get(userId); CredentialRepresentation credential = new CredentialRepresentation(); credential.setType(CredentialRepresentation.PASSWORD); credential.setValue(password); credential.setTemporary(false); userResource.resetPassword(credential); log.info("Created user: {} with password", username); } else { throw new RuntimeException("Failed to create user: " + username + ". Status: " + response.getStatus()); } response.close(); } private static void assignRolesToUsers() { assignRoleToUser(ADMIN_USER, ADMIN_ROLE); assignRoleToUser(NORMAL_USER, USER_ROLE); assignRoleToUser(ATTACKER_USER, USER_ROLE); } private static void assignRoleToUser(String username, String roleName) { List<UserRepresentation> users = realmResource.users().search(username); if (!users.isEmpty()) { UserResource userResource = realmResource.users().get(users.get(0).getId()); RoleRepresentation role = realmResource.roles().get(roleName).toRepresentation(); userResource.roles().realmLevel().add(Arrays.asList(role)); } } @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { // Route 1: Secure default - property preferred over header KeycloakSecurityPolicy securePolicy = new KeycloakSecurityPolicy(); securePolicy.setServerUrl(keycloakService.getKeycloakServerUrl()); securePolicy.setRealm(TEST_REALM_NAME); securePolicy.setClientId(TEST_CLIENT_ID); securePolicy.setClientSecret(TEST_CLIENT_SECRET); securePolicy.setPreferPropertyOverHeader(true); securePolicy.setAllowTokenFromHeader(true); securePolicy.setValidateTokenBinding(true); from("direct:secure-default") .policy(securePolicy) .transform().constant("Access granted - secure default"); // Route 2: Maximum security - headers disabled KeycloakSecurityPolicy maxSecurityPolicy = new KeycloakSecurityPolicy(); maxSecurityPolicy.setServerUrl(keycloakService.getKeycloakServerUrl()); maxSecurityPolicy.setRealm(TEST_REALM_NAME); maxSecurityPolicy.setClientId(TEST_CLIENT_ID); maxSecurityPolicy.setClientSecret(TEST_CLIENT_SECRET); maxSecurityPolicy.setAllowTokenFromHeader(false); from("direct:max-security") .policy(maxSecurityPolicy) .transform().constant("Access granted - max security"); // Route 3: Admin-only route KeycloakSecurityPolicy adminPolicy = new KeycloakSecurityPolicy(); adminPolicy.setServerUrl(keycloakService.getKeycloakServerUrl()); adminPolicy.setRealm(TEST_REALM_NAME); adminPolicy.setClientId(TEST_CLIENT_ID); adminPolicy.setClientSecret(TEST_CLIENT_SECRET); adminPolicy.setRequiredRoles(Arrays.asList(ADMIN_ROLE)); adminPolicy.setPreferPropertyOverHeader(true); from("direct:admin-only") .policy(adminPolicy) .transform().constant("Admin access granted"); } }; } @Test @Order(1) void testKeycloakServiceConfiguration() { assertNotNull(keycloakService.getKeycloakServerUrl()); assertNotNull(TEST_CLIENT_SECRET); } @Test @Order(10) void testPropertyTokenWorks() { String normalToken = getAccessToken(NORMAL_USER, NORMAL_PASSWORD); String result = template.send("direct:secure-default", exchange -> { exchange.setProperty(KeycloakSecurityConstants.ACCESS_TOKEN_PROPERTY, normalToken); exchange.getIn().setBody("test"); }).getMessage().getBody(String.class); assertEquals("Access granted - secure default", result); log.info("βœ“ Property token works"); } @Test @Order(11) void testHeaderTokenWorks() { String normalToken = getAccessToken(NORMAL_USER, NORMAL_PASSWORD); String result = template.requestBodyAndHeader("direct:secure-default", "test", KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, normalToken, String.class); assertEquals("Access granted - secure default", result); log.info("βœ“ Header token works"); } @Test @Order(12) void testPropertyPreferredOverHeader() { String normalToken = getAccessToken(NORMAL_USER, NORMAL_PASSWORD); String attackerToken = getAccessToken(ATTACKER_USER, ATTACKER_PASSWORD); String result = template.send("direct:secure-default", exchange -> { exchange.setProperty(KeycloakSecurityConstants.ACCESS_TOKEN_PROPERTY, normalToken); exchange.getIn().setHeader(KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, attackerToken); exchange.getIn().setBody("test"); }).getMessage().getBody(String.class); assertEquals("Access granted - secure default", result); log.info("βœ“ Property token preferred over header token"); } @Test @Order(13) void testInvalidHeaderIgnoredWhenPropertyValid() { String normalToken = getAccessToken(NORMAL_USER, NORMAL_PASSWORD); String result = template.send("direct:secure-default", exchange -> { exchange.setProperty(KeycloakSecurityConstants.ACCESS_TOKEN_PROPERTY, normalToken); exchange.getIn().setHeader(KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, "invalid.token"); exchange.getIn().setBody("test"); }).getMessage().getBody(String.class); assertEquals("Access granted - secure default", result); log.info("βœ“ Invalid header ignored when property valid"); } @Test @Order(20) void testHeaderRejectedWhenHeadersDisabled() { String normalToken = getAccessToken(NORMAL_USER, NORMAL_PASSWORD); CamelExecutionException ex = assertThrows(CamelExecutionException.class, () -> { template.requestBodyAndHeader("direct:max-security", "test", KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, normalToken, String.class); }); assertTrue(ex.getCause() instanceof CamelAuthorizationException); log.info("βœ“ Header correctly rejected when headers disabled"); } @Test @Order(21) void testPropertyWorksWhenHeadersDisabled() { String normalToken = getAccessToken(NORMAL_USER, NORMAL_PASSWORD); String result = template.send("direct:max-security", exchange -> { exchange.setProperty(KeycloakSecurityConstants.ACCESS_TOKEN_PROPERTY, normalToken); exchange.getIn().setBody("test"); }).getMessage().getBody(String.class); assertEquals("Access granted - max security", result); log.info("βœ“ Property works when headers disabled"); } @Test @Order(30) void testPropertyTokenUsedNotHeader() { String normalToken = getAccessToken(NORMAL_USER, NORMAL_PASSWORD); String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD); String result = template.send("direct:secure-default", exchange -> { exchange.setProperty(KeycloakSecurityConstants.ACCESS_TOKEN_PROPERTY, normalToken); exchange.getIn().setHeader(KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, adminToken); exchange.getIn().setBody("test"); }).getMessage().getBody(String.class); assertEquals("Access granted - secure default", result); log.info("βœ“ Property token preferred - attack vector mitigated"); } @Test @Order(31) void testAttackScenario_SessionHijacking() { String victimToken = getAccessToken(NORMAL_USER, NORMAL_PASSWORD); String attackerToken = getAccessToken(ATTACKER_USER, ATTACKER_PASSWORD); String result = template.send("direct:secure-default", exchange -> { exchange.setProperty(KeycloakSecurityConstants.ACCESS_TOKEN_PROPERTY, victimToken); exchange.getIn().setHeader(KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, attackerToken); exchange.getIn().setBody("hijack attempt"); }).getMessage().getBody(String.class); assertEquals("Access granted - secure default", result); log.info("βœ“ BLOCKED: Session hijacking prevented"); } @Test @Order(32) void testAuthorizationHeaderFormat() { String normalToken = getAccessToken(NORMAL_USER, NORMAL_PASSWORD); String result = template.requestBodyAndHeader("direct:secure-default", "test", "Authorization", "Bearer " + normalToken, String.class); assertEquals("Access granted - secure default", result); log.info("βœ“ Authorization Bearer header works"); } @Test @Order(33) void testNoTokenRejected() { CamelExecutionException ex = assertThrows(CamelExecutionException.class, () -> { template.sendBody("direct:secure-default", "test"); }); assertTrue(ex.getCause() instanceof CamelAuthorizationException); assertTrue(ex.getCause().getMessage().contains("Access token not found")); log.info("βœ“ Request without token correctly rejected"); } private String getAccessToken(String username, String password) { try (Client client = ClientBuilder.newClient()) { String tokenUrl = keycloakService.getKeycloakServerUrl() + "/realms/" + TEST_REALM_NAME + "/protocol/openid-connect/token"; Form form = new Form() .param("grant_type", "password") .param("client_id", TEST_CLIENT_ID) .param("client_secret", TEST_CLIENT_SECRET) .param("username", username) .param("password", password); try (Response response = client.target(tokenUrl) .request(MediaType.APPLICATION_JSON) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED))) { if (response.getStatus() == 200) { @SuppressWarnings("unchecked") Map<String, Object> tokenResponse = response.readEntity(Map.class); return (String) tokenResponse.get("access_token"); } else { String errorBody = response.readEntity(String.class); log.error("Failed to obtain token for user {}. Status: {}, Response: {}", username, response.getStatus(), errorBody); throw new RuntimeException( "Failed to obtain access token for " + username + ". Status: " + response.getStatus() + ", Error: " + errorBody); } } } catch (Exception e) { throw new RuntimeException("Error obtaining access token for " + username, e); } } }
KeycloakTokenBindingSecurityIT
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/application/ApplicationImpl.java
{ "start": 20869, "end": 21334 }
class ____ implements SingleArcTransition<ApplicationImpl, ApplicationEvent> { @Override public void transition(ApplicationImpl app, ApplicationEvent event) { // Start all the containers waiting for ApplicationInit for (Container container : app.containers.values()) { app.dispatcher.getEventHandler().handle(new ContainerInitEvent( container.getContainerId())); } } } static final
AppInitDoneTransition
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/Heartbeat.java
{ "start": 1265, "end": 4893 }
class ____ { private final int maxPollIntervalMs; private final GroupRebalanceConfig rebalanceConfig; private final Time time; private final Timer heartbeatTimer; private final Timer sessionTimer; private final Timer pollTimer; private final Logger log; private final ExponentialBackoff retryBackoff; private volatile long lastHeartbeatSend = 0L; private volatile boolean heartbeatInFlight = false; private volatile long heartbeatAttempts = 0L; public Heartbeat(GroupRebalanceConfig config, Time time) { if (config.heartbeatIntervalMs >= config.sessionTimeoutMs) throw new IllegalArgumentException("Heartbeat must be set lower than the session timeout"); this.rebalanceConfig = config; this.time = time; this.heartbeatTimer = time.timer(config.heartbeatIntervalMs); this.sessionTimer = time.timer(config.sessionTimeoutMs); this.maxPollIntervalMs = config.rebalanceTimeoutMs; this.pollTimer = time.timer(maxPollIntervalMs); this.retryBackoff = new ExponentialBackoff(rebalanceConfig.retryBackoffMs, CommonClientConfigs.RETRY_BACKOFF_EXP_BASE, rebalanceConfig.retryBackoffMaxMs, CommonClientConfigs.RETRY_BACKOFF_JITTER); final LogContext logContext = new LogContext("[Heartbeat groupID=" + config.groupId + "] "); this.log = logContext.logger(getClass()); } private void update(long now) { heartbeatTimer.update(now); sessionTimer.update(now); pollTimer.update(now); } public void poll(long now) { update(now); pollTimer.reset(maxPollIntervalMs); } boolean hasInflight() { return heartbeatInFlight; } void sentHeartbeat(long now) { lastHeartbeatSend = now; heartbeatInFlight = true; update(now); heartbeatTimer.reset(rebalanceConfig.heartbeatIntervalMs); if (log.isTraceEnabled()) { log.trace("Sending heartbeat request with {}ms remaining on timer", heartbeatTimer.remainingMs()); } } void failHeartbeat() { update(time.milliseconds()); heartbeatInFlight = false; heartbeatTimer.reset(retryBackoff.backoff(heartbeatAttempts++)); log.trace("Heartbeat failed, reset the timer to {}ms remaining", heartbeatTimer.remainingMs()); } void receiveHeartbeat() { update(time.milliseconds()); heartbeatInFlight = false; heartbeatAttempts = 0L; sessionTimer.reset(rebalanceConfig.sessionTimeoutMs); } boolean shouldHeartbeat(long now) { update(now); return heartbeatTimer.isExpired(); } long lastHeartbeatSend() { return this.lastHeartbeatSend; } long timeToNextHeartbeat(long now) { update(now); return heartbeatTimer.remainingMs(); } boolean sessionTimeoutExpired(long now) { update(now); return sessionTimer.isExpired(); } void resetTimeouts() { update(time.milliseconds()); sessionTimer.reset(rebalanceConfig.sessionTimeoutMs); pollTimer.reset(maxPollIntervalMs); heartbeatTimer.reset(rebalanceConfig.heartbeatIntervalMs); } void resetSessionTimeout() { update(time.milliseconds()); sessionTimer.reset(rebalanceConfig.sessionTimeoutMs); } boolean pollTimeoutExpired(long now) { update(now); return pollTimer.isExpired(); } long lastPollTime() { return pollTimer.currentTimeMs(); } }
Heartbeat
java
apache__camel
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/RestJettyGetCustomHttpBindingTest.java
{ "start": 1228, "end": 2549 }
class ____ extends BaseJettyTest { @BindToRegistry("mybinding") private JettyRestHttpBinding binding = new MyCustomHttpBinding("I was here;"); @Test public void testJettyProducerGet() { String out = template.requestBody("http://localhost:" + getPort() + "/users/123/basic", null, String.class); assertEquals("I was here;123;Donald Duck", out); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // configure to use jetty on localhost with the given port restConfiguration().component("jetty").host("localhost").port(getPort()).endpointProperty("httpBinding", "#mybinding"); // use the rest DSL to define the rest services rest("/users/").get("{id}/basic").to("direct:basic"); from("direct:basic").to("mock:input").process(new Processor() { public void process(Exchange exchange) { String id = exchange.getIn().getHeader("id", String.class); exchange.getMessage().setBody(id + ";Donald Duck"); } }); } }; } }
RestJettyGetCustomHttpBindingTest
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/classloading/jar/UserCodeType.java
{ "start": 1205, "end": 1299 }
class ____ by the {@link org.apache.flink.test.classloading.ClassLoaderITCase}. * * <p>This
used
java
quarkusio__quarkus
test-framework/security-jwt/src/main/java/io/quarkus/test/security/jwt/Claim.java
{ "start": 216, "end": 781 }
interface ____ { /** * Claim name */ String key(); /** * Claim value */ String value(); /** * Claim value type. * If this type is set to {@link ClaimType#DEFAULT} then the value will be converted to String unless the claim * is a standard claim such as `exp` (expiry), `iat` (issued at), `nbf` (not before), `auth_time` (authentication time) * whose value will be converted to Long or `email_verified` whose value will be converted to Boolean. */ ClaimType type() default ClaimType.DEFAULT; }
Claim
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/concurrent/AbstractConcurrentInitializerCloseAndExceptionsTest.java
{ "start": 1751, "end": 1897 }
class ____ to create a {@link ConcurrentInitializer} object on which the * tests are executed. * * @param <T> Domain type. */ public abstract
have
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/JournalSet.java
{ "start": 14767, "end": 24859 }
class ____ extends EditLogOutputStream { JournalSetOutputStream() throws IOException { super(); } /** * Get the last txId journalled in the stream. * The txId is recorded when FSEditLogOp is written to the journal. * JournalSet tracks the txId uniformly for all underlying streams. */ @Override public long getLastJournalledTxId() { return lastJournalledTxId; } @Override public void write(final FSEditLogOp op) throws IOException { mapJournalsAndReportErrors(new JournalClosure() { @Override public void apply(JournalAndStream jas) throws IOException { if (jas.isActive()) { jas.getCurrentStream().write(op); } } }, "write op"); assert lastJournalledTxId < op.txid : "TxId order violation for op=" + op + ", lastJournalledTxId=" + lastJournalledTxId; lastJournalledTxId = op.txid; } @Override public void writeRaw(final byte[] data, final int offset, final int length) throws IOException { mapJournalsAndReportErrors(new JournalClosure() { @Override public void apply(JournalAndStream jas) throws IOException { if (jas.isActive()) { jas.getCurrentStream().writeRaw(data, offset, length); } } }, "write bytes"); } @Override public void create(final int layoutVersion) throws IOException { mapJournalsAndReportErrors(new JournalClosure() { @Override public void apply(JournalAndStream jas) throws IOException { if (jas.isActive()) { jas.getCurrentStream().create(layoutVersion); } } }, "create"); } @Override public void close() throws IOException { mapJournalsAndReportErrors(new JournalClosure() { @Override public void apply(JournalAndStream jas) throws IOException { jas.closeStream(); } }, "close"); } @Override public void abort() throws IOException { mapJournalsAndReportErrors(new JournalClosure() { @Override public void apply(JournalAndStream jas) throws IOException { jas.abort(); } }, "abort"); } @Override public void setReadyToFlush() throws IOException { mapJournalsAndReportErrors(new JournalClosure() { @Override public void apply(JournalAndStream jas) throws IOException { if (jas.isActive()) { jas.getCurrentStream().setReadyToFlush(); } } }, "setReadyToFlush"); } @Override protected void flushAndSync(final boolean durable) throws IOException { mapJournalsAndReportErrors(new JournalClosure() { @Override public void apply(JournalAndStream jas) throws IOException { if (jas.isActive()) { jas.getCurrentStream().flushAndSync(durable); } } }, "flushAndSync"); } @Override public void flush() throws IOException { mapJournalsAndReportErrors(new JournalClosure() { @Override public void apply(JournalAndStream jas) throws IOException { if (jas.isActive()) { jas.getCurrentStream().flush(); } } }, "flush"); } @Override public boolean shouldForceSync() { for (JournalAndStream js : journals) { if (js.isActive() && js.getCurrentStream().shouldForceSync()) { return true; } } return false; } @Override protected long getNumSync() { for (JournalAndStream jas : journals) { if (jas.isActive()) { return jas.getCurrentStream().getNumSync(); } } return 0; } } @Override public void setOutputBufferCapacity(final int size) { try { mapJournalsAndReportErrors(new JournalClosure() { @Override public void apply(JournalAndStream jas) throws IOException { jas.getManager().setOutputBufferCapacity(size); } }, "setOutputBufferCapacity"); } catch (IOException e) { LOG.error("Error in setting outputbuffer capacity"); } } List<JournalAndStream> getAllJournalStreams() { return journals; } List<JournalManager> getJournalManagers() { List<JournalManager> jList = new ArrayList<JournalManager>(); for (JournalAndStream j : journals) { jList.add(j.getManager()); } return jList; } void add(JournalManager j, boolean required) { add(j, required, false); } void add(JournalManager j, boolean required, boolean shared) { JournalAndStream jas = new JournalAndStream(j, required, shared); journals.add(jas); } void remove(JournalManager j) { JournalAndStream jasToRemove = null; for (JournalAndStream jas: journals) { if (jas.getManager().equals(j)) { jasToRemove = jas; break; } } if (jasToRemove != null) { jasToRemove.abort(); journals.remove(jasToRemove); } } @Override public void purgeLogsOlderThan(final long minTxIdToKeep) throws IOException { mapJournalsAndReportErrors(new JournalClosure() { @Override public void apply(JournalAndStream jas) throws IOException { jas.getManager().purgeLogsOlderThan(minTxIdToKeep); } }, "purgeLogsOlderThan " + minTxIdToKeep); } @Override public void recoverUnfinalizedSegments() throws IOException { mapJournalsAndReportErrors(new JournalClosure() { @Override public void apply(JournalAndStream jas) throws IOException { jas.getManager().recoverUnfinalizedSegments(); } }, "recoverUnfinalizedSegments"); } /** * Return a manifest of what finalized edit logs are available. All available * edit logs are returned starting from the transaction id passed. If * 'fromTxId' falls in the middle of a log, that log is returned as well. * * @param fromTxId Starting transaction id to read the logs. * @return RemoteEditLogManifest object. */ public synchronized RemoteEditLogManifest getEditLogManifest(long fromTxId) { // Collect RemoteEditLogs available from each FileJournalManager List<RemoteEditLog> allLogs = new ArrayList<>(); for (JournalAndStream j : journals) { if (j.getManager() instanceof FileJournalManager) { FileJournalManager fjm = (FileJournalManager)j.getManager(); try { allLogs.addAll(fjm.getRemoteEditLogs(fromTxId, false)); } catch (Throwable t) { LOG.warn("Cannot list edit logs in " + fjm, t); } } } // Group logs by their starting txid final Map<Long, List<RemoteEditLog>> logsByStartTxId = new HashMap<>(); allLogs.forEach(input -> { long key = RemoteEditLog.GET_START_TXID.apply(input); logsByStartTxId.computeIfAbsent(key, k-> new ArrayList<>()).add(input); }); long curStartTxId = fromTxId; List<RemoteEditLog> logs = new ArrayList<>(); while (true) { List<RemoteEditLog> logGroup = logsByStartTxId.getOrDefault(curStartTxId, Collections.emptyList()); if (logGroup.isEmpty()) { // we have a gap in logs - for example because we recovered some old // storage directory with ancient logs. Clear out any logs we've // accumulated so far, and then skip to the next segment of logs // after the gap. SortedSet<Long> startTxIds = new TreeSet<>(logsByStartTxId.keySet()); startTxIds = startTxIds.tailSet(curStartTxId); if (startTxIds.isEmpty()) { break; } else { if (LOG.isDebugEnabled()) { LOG.debug("Found gap in logs at " + curStartTxId + ": " + "not returning previous logs in manifest."); } logs.clear(); curStartTxId = startTxIds.first(); continue; } } // Find the one that extends the farthest forward RemoteEditLog bestLog = Collections.max(logGroup); logs.add(bestLog); // And then start looking from after that point curStartTxId = bestLog.getEndTxId() + 1; } RemoteEditLogManifest ret = new RemoteEditLogManifest(logs, curStartTxId - 1); if (LOG.isDebugEnabled()) { LOG.debug("Generated manifest for logs since " + fromTxId + ":" + ret); } return ret; } /** * Add sync times to the buffer. */ String getSyncTimes() { StringBuilder buf = new StringBuilder(); for (JournalAndStream jas : journals) { if (jas.isActive()) { buf.append(jas.getCurrentStream().getTotalSyncTime()) .append(" "); } } return buf.toString(); } @Override public void doPreUpgrade() throws IOException { // This operation is handled by FSEditLog directly. throw new UnsupportedOperationException(); } @Override public void doUpgrade(Storage storage) throws IOException { // This operation is handled by FSEditLog directly. throw new UnsupportedOperationException(); } @Override public void doFinalize() throws IOException { // This operation is handled by FSEditLog directly. throw new UnsupportedOperationException(); } @Override public boolean canRollBack(StorageInfo storage, StorageInfo prevStorage, int targetLayoutVersion) throws IOException { // This operation is handled by FSEditLog directly. throw new UnsupportedOperationException(); } @Override public void doRollback() throws IOException { // This operation is handled by FSEditLog directly. throw new UnsupportedOperationException(); } @Override public void discardSegments(long startTxId) throws IOException { // This operation is handled by FSEditLog directly. throw new UnsupportedOperationException(); } @Override public long getJournalCTime() throws IOException { // This operation is handled by FSEditLog directly. throw new UnsupportedOperationException(); } }
JournalSetOutputStream
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/verification/VerificationOnMultipleMocksUsingMatchersTest.java
{ "start": 415, "end": 1658 }
class ____ extends TestBase { @Test public void shouldVerifyUsingMatchers() throws Exception { List<Object> list = Mockito.mock(List.class); HashMap<Object, Object> map = Mockito.mock(HashMap.class); list.add("test"); list.add(1, "test two"); map.put("test", 100); map.put("test two", 200); verify(list).add(any()); verify(list).add(anyInt(), eq("test two")); verify(map, times(2)).put(any(), any()); verify(map).put(eq("test two"), eq(200)); verifyNoMoreInteractions(list, map); } @Test public void shouldVerifyMultipleMocks() throws Exception { List<String> list = mock(List.class); Map<Object, Integer> map = mock(Map.class); Set<?> set = mock(Set.class); list.add("one"); list.add("one"); list.add("two"); map.put("one", 1); map.put("one", 1); verify(list, times(2)).add("one"); verify(list, times(1)).add("two"); verify(list, times(0)).add("three"); verify(map, times(2)).put(any(), anyInt()); verifyNoMoreInteractions(list, map); verifyNoInteractions(set); } }
VerificationOnMultipleMocksUsingMatchersTest
java
apache__camel
components/camel-jpa/src/test/java/org/apache/camel/component/jpa/AbstractJpaMethodTest.java
{ "start": 1410, "end": 5834 }
class ____ extends AbstractJpaMethodSupport { protected Customer receivedCustomer; abstract boolean usePersist(); @Test public void produceNewEntity() throws Exception { setUp("jpa://" + Customer.class.getName() + "?usePersist=" + (usePersist() ? "true" : "false")); Customer customer = createDefaultCustomer(); Customer receivedCustomer = template.requestBody(endpoint, customer, Customer.class); assertEquals(customer.getName(), receivedCustomer.getName()); assertNotNull(receivedCustomer.getId()); assertEquals(customer.getAddress().getAddressLine1(), receivedCustomer.getAddress().getAddressLine1()); assertEquals(customer.getAddress().getAddressLine2(), receivedCustomer.getAddress().getAddressLine2()); assertNotNull(receivedCustomer.getAddress().getId()); List<?> results = entityManager.createQuery("select o from " + Customer.class.getName() + " o").getResultList(); assertEquals(1, results.size()); Customer persistedCustomer = (Customer) results.get(0); assertEquals(receivedCustomer.getName(), persistedCustomer.getName()); assertEquals(receivedCustomer.getId(), persistedCustomer.getId()); assertEquals(receivedCustomer.getAddress().getAddressLine1(), persistedCustomer.getAddress().getAddressLine1()); assertEquals(receivedCustomer.getAddress().getAddressLine2(), persistedCustomer.getAddress().getAddressLine2()); assertEquals(receivedCustomer.getAddress().getId(), persistedCustomer.getAddress().getId()); } @Test public void produceNewEntitiesFromList() throws Exception { setUp("jpa://" + List.class.getName() + "?usePersist=" + (usePersist() ? "true" : "false")); List<Customer> customers = new ArrayList<>(); customers.add(createDefaultCustomer()); customers.add(createDefaultCustomer()); List<?> returnedCustomers = template.requestBody(endpoint, customers, List.class); assertEquals(2, returnedCustomers.size()); assertEntitiesInDatabase(2, Customer.class.getName()); assertEntitiesInDatabase(2, Address.class.getName()); } @Test public void produceNewEntitiesFromArray() throws Exception { setUp("jpa://" + Customer[].class.getName() + "?usePersist=" + (usePersist() ? "true" : "false")); Customer[] customers = new Customer[] { createDefaultCustomer(), createDefaultCustomer() }; Object reply = template.requestBody(endpoint, customers); Customer[] returnedCustomers = (Customer[]) reply; assertEquals(2, returnedCustomers.length); assertEntitiesInDatabase(2, Customer.class.getName()); assertEntitiesInDatabase(2, Address.class.getName()); } @Test public void consumeEntity() throws Exception { setUp("jpa://" + Customer.class.getName() + "?usePersist=" + (usePersist() ? "true" : "false")); final Customer customer = createDefaultCustomer(); save(customer); assertEntitiesInDatabase(1, Customer.class.getName()); assertEntitiesInDatabase(1, Address.class.getName()); final CountDownLatch latch = new CountDownLatch(1); consumer = endpoint.createConsumer(new Processor() { public void process(Exchange e) { receivedCustomer = e.getIn().getBody(Customer.class); assertNotNull(e.getIn().getHeader(JpaConstants.ENTITY_MANAGER, EntityManager.class)); latch.countDown(); } }); consumer.start(); assertTrue(latch.await(50, TimeUnit.SECONDS)); consumer.stop(); Thread.sleep(1000); assertNotNull(receivedCustomer); assertEquals(customer.getName(), receivedCustomer.getName()); assertEquals(customer.getId(), receivedCustomer.getId()); assertEquals(customer.getAddress().getAddressLine1(), receivedCustomer.getAddress().getAddressLine1()); assertEquals(customer.getAddress().getAddressLine2(), receivedCustomer.getAddress().getAddressLine2()); assertEquals(customer.getAddress().getId(), receivedCustomer.getAddress().getId()); // give a bit time for consumer to delete after done Thread.sleep(1000); assertEntitiesInDatabase(0, Customer.class.getName()); assertEntitiesInDatabase(0, Address.class.getName()); } }
AbstractJpaMethodTest
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/node/SBreak.java
{ "start": 661, "end": 1103 }
class ____ extends AStatement { public SBreak(int identifier, Location location) { super(identifier, location); } @Override public <Scope> void visit(UserTreeVisitor<Scope> userTreeVisitor, Scope scope) { userTreeVisitor.visitBreak(this, scope); } @Override public <Scope> void visitChildren(UserTreeVisitor<Scope> userTreeVisitor, Scope scope) { // terminal node; no children } }
SBreak
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/ConfigurationTest.java
{ "start": 929, "end": 4850 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot( jar -> jar.addClasses(HelloClientWithBaseUri.class, EchoResource.class, EchoClientWithEmptyPath.class)) .withConfigurationResource("configuration-test-application.properties"); @RestClient HelloClientWithBaseUri client; @RestClient EchoClientWithEmptyPath echoClientWithEmptyPath; @Inject RestClientsConfig restClientsConfig; @Test void shouldHaveSingletonScope() { BeanManager beanManager = Arc.container().beanManager(); Set<Bean<?>> beans = beanManager.getBeans(HelloClientWithBaseUri.class, RestClient.LITERAL); Bean<?> resolvedBean = beanManager.resolve(beans); assertThat(resolvedBean.getScope()).isEqualTo(Singleton.class); } @Test void clientShouldRespond() { assertThat(client.echo("world")).isEqualTo("hi, world!"); } @Test void checkClientSpecificConfigs() { RestClientsConfig.RestClientConfig clientConfig = restClientsConfig.getClient(HelloClientWithBaseUri.class); verifyClientConfig(clientConfig, true); clientConfig = restClientsConfig.getClient(ConfigKeyClient.class); verifyClientConfig(clientConfig, true); assertThat(clientConfig.proxyAddress().isPresent()).isTrue(); assertThat(clientConfig.proxyAddress().get()).isEqualTo("localhost:8080"); assertThat(clientConfig.headers()).containsOnly(entry("user-agent", "MP REST Client"), entry("foo", "bar")); clientConfig = restClientsConfig.getClient(QuotedConfigKeyClient.class); assertThat(clientConfig.url().isPresent()).isTrue(); assertThat(clientConfig.url().get()).endsWith("/hello"); assertThat(clientConfig.headers()).containsOnly(entry("foo", "bar")); clientConfig = restClientsConfig.getClient(MPConfigKeyClient.class); verifyClientConfig(clientConfig, false); } @Test void emptyPathAnnotationShouldWork() { assertThat(echoClientWithEmptyPath.echo("hello", "hello world")).isEqualTo("hello world"); } private void verifyClientConfig(RestClientsConfig.RestClientConfig clientConfig, boolean checkExtraProperties) { assertTrue(clientConfig.url().isPresent()); assertThat(clientConfig.url().get()).endsWith("/hello"); assertTrue(clientConfig.providers().isPresent()); assertThat(clientConfig.providers().get()) .isEqualTo("io.quarkus.rest.client.reactive.HelloClientWithBaseUri$MyResponseFilter"); assertTrue(clientConfig.connectTimeout().isPresent()); assertThat(clientConfig.connectTimeout().get()).isEqualTo(5000); assertTrue(clientConfig.readTimeout().isPresent()); assertThat(clientConfig.readTimeout().get()).isEqualTo(6000); assertTrue(clientConfig.followRedirects().isPresent()); assertThat(clientConfig.followRedirects().get()).isEqualTo(true); assertTrue(clientConfig.queryParamStyle().isPresent()); assertThat(clientConfig.queryParamStyle().get()).isEqualTo(QueryParamStyle.COMMA_SEPARATED); if (checkExtraProperties) { assertTrue(clientConfig.connectionTTL().isPresent()); assertThat(clientConfig.connectionTTL().getAsInt()).isEqualTo(30000); assertTrue(clientConfig.connectionPoolSize().isPresent()); assertThat(clientConfig.connectionPoolSize().getAsInt()).isEqualTo(10); assertTrue(clientConfig.keepAliveEnabled().isPresent()); assertThat(clientConfig.keepAliveEnabled().get()).isFalse(); assertTrue(clientConfig.maxRedirects().isPresent()); assertThat(clientConfig.maxRedirects().getAsInt()).isEqualTo(5); } } @RegisterRestClient(configKey = "client-prefix") @Path("/") public
ConfigurationTest
java
elastic__elasticsearch
modules/lang-expression/src/test/java/org/elasticsearch/script/expression/ExpressionDoubleValuesScriptTests.java
{ "start": 1353, "end": 4067 }
class ____ extends ESTestCase { private ExpressionScriptEngine engine; private ScriptService scriptService; @Override public void setUp() throws Exception { super.setUp(); engine = new ExpressionScriptEngine(); scriptService = new ScriptService( Settings.EMPTY, Map.of("expression", engine), ScriptModule.CORE_CONTEXTS, () -> 1L, TestProjectResolvers.singleProject(randomProjectIdOrDefault()) ); } @SuppressWarnings("unchecked") private DoubleValuesScript compile(String expression) { var script = new Script(ScriptType.INLINE, "expression", expression, Collections.emptyMap()); return scriptService.compile(script, DoubleValuesScript.CONTEXT).newInstance(); } public void testCompileError() { ScriptException e = expectThrows(ScriptException.class, () -> compile("10 * log(10)")); assertTrue(e.getCause() instanceof ParseException); assertEquals("Invalid expression '10 * log(10)': Unrecognized function call (log).", e.getCause().getMessage()); } public void testEvaluate() { var expression = compile("10 * log10(10)"); assertEquals("10 * log10(10)", expression.sourceText()); assertEquals(10.0, expression.evaluate(new DoubleValues[0]), 0.00001); assertEquals(10.0, expression.execute(), 0.00001); expression = compile("20 * log10(a)"); assertEquals("20 * log10(a)", expression.sourceText()); assertEquals(20.0, expression.evaluate(new DoubleValues[] { DoubleValues.withDefault(DoubleValues.EMPTY, 10.0) }), 0.00001); } public void testDoubleValuesSource() throws IOException { SimpleBindings bindings = new SimpleBindings(); bindings.add("popularity", DoubleValuesSource.constant(5)); var expression = compile("10 * log10(popularity)"); var doubleValues = expression.getDoubleValuesSource((name) -> bindings.getDoubleValuesSource(name)); assertEquals("expr(10 * log10(popularity))", doubleValues.toString()); var values = doubleValues.getValues(null, null); assertTrue(values.advanceExact(0)); assertEquals(6, (int) values.doubleValue()); var sortField = expression.getSortField((name) -> bindings.getDoubleValuesSource(name), false); assertEquals("expr(10 * log10(popularity))", sortField.getField()); assertEquals(SortField.Type.CUSTOM, sortField.getType()); assertFalse(sortField.getReverse()); var rescorer = expression.getRescorer((name) -> bindings.getDoubleValuesSource(name)); assertNotNull(rescorer); } }
ExpressionDoubleValuesScriptTests
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/record/AbstractRecordBatch.java
{ "start": 850, "end": 1219 }
class ____ implements RecordBatch { @Override public boolean hasProducerId() { return RecordBatch.NO_PRODUCER_ID < producerId(); } @Override public long nextOffset() { return lastOffset() + 1; } @Override public boolean isCompressed() { return compressionType() != CompressionType.NONE; } }
AbstractRecordBatch
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/builder/LegacyErrorHandlerBuilderRef.java
{ "start": 1083, "end": 2628 }
class ____ extends LegacyErrorHandlerBuilderSupport implements ErrorHandlerRefProperties { public static final String DEFAULT_ERROR_HANDLER_BUILDER = ErrorHandlerRefProperties.DEFAULT_ERROR_HANDLER_BUILDER; private final ErrorHandlerRefConfiguration configuration = new ErrorHandlerRefConfiguration(); public LegacyErrorHandlerBuilderRef() { } public LegacyErrorHandlerBuilderRef(String ref) { this.configuration.setRef(ref); } @Override public boolean supportTransacted() { return configuration.isSupportTransacted(); } @Override public LegacyErrorHandlerBuilder cloneBuilder() { LegacyErrorHandlerBuilderRef answer = new LegacyErrorHandlerBuilderRef(configuration.getRef()); cloneBuilder(answer); return answer; } protected void cloneBuilder(LegacyErrorHandlerBuilderRef other) { other.setSupportTransacted(configuration.isSupportTransacted()); } public String getRef() { return configuration.getRef(); } @Override public void setRef(String ref) { configuration.setRef(ref); } @Override public boolean isSupportTransacted() { return configuration.isSupportTransacted(); } @Override public void setSupportTransacted(boolean supportTransacted) { configuration.setSupportTransacted(supportTransacted); } @Override public String toString() { return "ErrorHandlerBuilderRef[" + configuration.getRef() + "]"; } }
LegacyErrorHandlerBuilderRef
java
apache__kafka
clients/src/test/java/org/apache/kafka/clients/consumer/internals/TopicMetadataFetcherTest.java
{ "start": 2434, "end": 11240 }
class ____ { private final String topicName = "test"; private final Uuid topicId = Uuid.randomUuid(); private final Map<String, Uuid> topicIds = new HashMap<>() { { put(topicName, topicId); } }; private final TopicPartition tp0 = new TopicPartition(topicName, 0); private final int validLeaderEpoch = 0; private final MetadataResponse initialUpdateResponse = RequestTestUtils.metadataUpdateWithIds(1, singletonMap(topicName, 4), topicIds); private MockTime time = new MockTime(1); private SubscriptionState subscriptions; private ConsumerMetadata metadata; private MockClient client; private Metrics metrics; private ConsumerNetworkClient consumerClient; private TopicMetadataFetcher topicMetadataFetcher; @BeforeEach public void setup() { } private void assignFromUser(Set<TopicPartition> partitions) { subscriptions.assignFromUser(partitions); client.updateMetadata(initialUpdateResponse); // A dummy metadata update to ensure valid leader epoch. metadata.updateWithCurrentRequestVersion(RequestTestUtils.metadataUpdateWithIds("dummy", 1, Collections.emptyMap(), singletonMap(topicName, 4), tp -> validLeaderEpoch, topicIds), false, 0L); } @AfterEach public void teardown() throws Exception { if (metrics != null) this.metrics.close(); } @Test public void testGetAllTopics() { // sending response before request, as getTopicMetadata is a blocking call buildFetcher(); assignFromUser(singleton(tp0)); client.prepareResponse(newMetadataResponse(Errors.NONE)); Map<String, List<PartitionInfo>> allTopics = topicMetadataFetcher.getAllTopicMetadata(time.timer(5000L)); assertEquals(initialUpdateResponse.topicMetadata().size(), allTopics.size()); } @Test public void testGetAllTopicsDisconnect() { // first try gets a disconnect, next succeeds buildFetcher(); assignFromUser(singleton(tp0)); client.prepareResponse(null, true); client.prepareResponse(newMetadataResponse(Errors.NONE)); Map<String, List<PartitionInfo>> allTopics = topicMetadataFetcher.getAllTopicMetadata(time.timer(5000L)); assertEquals(initialUpdateResponse.topicMetadata().size(), allTopics.size()); } @Test public void testGetAllTopicsTimeout() { // since no response is prepared, the request should time out buildFetcher(); assignFromUser(singleton(tp0)); assertThrows(TimeoutException.class, () -> topicMetadataFetcher.getAllTopicMetadata(time.timer(50L))); } @Test public void testGetAllTopicsUnauthorized() { buildFetcher(); assignFromUser(singleton(tp0)); client.prepareResponse(newMetadataResponse(Errors.TOPIC_AUTHORIZATION_FAILED)); try { topicMetadataFetcher.getAllTopicMetadata(time.timer(10L)); fail(); } catch (TopicAuthorizationException e) { assertEquals(singleton(topicName), e.unauthorizedTopics()); } } @Test public void testGetTopicMetadataInvalidTopic() { buildFetcher(); assignFromUser(singleton(tp0)); client.prepareResponse(newMetadataResponse(Errors.INVALID_TOPIC_EXCEPTION)); assertThrows(InvalidTopicException.class, () -> topicMetadataFetcher.getTopicMetadata(topicName, true, time.timer(5000L))); } @Test public void testGetTopicMetadataUnknownTopic() { buildFetcher(); assignFromUser(singleton(tp0)); client.prepareResponse(newMetadataResponse(Errors.UNKNOWN_TOPIC_OR_PARTITION)); List<PartitionInfo> topicMetadata = topicMetadataFetcher.getTopicMetadata(topicName, true, time.timer(5000L)); assertNull(topicMetadata); } @Test public void testGetTopicMetadataLeaderNotAvailable() { buildFetcher(); assignFromUser(singleton(tp0)); client.prepareResponse(newMetadataResponse(Errors.LEADER_NOT_AVAILABLE)); client.prepareResponse(newMetadataResponse(Errors.NONE)); List<PartitionInfo> topicMetadata = topicMetadataFetcher.getTopicMetadata(topicName, true, time.timer(5000L)); assertNotNull(topicMetadata); } @Test public void testGetTopicMetadataOfflinePartitions() { buildFetcher(); assignFromUser(singleton(tp0)); MetadataResponse originalResponse = newMetadataResponse(Errors.NONE); //baseline ok response //create a response based on the above one with all partitions being leaderless List<MetadataResponse.TopicMetadata> altTopics = new ArrayList<>(); for (MetadataResponse.TopicMetadata item : originalResponse.topicMetadata()) { List<MetadataResponse.PartitionMetadata> partitions = item.partitionMetadata(); List<MetadataResponse.PartitionMetadata> altPartitions = new ArrayList<>(); for (MetadataResponse.PartitionMetadata p : partitions) { altPartitions.add(new MetadataResponse.PartitionMetadata( p.error, p.topicPartition, Optional.empty(), //no leader Optional.empty(), p.replicaIds, p.inSyncReplicaIds, p.offlineReplicaIds )); } MetadataResponse.TopicMetadata alteredTopic = new MetadataResponse.TopicMetadata( item.error(), item.topic(), item.isInternal(), altPartitions ); altTopics.add(alteredTopic); } Node controller = originalResponse.controller(); MetadataResponse altered = RequestTestUtils.metadataResponse( originalResponse.brokers(), originalResponse.clusterId(), controller != null ? controller.id() : MetadataResponse.NO_CONTROLLER_ID, altTopics); client.prepareResponse(altered); List<PartitionInfo> topicMetadata = topicMetadataFetcher.getTopicMetadata(topicName, false, time.timer(5000L)); assertNotNull(topicMetadata); assertFalse(topicMetadata.isEmpty()); //noinspection ConstantConditions assertEquals(metadata.fetch().partitionCountForTopic(topicName).longValue(), topicMetadata.size()); } private MetadataResponse newMetadataResponse(Errors error) { List<MetadataResponse.PartitionMetadata> partitionsMetadata = new ArrayList<>(); if (error == Errors.NONE) { Optional<MetadataResponse.TopicMetadata> foundMetadata = initialUpdateResponse.topicMetadata() .stream() .filter(topicMetadata -> topicMetadata.topic().equals(topicName)) .findFirst(); foundMetadata.ifPresent(topicMetadata -> partitionsMetadata.addAll(topicMetadata.partitionMetadata())); } MetadataResponse.TopicMetadata topicMetadata = new MetadataResponse.TopicMetadata(error, topicName, false, partitionsMetadata); List<Node> brokers = new ArrayList<>(initialUpdateResponse.brokers()); return RequestTestUtils.metadataResponse(brokers, initialUpdateResponse.clusterId(), initialUpdateResponse.controller().id(), Collections.singletonList(topicMetadata)); } private void buildFetcher() { MetricConfig metricConfig = new MetricConfig(); long metadataExpireMs = Long.MAX_VALUE; long retryBackoffMs = 100; long retryBackoffMaxMs = 1000; LogContext logContext = new LogContext(); SubscriptionState subscriptionState = new SubscriptionState(logContext, AutoOffsetResetStrategy.EARLIEST); buildDependencies(metricConfig, metadataExpireMs, subscriptionState, logContext); topicMetadataFetcher = new TopicMetadataFetcher(logContext, consumerClient, retryBackoffMs, retryBackoffMaxMs); } private void buildDependencies(MetricConfig metricConfig, long metadataExpireMs, SubscriptionState subscriptionState, LogContext logContext) { time = new MockTime(1); subscriptions = subscriptionState; metadata = new ConsumerMetadata(0, 0, metadataExpireMs, false, false, subscriptions, logContext, new ClusterResourceListeners()); client = new MockClient(time, metadata); metrics = new Metrics(metricConfig, time); consumerClient = new ConsumerNetworkClient(logContext, client, metadata, time, 100, 1000, Integer.MAX_VALUE); } }
TopicMetadataFetcherTest
java
greenrobot__greendao
tests/DaoTestBase/src/main/java/org/greenrobot/greendao/daotest/AnActiveEntityDao.java
{ "start": 473, "end": 759 }
class ____ extends AbstractDao<AnActiveEntity, Long> { public static final String TABLENAME = "AN_ACTIVE_ENTITY"; /** * Properties of entity AnActiveEntity.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static
AnActiveEntityDao
java
spring-projects__spring-boot
module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilter.java
{ "start": 899, "end": 1189 }
class ____ implements FileFilter { private final String name; public TriggerFileFilter(String name) { Assert.notNull(name, "'name' must not be null"); this.name = name; } @Override public boolean accept(File file) { return file.getName().equals(this.name); } }
TriggerFileFilter
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportWithConditionTests.java
{ "start": 2561, "end": 2722 }
class ____ { } @Configuration @Conditional(NeverMatchingCondition.class) @Import(BeanProvidingConfiguration.class) protected static
UnconditionalConfiguration
java
spring-projects__spring-security
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson2/Saml2PostAuthenticationRequestMixin.java
{ "start": 1158, "end": 1883 }
class ____ in serialize/deserialize * {@link Saml2PostAuthenticationRequest}. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new Saml2Jackson2Module()); * </pre> * * @author Ulrich Grave * @since 5.7 * @see Saml2Jackson2Module * @see SecurityJackson2Modules * @deprecated as of 7.0 in favor of * {@code org.springframework.security.saml2.jackson.Saml2PostAuthenticationRequestMixin} * based on Jackson 3 */ @SuppressWarnings("removal") @Deprecated(forRemoval = true) @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(ignoreUnknown = true)
helps
java
quarkusio__quarkus
extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevUIProcessor.java
{ "start": 1413, "end": 5065 }
class ____ extends AbstractDevUIProcessor { OidcBuildTimeConfig oidcConfig; @Record(ExecutionTime.RUNTIME_INIT) @BuildStep(onlyIf = IsLocalDevelopment.class) @Consume(RuntimeConfigSetupCompleteBuildItem.class) void produceProviderComponent(Optional<KeycloakDevServicesConfigBuildItem> configProps, BuildProducer<KeycloakAdminPageBuildItem> keycloakAdminPageProducer, OidcDevUiRecorder recorder, NonApplicationRootPathBuildItem nonApplicationRootPathBuildItem, BeanContainerBuildItem beanContainer, Capabilities capabilities) { final String keycloakAdminUrl = KeycloakDevServicesConfigBuildItem.getKeycloakUrl(configProps); if (keycloakAdminUrl != null) { String realmUrl = configProps.get().getConfig().get("quarkus.oidc.auth-server-url"); @SuppressWarnings("unchecked") Map<String, String> users = (Map<String, String>) configProps.get().getProperties().get("oidc.users"); @SuppressWarnings("unchecked") final List<String> keycloakRealms = (List<String>) configProps.get().getProperties().get("keycloak.realms"); CardPageBuildItem cardPageBuildItem = createProviderWebComponent( recorder, capabilities, "Keycloak", getApplicationType(), oidcConfig.devui().grant().type().orElse(DevUiConfig.Grant.Type.CODE).getGrantType(), realmUrl + "/protocol/openid-connect/auth", realmUrl + "/protocol/openid-connect/token", realmUrl + "/protocol/openid-connect/logout", true, beanContainer, oidcConfig.devui().webClientTimeout(), oidcConfig.devui().grantOptions(), nonApplicationRootPathBuildItem, keycloakAdminUrl, users, keycloakRealms, configProps.get().isContainerRestarted(), false, null); cardPageBuildItem.setLogo("keycloak_logo.svg", "keycloak_logo.svg"); // use same card page so that both pages appear on the same card var keycloakAdminPageItem = new KeycloakAdminPageBuildItem(cardPageBuildItem); keycloakAdminPageProducer.produce(keycloakAdminPageItem); } } @BuildStep(onlyIf = IsLocalDevelopment.class) JsonRPCProvidersBuildItem produceOidcDevJsonRpcService() { return new JsonRPCProvidersBuildItem(OidcDevJsonRpcService.class); } @BuildStep(onlyIf = IsLocalDevelopment.class) AdditionalBeanBuildItem registerOidcDevLoginObserver() { // TODO: this is called even when Keycloak DEV UI is disabled and OIDC DEV UI is enabled // we should fine a mechanism to switch where the endpoints are registered or have shared build steps return AdditionalBeanBuildItem.unremovableOf(OidcDevLoginObserver.class); } @Record(ExecutionTime.RUNTIME_INIT) @BuildStep(onlyIf = IsLocalDevelopment.class) void invokeEndpoint(BuildProducer<RouteBuildItem> routeProducer, OidcDevUiRecorder recorder, NonApplicationRootPathBuildItem nonApplicationRootPathBuildItem) { // TODO: this is called even when Keycloak DEV UI is disabled and OIDC DEV UI is enabled // we should fine a mechanism to switch where the endpoints are registered or have shared build steps registerOidcWebAppRoutes(routeProducer, recorder, nonApplicationRootPathBuildItem); } }
KeycloakDevUIProcessor
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/FluxWindowWhenTest.java
{ "start": 2477, "end": 24678 }
class ____ { final int i; Wrapper(int i) { created.increment(); this.i = i; } @Override public String toString() { return "{i=" + i + '}'; } } MemoryUtils.RetainedDetector finalizedTracker = new MemoryUtils.RetainedDetector(); final CountDownLatch latch = new CountDownLatch(1); Flux<Wrapper> emitter = Flux.range(1, 400) .delayElements(Duration.ofMillis(10)) .map(i -> finalizedTracker.tracked(new Wrapper(i))); AtomicReference<FluxWindowWhen.WindowWhenMainSubscriber> startEndMain = new AtomicReference<>(); AtomicReference<List> windows = new AtomicReference<>(); LOGGER.info("stat[index, windows in flight, finalized] windowStart windowEnd:"); Mono<List<Tuple3<Long, Integer, Long>>> buffers = emitter.window(Duration.ofMillis(1000), Duration.ofMillis(500)) .doOnSubscribe(s -> { FluxWindowWhen.WindowWhenMainSubscriber sem = (FluxWindowWhen.WindowWhenMainSubscriber) s; startEndMain.set(sem); windows.set(sem.windows); }) .flatMap(Flux::collectList) .index().elapsed() .doOnNext(it -> System.gc()) //index, number of windows "in flight", finalized .map(elapsed -> { long millis = elapsed.getT1(); Tuple2<Long, List<Wrapper>> t2 = elapsed.getT2(); Tuple3<Long, Integer, Long> stat = Tuples.of(t2.getT1(), windows.get().size(), finalizedTracker.finalizedCount()); //log the window boundaries without retaining them in the tuple if (t2.getT2().isEmpty()) { LOGGER.info("{}ms : {} empty window", millis, stat); } else { LOGGER.info("{}ms : {}\t{}\t{}", millis, stat, t2.getT2().get(0), t2.getT2().get(t2.getT2().size() - 1)); } return stat; }) .doOnComplete(latch::countDown) .collectList(); List<Tuple3<Long, Integer, Long>> finalizeStats = buffers.block(); LOGGER.info("Tracked {} elements, collected {} windows", finalizedTracker.trackedTotal(), finalizeStats.size()); //at least 5 intermediate finalize Condition<? super Tuple3<Long, Integer, Long>> hasFinalized = new Condition<>( t3 -> t3.getT3() > 0, "has finalized"); assertThat(finalizeStats).areAtLeast(5, hasFinalized); assertThat(finalizeStats).allMatch(t3 -> t3.getT2() <= 5, "limited number of windows in flight"); latch.await(10, TimeUnit.SECONDS); System.gc(); Thread.sleep(500); assertThat(windows.get().size()) .as("no window retained") .isZero(); assertThat(finalizedTracker.finalizedCount()) .as("final GC collects all") .isEqualTo(created.longValue()); } @Test public void normal() { AssertSubscriber<Flux<Integer>> ts = AssertSubscriber.create(); Sinks.Many<Integer> sp1 = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> sp2 = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> sp3 = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> sp4 = Sinks.unsafe().many().multicast().directBestEffort(); sp1.asFlux().windowWhen(sp2.asFlux(), v -> v == 1 ? sp3.asFlux() : sp4.asFlux()) .subscribe(ts); sp1.emitNext(1, FAIL_FAST); sp2.emitNext(1, FAIL_FAST); sp1.emitNext(2, FAIL_FAST); sp2.emitNext(2, FAIL_FAST); sp1.emitNext(3, FAIL_FAST); sp3.emitNext(1, FAIL_FAST); sp1.emitNext(4, FAIL_FAST); sp4.emitNext(1, FAIL_FAST); sp1.emitComplete(FAIL_FAST); ts.assertValueCount(2) .assertNoError() .assertComplete(); expect(ts, 0, 2, 3); expect(ts, 1, 3, 4); assertThat(sp1.currentSubscriberCount()).as("sp1 has subscriber").isZero(); assertThat(sp2.currentSubscriberCount()).as("sp2 has subscriber").isZero(); assertThat(sp3.currentSubscriberCount()).as("sp3 has subscriber").isZero(); assertThat(sp4.currentSubscriberCount()).as("sp4 has subscriber").isZero(); } @Test public void normalStarterEnds() { AssertSubscriber<Flux<Integer>> ts = AssertSubscriber.create(); Sinks.Many<Integer> source = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> openSelector = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> closeSelectorFor1 = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> closeSelectorForOthers = Sinks.unsafe().many().multicast().directBestEffort(); source.asFlux().windowWhen(openSelector.asFlux(), v -> v == 1 ? closeSelectorFor1.asFlux() : closeSelectorForOthers.asFlux()) .subscribe(ts); source.emitNext(1, FAIL_FAST); openSelector.emitNext(1, FAIL_FAST); source.emitNext(2, FAIL_FAST); openSelector.emitNext(2, FAIL_FAST); source.emitNext(3, FAIL_FAST); closeSelectorFor1.emitNext(1, FAIL_FAST); source.emitNext(4, FAIL_FAST); closeSelectorForOthers.emitNext(1, FAIL_FAST); openSelector.emitComplete(FAIL_FAST); source.emitComplete(FAIL_FAST); //TODO evaluate, should the open completing cause the source to lose subscriber? ts.assertValueCount(2) .assertNoError() .assertComplete(); expect(ts, 0, 2, 3); expect(ts, 1, 3, 4); assertThat(openSelector.currentSubscriberCount()).as("openSelector has subscriber").isZero(); assertThat(closeSelectorFor1.currentSubscriberCount()).as("closeSelectorFor1 has subscriber").isZero(); assertThat(closeSelectorForOthers.currentSubscriberCount()).as("closeSelectorForOthers has subscriber").isZero(); assertThat(source.currentSubscriberCount()).as("source has subscriber").isZero(); } @Test public void oneWindowOnly() { AssertSubscriber<Flux<Integer>> ts = AssertSubscriber.create(); Sinks.Many<Integer> source = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> openSelector = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> closeSelectorFor1 = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> closeSelectorOthers = Sinks.unsafe().many().multicast().directBestEffort(); source.asFlux().windowWhen(openSelector.asFlux(), v -> v == 1 ? closeSelectorFor1.asFlux() : closeSelectorOthers.asFlux()) .subscribe(ts); openSelector.emitNext(1, FAIL_FAST); source.emitNext(1, FAIL_FAST); source.emitNext(2, FAIL_FAST); source.emitNext(3, FAIL_FAST); closeSelectorFor1.emitComplete(FAIL_FAST); source.emitNext(4, FAIL_FAST); source.emitComplete(FAIL_FAST); ts.assertValueCount(1) .assertNoError() .assertComplete(); expect(ts, 0, 1, 2, 3); assertThat(openSelector.currentSubscriberCount()).as("openSelector has subscriber").isZero(); assertThat(closeSelectorFor1.currentSubscriberCount()).as("closeSelectorFor1 has subscriber").isZero(); assertThat(closeSelectorOthers.currentSubscriberCount()).as("closeSelectorOthers has subscriber").isZero(); assertThat(source.currentSubscriberCount()).as("source has subscriber").isZero(); } @Test public void windowWillAccumulateMultipleListsOfValuesOverlap() { //given: "a source and a collected flux" Sinks.Many<Integer> numbers = Sinks.many().multicast().onBackpressureBuffer(); Sinks.Many<Integer> bucketOpening = Sinks.many().multicast().onBackpressureBuffer(); //"overlapping buffers" Sinks.Many<Integer> boundaryFlux = Sinks.many().multicast().onBackpressureBuffer(); StepVerifier.create(numbers.asFlux() .windowWhen(bucketOpening.asFlux(), u -> boundaryFlux.asFlux()) .flatMap(Flux::buffer) .collectList()) .then(() -> { numbers.emitNext(1, FAIL_FAST); numbers.emitNext(2, FAIL_FAST); bucketOpening.emitNext(1, FAIL_FAST); numbers.emitNext(3, FAIL_FAST); bucketOpening.emitNext(1, FAIL_FAST); numbers.emitNext(5, FAIL_FAST); boundaryFlux.emitNext(1, FAIL_FAST); bucketOpening.emitNext(1, FAIL_FAST); boundaryFlux.emitComplete(FAIL_FAST); numbers.emitComplete(FAIL_FAST); //"the collected overlapping lists are available" }) .assertNext(res -> assertThat(res).containsExactly(Arrays.asList(3, 5), Arrays.asList(5))) .verifyComplete(); } Flux<List<Integer>> scenario_windowWillSubdivideAnInputFluxOverlapTime() { return Flux.just(1, 2, 3, 4, 5, 6, 7, 8) .delayElements(Duration.ofMillis(99)) .window(Duration.ofMillis(300), Duration.ofMillis(200)) .concatMap(Flux::buffer, 1); } @Test public void windowWillSubdivideAnInputFluxOverlapTime() { StepVerifier.withVirtualTime(this::scenario_windowWillSubdivideAnInputFluxOverlapTime) .thenAwait(Duration.ofSeconds(10)) .assertNext(t -> assertThat(t).containsExactly(1, 2, 3)) .assertNext(t -> assertThat(t).containsExactly(3, 4, 5)) .assertNext(t -> assertThat(t).containsExactly(5, 6, 7)) .assertNext(t -> assertThat(t).containsExactly(7, 8)) .verifyComplete(); } Flux<List<Integer>> scenario_windowWillSubdivideAnInputFluxSameTime() { return Flux.just(1, 2, 3, 4, 5, 6, 7, 8) .delayElements(Duration.ofMillis(99)) .window(Duration.ofMillis(300), Duration.ofMillis(300)) .concatMap(Flux::buffer); } @Test public void windowWillSubdivideAnInputFluxSameTime() { StepVerifier.withVirtualTime(this::scenario_windowWillSubdivideAnInputFluxSameTime) .thenAwait(Duration.ofSeconds(10)) .assertNext(t -> assertThat(t).containsExactly(1, 2, 3)) .assertNext(t -> assertThat(t).containsExactly(4, 5, 6)) .assertNext(t -> assertThat(t).containsExactly(7, 8)) .verifyComplete(); } Flux<List<Integer>> scenario_windowWillSubdivideAnInputFluxGapTime() { return Flux.just(1, 2, 3, 4, 5, 6, 7, 8) .delayElements(Duration.ofMillis(99)) .window(Duration.ofMillis(200), Duration.ofMillis(300)) .concatMap(Flux::buffer); } @Test public void windowWillSubdivideAnInputFluxGapTime() { StepVerifier.withVirtualTime(this::scenario_windowWillSubdivideAnInputFluxGapTime) .thenAwait(Duration.ofSeconds(10)) .assertNext(t -> assertThat(t).containsExactly(1, 2)) .assertNext(t -> assertThat(t).containsExactly(4, 5)) .assertNext(t -> assertThat(t).containsExactly(7, 8)) .verifyComplete(); } @Test public void sourceError() { TestPublisher<Integer> source = TestPublisher.create(); TestPublisher<Integer> start = TestPublisher.create(); TestPublisher<Integer> end = TestPublisher.create(); StepVerifier.create(source.flux() .windowWhen(start, v -> end) .flatMap(Flux::materialize) ) .then(() -> start.next(1)) .then(() -> source.error( new IllegalStateException("expected failure"))) // failure observerd by window .expectNextMatches(signalSourceErrorMessage("expected failure")) // failure observed by main Flux .expectErrorMessage("expected failure") .verify(); source.assertNoSubscribers(); start.assertNoSubscribers(); end.assertNoSubscribers(); } private <T> Predicate<? super Signal<T>> signalSourceErrorMessage(String expectedMessage) { return signal -> signal.isOnError() && signal.getThrowable() != null && signal.getThrowable().getCause() != null && expectedMessage.equals(signal.getThrowable().getCause().getMessage()); } @Test public void startError() { TestPublisher<Integer> source = TestPublisher.create(); TestPublisher<Integer> start = TestPublisher.create(); final TestPublisher<Integer> end = TestPublisher.create(); StepVerifier.create(source.flux() .windowWhen(start, v -> end) .flatMap(Flux.identityFunction()) ) .then(() -> start.error(new IllegalStateException("boom"))) .expectErrorMessage("boom") .verify(); source.assertNoSubscribers(); start.assertNoSubscribers(); end.assertNoSubscribers(); } @Test public void startDoneThenError() { TestPublisher<Integer> source = TestPublisher.create(); TestPublisher<Integer> start = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE); final TestPublisher<Integer> end = TestPublisher.create(); StepVerifier.create(source.flux() .windowWhen(start, v -> end) .flatMap(Flux.identityFunction()) ) .then(() -> start.error(new IllegalStateException("boom")) .error(new IllegalStateException("boom2"))) .expectErrorMessage("boom") .verifyThenAssertThat() .hasDroppedErrorWithMessage("boom2"); source.assertNoSubscribers(); //start doesn't cleanup and as such still has a subscriber end.assertNoSubscribers(); } @Test public void startDoneThenComplete() { TestPublisher<Integer> source = TestPublisher.create(); TestPublisher<Integer> start = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE); final TestPublisher<Integer> end = TestPublisher.create(); StepVerifier.create(source.flux() .windowWhen(start, v -> end) .flatMap(Flux.identityFunction()) ) .then(() -> start.error(new IllegalStateException("boom")) .complete()) .expectErrorMessage("boom") .verifyThenAssertThat() .hasNotDroppedErrors(); source.assertNoSubscribers(); //start doesn't cleanup and as such still has a subscriber end.assertNoSubscribers(); } @Test public void startDoneThenNext() { TestPublisher<Integer> source = TestPublisher.create(); TestPublisher<Integer> start = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE); final TestPublisher<Integer> end = TestPublisher.create(); StepVerifier.create(source.flux() .windowWhen(start, v -> end) .flatMap(Flux.identityFunction()) ) .then(() -> start.error(new IllegalStateException("boom")) .next(1)) .expectErrorMessage("boom") .verifyThenAssertThat() .hasNotDroppedErrors() .hasNotDroppedElements(); source.assertNoSubscribers(); //start doesn't cleanup and as such still has a subscriber end.assertNoSubscribers(); } @Test public void endError() { TestPublisher<Integer> source = TestPublisher.create(); TestPublisher<Integer> start = TestPublisher.create(); TestPublisher<Integer> end = TestPublisher.create(); StepVerifier.create(source.flux() .windowWhen(start, v -> end) .flatMap(Flux.identityFunction()) ) .then(() -> start.next(1)) .then(() -> end.error(new IllegalStateException("boom"))) .expectErrorMessage("boom") .verify(); source.assertNoSubscribers(); start.assertNoSubscribers(); end.assertNoSubscribers(); } @Test public void endDoneThenError() { TestPublisher<Integer> source = TestPublisher.create(); TestPublisher<Integer> start = TestPublisher.create(); TestPublisher<Integer> end = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE); StepVerifier.create(source.flux() .windowWhen(start, v -> end) .flatMap(Flux.identityFunction()) ) .then(() -> start.next(1)) .then(() -> end.error(new IllegalStateException("boom")) .error(new IllegalStateException("boom2"))) .expectErrorMessage("boom") .verifyThenAssertThat() .hasDroppedErrorWithMessage("boom2"); source.assertNoSubscribers(); start.assertNoSubscribers(); //end doesn't cleanup and as such still has a subscriber } @Test public void endDoneThenComplete() { TestPublisher<Integer> source = TestPublisher.create(); TestPublisher<Integer> start = TestPublisher.create(); TestPublisher<Integer> end = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE); StepVerifier.create(source.flux() .windowWhen(start, v -> end) .flatMap(Flux.identityFunction()) ) .then(() -> start.next(1)) .then(() -> end.error(new IllegalStateException("boom")) .complete()) .expectErrorMessage("boom") .verifyThenAssertThat() .hasNotDroppedErrors(); source.assertNoSubscribers(); start.assertNoSubscribers(); //end doesn't cleanup and as such still has a subscriber } @Test public void endDoneThenNext() { TestPublisher<Integer> source = TestPublisher.create(); TestPublisher<Integer> start = TestPublisher.create(); TestPublisher<Integer> end = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE); StepVerifier.create(source.flux() .windowWhen(start, v -> end) .flatMap(Flux.identityFunction()) ) .then(() -> start.next(1)) .then(() -> end.error(new IllegalStateException("boom")) .next(1)) .expectErrorMessage("boom") .verifyThenAssertThat() .hasNotDroppedErrors() .hasNotDroppedElements(); source.assertNoSubscribers(); start.assertNoSubscribers(); //end doesn't cleanup and as such still has a subscriber } @Test public void mainError() { StepVerifier.create(Flux.error(new IllegalStateException("boom")) .windowWhen(Flux.never(), v -> Mono.just(1)) .flatMap(Flux::count)) .verifyErrorMessage("boom"); } @Test public void mainDoneThenNext() { TestPublisher<Integer> source = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE); StepVerifier.create(source.flux() .windowWhen(Flux.never(), v -> Mono.just(1)) .flatMap(Flux.identityFunction())) .then(() -> source.complete().next(1)) .expectComplete() .verifyThenAssertThat() .hasDropped(1); } @Test public void mainDoneThenError() { TestPublisher<Integer> source = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE); StepVerifier.create(source.flux() .windowWhen(Flux.never(), v -> Mono.just(1)) .flatMap(Flux.identityFunction())) .then(() -> source.complete().error(new IllegalStateException("boom"))) .expectComplete() .verifyThenAssertThat() .hasDroppedErrorWithMessage("boom"); } @Test public void mainDoneThenComplete() { TestPublisher<Integer> source = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE); StepVerifier.create(source.flux() .windowWhen(Flux.never(), v -> Mono.just(1)) .flatMap(Flux.identityFunction())) .then(() -> source.complete().complete()) .expectComplete() .verifyThenAssertThat() .hasNotDroppedErrors() .hasNotDroppedElements(); } @Test public void scanOperator(){ Flux<Integer> parent = Flux.just(1); FluxWindowWhen<Integer, Integer, Object> test = new FluxWindowWhen<>(parent, Flux.just(2), v -> Flux.empty(), Queues.empty()); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); } @Test public void scanMainSubscriber() { CoreSubscriber<Flux<Integer>> actual = new LambdaSubscriber<>(null, e -> {}, null, sub -> sub.request(1)); FluxWindowWhen.WindowWhenMainSubscriber<Integer, Integer, Integer> test = new FluxWindowWhen.WindowWhenMainSubscriber<>(actual, Flux.never(), Flux::just, Queues.unbounded()); Subscription parent = Operators.emptySubscription(); test.onSubscribe(parent); Assertions.assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); test.onComplete(); Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue(); Assertions.assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse(); test.cancel(); Assertions.assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue(); Assertions.assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)) .isEqualTo(0); test.request(123L); Assertions.assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)) .isEqualTo(123L); } @Test public void scanMainSubscriberError() { CoreSubscriber<Flux<Integer>> actual = new LambdaSubscriber<>(null, e -> {}, null, null); FluxWindowWhen.WindowWhenMainSubscriber<Integer, Integer, Integer> test = new FluxWindowWhen.WindowWhenMainSubscriber<>(actual, Flux.never(), Flux::just, Queues.unbounded()); Subscription parent = Operators.emptySubscription(); test.onSubscribe(parent); Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); Assertions.assertThat(test.scan(Scannable.Attr.ERROR)).isNull(); test.onError(new IllegalStateException("boom")); Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue(); Assertions.assertThat(test.scan(Scannable.Attr.ERROR)) .isNotNull() .hasMessage("boom"); } }
Wrapper
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/recovery/NMLeveldbStateStoreService.java
{ "start": 11811, "end": 27740 }
class ____ extends BaseRecoveryIterator<RecoveredContainerState> { ContainerStateIterator() throws IOException { super(CONTAINERS_KEY_PREFIX); } @Override protected RecoveredContainerState getNextItem(LeveldbIterator it) throws IOException { return getNextRecoveredContainer(it); } } private RecoveredContainerState getNextRecoveredContainer(LeveldbIterator it) throws IOException { RecoveredContainerState rcs = null; try { while (it.hasNext()) { Entry<byte[], byte[]> entry = it.peekNext(); String key = asString(entry.getKey()); if (!key.startsWith(CONTAINERS_KEY_PREFIX)) { return null; } int idEndPos = key.indexOf('/', CONTAINERS_KEY_PREFIX.length()); if (idEndPos < 0) { throw new IOException("Unable to determine container in key: " + key); } String keyPrefix = key.substring(0, idEndPos + 1); rcs = loadContainerState(it, keyPrefix); if (rcs.startRequest != null) { break; } else { removeContainer(rcs.getContainerId()); rcs = null; } } } catch (DBException e) { throw new IOException(e); } return rcs; } @Override public RecoveryIterator<RecoveredContainerState> getContainerStateIterator() throws IOException { return new ContainerStateIterator(); } private RecoveredContainerState loadContainerState(LeveldbIterator iter, String keyPrefix) throws IOException { ContainerId containerId = ContainerId.fromString( keyPrefix.substring(CONTAINERS_KEY_PREFIX.length(), keyPrefix.length()-1)); RecoveredContainerState rcs = new RecoveredContainerState(containerId); rcs.status = RecoveredContainerStatus.REQUESTED; while (iter.hasNext()) { Entry<byte[],byte[]> entry = iter.peekNext(); String key = asString(entry.getKey()); if (!key.startsWith(keyPrefix)) { break; } iter.next(); String suffix = key.substring(keyPrefix.length()-1); // start with '/' if (suffix.equals(CONTAINER_REQUEST_KEY_SUFFIX)) { rcs.startRequest = new StartContainerRequestPBImpl( StartContainerRequestProto.parseFrom(entry.getValue())); ContainerTokenIdentifier containerTokenIdentifier = BuilderUtils .newContainerTokenIdentifier(rcs.startRequest.getContainerToken()); rcs.capability = new ResourcePBImpl( containerTokenIdentifier.getProto().getResource()); } else if (suffix.equals(CONTAINER_VERSION_KEY_SUFFIX)) { rcs.version = Integer.parseInt(asString(entry.getValue())); } else if (suffix.equals(CONTAINER_START_TIME_KEY_SUFFIX)) { rcs.setStartTime(Long.parseLong(asString(entry.getValue()))); } else if (suffix.equals(CONTAINER_DIAGS_KEY_SUFFIX)) { rcs.diagnostics = asString(entry.getValue()); } else if (suffix.equals(CONTAINER_QUEUED_KEY_SUFFIX)) { if (rcs.status == RecoveredContainerStatus.REQUESTED) { rcs.status = RecoveredContainerStatus.QUEUED; } } else if (suffix.equals(CONTAINER_PAUSED_KEY_SUFFIX)) { if ((rcs.status == RecoveredContainerStatus.LAUNCHED) ||(rcs.status == RecoveredContainerStatus.QUEUED) ||(rcs.status == RecoveredContainerStatus.REQUESTED)) { rcs.status = RecoveredContainerStatus.PAUSED; } } else if (suffix.equals(CONTAINER_LAUNCHED_KEY_SUFFIX)) { if ((rcs.status == RecoveredContainerStatus.REQUESTED) || (rcs.status == RecoveredContainerStatus.QUEUED) ||(rcs.status == RecoveredContainerStatus.PAUSED)) { rcs.status = RecoveredContainerStatus.LAUNCHED; } } else if (suffix.equals(CONTAINER_KILLED_KEY_SUFFIX)) { rcs.killed = true; } else if (suffix.equals(CONTAINER_EXIT_CODE_KEY_SUFFIX)) { rcs.status = RecoveredContainerStatus.COMPLETED; rcs.exitCode = Integer.parseInt(asString(entry.getValue())); } else if (suffix.equals(CONTAINER_UPDATE_TOKEN_SUFFIX)) { ContainerTokenIdentifierProto tokenIdentifierProto = ContainerTokenIdentifierProto.parseFrom(entry.getValue()); Token currentToken = rcs.getStartRequest().getContainerToken(); Token updatedToken = Token .newInstance(tokenIdentifierProto.toByteArray(), ContainerTokenIdentifier.KIND.toString(), currentToken.getPassword().array(), currentToken.getService()); rcs.startRequest.setContainerToken(updatedToken); rcs.capability = new ResourcePBImpl(tokenIdentifierProto.getResource()); rcs.version = tokenIdentifierProto.getVersion(); } else if (suffix.equals(CONTAINER_REMAIN_RETRIES_KEY_SUFFIX)) { rcs.setRemainingRetryAttempts( Integer.parseInt(asString(entry.getValue()))); } else if (suffix.equals(CONTAINER_RESTART_TIMES_SUFFIX)) { String value = asString(entry.getValue()); // parse the string format of List<Long>, e.g. [34, 21, 22] String[] unparsedRestartTimes = value.substring(1, value.length() - 1).split(", "); List<Long> restartTimes = new ArrayList<>(); for (String restartTime : unparsedRestartTimes) { if (!restartTime.isEmpty()) { restartTimes.add(Long.parseLong(restartTime)); } } rcs.setRestartTimes(restartTimes); } else if (suffix.equals(CONTAINER_WORK_DIR_KEY_SUFFIX)) { rcs.setWorkDir(asString(entry.getValue())); } else if (suffix.equals(CONTAINER_LOG_DIR_KEY_SUFFIX)) { rcs.setLogDir(asString(entry.getValue())); } else if (suffix.startsWith(CONTAINER_ASSIGNED_RESOURCES_KEY_SUFFIX)) { String resourceType = suffix.substring( CONTAINER_ASSIGNED_RESOURCES_KEY_SUFFIX.length()); ResourceMappings.AssignedResources assignedResources = ResourceMappings.AssignedResources.fromBytes(entry.getValue()); rcs.getResourceMappings().addAssignedResources(resourceType, assignedResources); } else { LOG.warn("the container " + containerId + " will be killed because of the unknown key " + key + " during recovery."); containerUnknownKeySuffixes.put(containerId, suffix); rcs.setRecoveryType(RecoveredContainerType.KILL); } } return rcs; } @Override public void storeContainer(ContainerId containerId, int containerVersion, long startTime, StartContainerRequest startRequest) throws IOException { String idStr = containerId.toString(); LOG.debug("storeContainer: containerId= {}, startRequest= {}", idStr, startRequest); final String keyVersion = getContainerVersionKey(idStr); final String keyRequest = getContainerKey(idStr, CONTAINER_REQUEST_KEY_SUFFIX); final StartContainerRequestProto startContainerRequest = ((StartContainerRequestPBImpl) startRequest).getProto(); final String keyStartTime = getContainerKey(idStr, CONTAINER_START_TIME_KEY_SUFFIX); final String startTimeValue = Long.toString(startTime); try { try (WriteBatch batch = db.createWriteBatch()) { batch.put(bytes(keyRequest), startContainerRequest.toByteArray()); batch.put(bytes(keyStartTime), bytes(startTimeValue)); if (containerVersion != 0) { batch.put(bytes(keyVersion), bytes(Integer.toString(containerVersion))); } db.write(batch); } } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @VisibleForTesting String getContainerVersionKey(String containerId) { return getContainerKey(containerId, CONTAINER_VERSION_KEY_SUFFIX); } private String getContainerKey(String containerId, String suffix) { return CONTAINERS_KEY_PREFIX + containerId + suffix; } @Override public void storeContainerQueued(ContainerId containerId) throws IOException { LOG.debug("storeContainerQueued: containerId={}", containerId); String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_QUEUED_KEY_SUFFIX; try { db.put(bytes(key), EMPTY_VALUE); } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } private void removeContainerQueued(ContainerId containerId) throws IOException { LOG.debug("removeContainerQueued: containerId={}", containerId); String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_QUEUED_KEY_SUFFIX; try { db.delete(bytes(key)); } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @Override public void storeContainerPaused(ContainerId containerId) throws IOException { LOG.debug("storeContainerPaused: containerId={}", containerId); String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_PAUSED_KEY_SUFFIX; try { db.put(bytes(key), EMPTY_VALUE); } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @Override public void removeContainerPaused(ContainerId containerId) throws IOException { LOG.debug("removeContainerPaused: containerId={}", containerId); String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_PAUSED_KEY_SUFFIX; try { db.delete(bytes(key)); } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @Override public void storeContainerDiagnostics(ContainerId containerId, StringBuilder diagnostics) throws IOException { LOG.debug("storeContainerDiagnostics: containerId={}, diagnostics=", containerId, diagnostics); String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_DIAGS_KEY_SUFFIX; try { db.put(bytes(key), bytes(diagnostics.toString())); } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @Override public void storeContainerLaunched(ContainerId containerId) throws IOException { LOG.debug("storeContainerLaunched: containerId={}", containerId); // Removing the container if queued for backward compatibility reasons removeContainerQueued(containerId); String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_LAUNCHED_KEY_SUFFIX; try { db.put(bytes(key), EMPTY_VALUE); } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @Override public void storeContainerUpdateToken(ContainerId containerId, ContainerTokenIdentifier containerTokenIdentifier) throws IOException { LOG.debug("storeContainerUpdateToken: containerId={}", containerId); String keyUpdateToken = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_UPDATE_TOKEN_SUFFIX; String keyVersion = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_VERSION_KEY_SUFFIX; try { WriteBatch batch = db.createWriteBatch(); try { // New value will overwrite old values for the same key batch.put(bytes(keyUpdateToken), containerTokenIdentifier.getProto().toByteArray()); batch.put(bytes(keyVersion), bytes(Integer.toString(containerTokenIdentifier.getVersion()))); db.write(batch); } finally { batch.close(); } } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @Override public void storeContainerKilled(ContainerId containerId) throws IOException { LOG.debug("storeContainerKilled: containerId={}", containerId); String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_KILLED_KEY_SUFFIX; try { db.put(bytes(key), EMPTY_VALUE); } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @Override public void storeContainerCompleted(ContainerId containerId, int exitCode) throws IOException { LOG.debug("storeContainerCompleted: containerId={}", containerId); String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_EXIT_CODE_KEY_SUFFIX; try { db.put(bytes(key), bytes(Integer.toString(exitCode))); } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @Override public void storeContainerRemainingRetryAttempts(ContainerId containerId, int remainingRetryAttempts) throws IOException { String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_REMAIN_RETRIES_KEY_SUFFIX; try { db.put(bytes(key), bytes(Integer.toString(remainingRetryAttempts))); } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @Override public void storeContainerRestartTimes(ContainerId containerId, List<Long> restartTimes) throws IOException { String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_RESTART_TIMES_SUFFIX; try { db.put(bytes(key), bytes(restartTimes.toString())); } catch (DBException e) { throw new IOException(e); } } @Override public void storeContainerWorkDir(ContainerId containerId, String workDir) throws IOException { String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_WORK_DIR_KEY_SUFFIX; try { db.put(bytes(key), bytes(workDir)); } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @Override public void storeContainerLogDir(ContainerId containerId, String logDir) throws IOException { String key = CONTAINERS_KEY_PREFIX + containerId.toString() + CONTAINER_LOG_DIR_KEY_SUFFIX; try { db.put(bytes(key), bytes(logDir)); } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } @Override public void removeContainer(ContainerId containerId) throws IOException { LOG.debug("removeContainer: containerId={}", containerId); String keyPrefix = CONTAINERS_KEY_PREFIX + containerId.toString(); try { WriteBatch batch = db.createWriteBatch(); try { batch.delete(bytes(keyPrefix + CONTAINER_REQUEST_KEY_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_DIAGS_KEY_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_LAUNCHED_KEY_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_QUEUED_KEY_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_PAUSED_KEY_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_KILLED_KEY_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_EXIT_CODE_KEY_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_UPDATE_TOKEN_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_START_TIME_KEY_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_LOG_DIR_KEY_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_VERSION_KEY_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_REMAIN_RETRIES_KEY_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_RESTART_TIMES_SUFFIX)); batch.delete(bytes(keyPrefix + CONTAINER_WORK_DIR_KEY_SUFFIX)); List<String> unknownKeysForContainer = containerUnknownKeySuffixes .removeAll(containerId); for (String unknownKeySuffix : unknownKeysForContainer) { batch.delete(bytes(keyPrefix + unknownKeySuffix)); } db.write(batch); } finally { batch.close(); } } catch (DBException e) { markStoreUnHealthy(e); throw new IOException(e); } } // Application Recovery Iterator private
ContainerStateIterator
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaWithPartitionByTest.java
{ "start": 1183, "end": 2742 }
class ____ { @BeforeEach void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { final DisplayItem displayItem20_1 = new DisplayItem(); displayItem20_1.setId( 1 ); displayItem20_1.setDiscountCode( "20" ); displayItem20_1.setDiscountValue( 12.34d ); final DisplayItem displayItem20_2 = new DisplayItem(); displayItem20_2.setId( 2 ); displayItem20_2.setDiscountCode( "20" ); displayItem20_2.setDiscountValue( 15.89 ); final DisplayItem displayItem100 = new DisplayItem(); displayItem100.setId( 3 ); displayItem100.setDiscountCode( "100" ); displayItem100.setDiscountValue( 12.5 ); session.persist( displayItem20_1 ); session.persist( displayItem20_2 ); session.persist( displayItem100 ); } ); } @Test @JiraKey( value = "HHH-10754" ) void testFormulaAnnotationWithPartitionBy(SessionFactoryScope scope) { scope.inTransaction( session -> { final List<DisplayItem> displayItems = session.createQuery( "select di from DisplayItem di order by di.id", DisplayItem.class).getResultList(); assertNotNull( displayItems ); assertEquals( 3, displayItems.size() ); assertEquals( 1, displayItems.get( 0 ).getItemsByCode().intValue() ); assertEquals( 2, displayItems.get( 1 ).getItemsByCode().intValue() ); assertEquals( 1, displayItems.get( 2 ).getItemsByCode().intValue() ); } ); } @AfterEach void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Entity(name = "DisplayItem") public static
FormulaWithPartitionByTest
java
apache__flink
flink-formats/flink-protobuf/src/main/java/org/apache/flink/formats/protobuf/serialize/RowToProtoConverter.java
{ "start": 2062, "end": 5867 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(ProtoToRowConverter.class); private final Method encodeMethod; private boolean isCodeSplit = false; public RowToProtoConverter(RowType rowType, PbFormatConfig formatConfig) throws PbCodegenException { try { Descriptors.Descriptor descriptor = PbFormatUtils.getDescriptor(formatConfig.getMessageClassName()); PbFormatContext formatContext = new PbFormatContext(formatConfig, false); PbCodegenAppender codegenAppender = new PbCodegenAppender(0); String uuid = UUID.randomUUID().toString().replace("-", ""); String generatedClassName = "GeneratedRowToProto_" + uuid; String generatedPackageName = RowToProtoConverter.class.getPackage().getName(); codegenAppender.appendLine("package " + generatedPackageName); codegenAppender.appendLine("import " + AbstractMessage.class.getName()); codegenAppender.appendLine("import " + Descriptors.class.getName()); codegenAppender.appendLine("import " + RowData.class.getName()); codegenAppender.appendLine("import " + ArrayData.class.getName()); codegenAppender.appendLine("import " + StringData.class.getName()); codegenAppender.appendLine("import " + ByteString.class.getName()); codegenAppender.appendLine("import " + List.class.getName()); codegenAppender.appendLine("import " + ArrayList.class.getName()); codegenAppender.appendLine("import " + Map.class.getName()); codegenAppender.appendLine("import " + HashMap.class.getName()); codegenAppender.begin("public class " + generatedClassName + "{"); codegenAppender.begin( "public static AbstractMessage " + PbConstant.GENERATED_ENCODE_METHOD + "(RowData rowData){"); codegenAppender.appendLine("AbstractMessage message = null"); PbCodegenSerializer codegenSer = PbCodegenSerializeFactory.getPbCodegenTopRowSer( descriptor, rowType, formatContext); String genCode = codegenSer.codegen("message", "rowData", codegenAppender.currentIndent()); codegenAppender.appendSegment(genCode); codegenAppender.appendLine("return message"); codegenAppender.end("}"); if (!formatContext.getSplitMethodStack().isEmpty()) { isCodeSplit = true; for (String spliteMethod : formatContext.getSplitMethodStack()) { codegenAppender.appendSegment(spliteMethod); } } codegenAppender.end("}"); String printCode = codegenAppender.printWithLineNumber(); LOG.debug("Protobuf encode codegen: \n" + printCode); Class generatedClass = PbCodegenUtils.compileClass( Thread.currentThread().getContextClassLoader(), generatedPackageName + "." + generatedClassName, codegenAppender.code()); encodeMethod = generatedClass.getMethod(PbConstant.GENERATED_ENCODE_METHOD, RowData.class); } catch (Exception ex) { throw new PbCodegenException(ex); } } public byte[] convertRowToProtoBinary(RowData rowData) throws Exception { AbstractMessage message = (AbstractMessage) encodeMethod.invoke(null, rowData); return message.toByteArray(); } @VisibleForTesting protected boolean isCodeSplit() { return isCodeSplit; } }
RowToProtoConverter
java
quarkusio__quarkus
extensions/devui/runtime/src/main/java/io/quarkus/devui/runtime/jsonrpc/JsonRpcRequest.java
{ "start": 137, "end": 1406 }
class ____ { private int id; private String jsonrpc = JsonRpcKeys.VERSION; private String method; private Map<String, Object> params; private final JsonMapper jsonMapper; public JsonRpcRequest(JsonMapper jsonMapper) { this.jsonMapper = jsonMapper; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getJsonrpc() { return jsonrpc; } public void setJsonrpc(String jsonrpc) { this.jsonrpc = jsonrpc; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public Map getParams() { return params; } public void setParams(Map<String, Object> params) { this.params = params; } public boolean hasParams() { return this.params != null && !this.params.isEmpty(); } public boolean hasParam(String key) { return this.params != null && this.params.containsKey(key); } public <T> T getParam(String key, Class<T> paramType) { if (hasParam(key)) { return jsonMapper.fromValue(params.get(key), paramType); } return null; } }
JsonRpcRequest
java
elastic__elasticsearch
modules/lang-painless/src/test/java/org/elasticsearch/painless/BaseClassTests.java
{ "start": 965, "end": 2716 }
class ____ extends ScriptTestCase { protected Map<ScriptContext<?>, List<Whitelist>> scriptContexts() { Map<ScriptContext<?>, List<Whitelist>> contexts = new HashMap<>(); contexts.put(Gets.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(NoArgs.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(OneArg.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(ArrayArg.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(PrimitiveArrayArg.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(DefArrayArg.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(ManyArgs.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(VarArgs.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(DefaultMethods.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(ReturnsVoid.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(ReturnsPrimitiveBoolean.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(ReturnsPrimitiveInt.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(ReturnsPrimitiveFloat.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(ReturnsPrimitiveDouble.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(NoArgsConstant.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(WrongArgsConstant.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(WrongLengthOfArgConstant.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(UnknownArgType.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(UnknownReturnType.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(UnknownArgTypeInArray.CONTEXT, PAINLESS_BASE_WHITELIST); contexts.put(TwoExecuteMethods.CONTEXT, PAINLESS_BASE_WHITELIST); return contexts; } public abstract static
BaseClassTests
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng7244IgnorePomPrefixInExpressions.java
{ "start": 954, "end": 1949 }
class ____ extends AbstractMavenIntegrationTestCase { private static final String PROJECT_PATH = "/mng-7244-ignore-pom-prefix-in-expressions"; @Test public void testIgnorePomPrefixInExpressions() throws IOException, VerificationException { final File projectDir = extractResources(PROJECT_PATH); final Verifier verifier = newVerifier(projectDir.getAbsolutePath()); verifier.addCliArgument("validate"); verifier.execute(); verifyLogDoesNotContainUnexpectedWarning(verifier); } private void verifyLogDoesNotContainUnexpectedWarning(Verifier verifier) throws IOException { List<String> loadedLines = verifier.loadLines("log.txt"); for (String line : loadedLines) { if (line.startsWith("[WARNING]") && line.contains("The expression ${pom.version} is deprecated.")) { fail("Log contained unexpected deprecation warning"); } } } }
MavenITmng7244IgnorePomPrefixInExpressions
java
quarkusio__quarkus
extensions/smallrye-openapi/runtime/src/main/java/io/quarkus/smallrye/openapi/runtime/filter/AutoBearerTokenSecurityFilter.java
{ "start": 252, "end": 1548 }
class ____ extends AutoSecurityFilter { private String securitySchemeValue; private String bearerFormat; public AutoBearerTokenSecurityFilter() { super(); } public AutoBearerTokenSecurityFilter(String securitySchemeName, String securitySchemeDescription, Map<String, String> securitySchemeExtensions, String securitySchemeValue, String bearerFormat) { super(securitySchemeName, securitySchemeDescription, securitySchemeExtensions); this.securitySchemeValue = securitySchemeValue; this.bearerFormat = bearerFormat; } public String getSecuritySchemeValue() { return securitySchemeValue; } public void setSecuritySchemeValue(String securitySchemeValue) { this.securitySchemeValue = securitySchemeValue; } public String getBearerFormat() { return bearerFormat; } public void setBearerFormat(String bearerFormat) { this.bearerFormat = bearerFormat; } @Override protected void updateSecurityScheme(SecurityScheme securityScheme) { securityScheme.setType(SecurityScheme.Type.HTTP); securityScheme.setScheme(securitySchemeValue); securityScheme.setBearerFormat(bearerFormat); } }
AutoBearerTokenSecurityFilter
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakeException.java
{ "start": 1112, "end": 1977 }
class ____ extends WebSocketHandshakeException { private static final long serialVersionUID = 1L; private final HttpRequest request; public WebSocketServerHandshakeException(String message) { this(message, null); } public WebSocketServerHandshakeException(String message, HttpRequest httpRequest) { super(message); if (httpRequest != null) { request = new DefaultHttpRequest(httpRequest.protocolVersion(), httpRequest.method(), httpRequest.uri(), httpRequest.headers()); } else { request = null; } } /** * Returns a {@link HttpRequest request} if exception occurs during request validation otherwise {@code null}. */ public HttpRequest request() { return request; } }
WebSocketServerHandshakeException
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafeCheckerTest.java
{ "start": 32254, "end": 32663 }
class ____ { final ImmutableList<@ThreadSafeTypeParameter ?> unknownSafeType; X(ImmutableList<@ThreadSafeTypeParameter ?> unknownSafeType) { this.unknownSafeType = unknownSafeType; } } """) .addSourceLines( "Test.java", """ import com.google.common.collect.ImmutableList;
X
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/MlAssignmentNotifier.java
{ "start": 1991, "end": 18114 }
class ____ implements ClusterStateListener { private static final Logger logger = LogManager.getLogger(MlAssignmentNotifier.class); static final Duration MIN_CHECK_UNASSIGNED_INTERVAL = Duration.ofSeconds(30); static final Duration LONG_TIME_UNASSIGNED_INTERVAL = Duration.ofMinutes(15); static final Duration MIN_REPORT_INTERVAL = Duration.ofHours(6); private final AnomalyDetectionAuditor anomalyDetectionAuditor; private final DataFrameAnalyticsAuditor dataFrameAnalyticsAuditor; private final ThreadPool threadPool; private final Clock clock; private Map<TaskNameAndId, UnassignedTimeAndReportTime> unassignedInfoByTask = Map.of(); private volatile Instant lastLogCheck; MlAssignmentNotifier( AnomalyDetectionAuditor anomalyDetectionAuditor, DataFrameAnalyticsAuditor dataFrameAnalyticsAuditor, ThreadPool threadPool, ClusterService clusterService ) { this(anomalyDetectionAuditor, dataFrameAnalyticsAuditor, threadPool, clusterService, Clock.systemUTC()); } MlAssignmentNotifier( AnomalyDetectionAuditor anomalyDetectionAuditor, DataFrameAnalyticsAuditor dataFrameAnalyticsAuditor, ThreadPool threadPool, ClusterService clusterService, Clock clock ) { this.anomalyDetectionAuditor = anomalyDetectionAuditor; this.dataFrameAnalyticsAuditor = dataFrameAnalyticsAuditor; this.threadPool = threadPool; this.clock = clock; this.lastLogCheck = clock.instant(); clusterService.addListener(this); } private static String executorName() { return ThreadPool.Names.GENERIC; } @Override public void clusterChanged(ClusterChangedEvent event) { if (event.localNodeMaster() == false) { unassignedInfoByTask = Map.of(); return; } Instant now = clock.instant(); if (lastLogCheck.plus(MIN_CHECK_UNASSIGNED_INTERVAL).isBefore(now)) { lastLogCheck = now; threadPool.executor(executorName()).execute(() -> logLongTimeUnassigned(now, event.state())); } if (event.metadataChanged() == false) { return; } threadPool.executor(executorName()).execute(() -> auditChangesToMlTasks(event)); } private void auditChangesToMlTasks(ClusterChangedEvent event) { for (ProjectMetadata project : event.state().getMetadata().projects().values()) { final Metadata previousMetadata = event.previousState().getMetadata(); if (previousMetadata.hasProject(project.id()) == false) { continue; } final ProjectMetadata previousProject = previousMetadata.getProject(project.id()); PersistentTasksCustomMetadata previousTasks = previousProject.custom(PersistentTasksCustomMetadata.TYPE); PersistentTasksCustomMetadata currentTasks = project.custom(PersistentTasksCustomMetadata.TYPE); if (Objects.equals(previousTasks, currentTasks)) { continue; } auditMlTasks(project.id(), event.previousState().nodes(), event.state().nodes(), previousTasks, currentTasks, false); } } /** * Creates an audit warning for all currently unassigned ML * tasks, even if a previous audit warning has been created. * Care must be taken not to call this method frequently. */ public void auditUnassignedMlTasks(ProjectId projectId, DiscoveryNodes nodes, PersistentTasksCustomMetadata tasks) { auditMlTasks(projectId, nodes, nodes, tasks, tasks, true); } private void auditMlTasks( ProjectId projectId, DiscoveryNodes previousNodes, DiscoveryNodes currentNodes, PersistentTasksCustomMetadata previousTasks, PersistentTasksCustomMetadata currentTasks, boolean alwaysAuditUnassigned ) { if (currentTasks == null) { return; } if (Metadata.DEFAULT_PROJECT_ID.equals(projectId) == false) { @FixForMultiProject final Metadata.MultiProjectPendingException exception = new Metadata.MultiProjectPendingException( "Can only audit ML changes on the default project" ); throw exception; } for (PersistentTask<?> currentTask : currentTasks.tasks()) { Assignment currentAssignment = currentTask.getAssignment(); PersistentTask<?> previousTask = previousTasks != null ? previousTasks.getTask(currentTask.getId()) : null; Assignment previousAssignment = previousTask != null ? previousTask.getAssignment() : null; boolean isTaskAssigned = (currentAssignment.getExecutorNode() != null); if (Objects.equals(currentAssignment, previousAssignment) && (isTaskAssigned || alwaysAuditUnassigned == false)) { continue; } boolean wasTaskAssigned = (previousAssignment != null) && (previousAssignment.getExecutorNode() != null); if (MlTasks.JOB_TASK_NAME.equals(currentTask.getTaskName())) { String jobId = ((OpenJobAction.JobParams) currentTask.getParams()).getJobId(); if (isTaskAssigned) { String msg = "Opening job"; if (anomalyDetectionAuditor.includeNodeInfo()) { String nodeName = nodeName(currentNodes, currentAssignment.getExecutorNode()); msg += " on node [" + nodeName + "]"; } anomalyDetectionAuditor.info(jobId, msg); } else if (alwaysAuditUnassigned) { if (anomalyDetectionAuditor.includeNodeInfo()) { anomalyDetectionAuditor.warning( jobId, "No node found to open job. Reasons [" + currentAssignment.getExplanation() + "]" ); } else { anomalyDetectionAuditor.warning(jobId, "Awaiting capacity to open job."); } } else if (wasTaskAssigned) { if (anomalyDetectionAuditor.includeNodeInfo()) { String nodeName = nodeName(previousNodes, previousAssignment.getExecutorNode()); anomalyDetectionAuditor.info(jobId, "Job unassigned from node [" + nodeName + "]"); } else { anomalyDetectionAuditor.info(jobId, "Job relocating."); } } } else if (MlTasks.DATAFEED_TASK_NAME.equals(currentTask.getTaskName())) { StartDatafeedAction.DatafeedParams datafeedParams = (StartDatafeedAction.DatafeedParams) currentTask.getParams(); String jobId = datafeedParams.getJobId(); if (jobId != null) { if (isTaskAssigned) { String msg = "Starting datafeed [" + datafeedParams.getDatafeedId() + "]"; if (anomalyDetectionAuditor.includeNodeInfo()) { String nodeName = nodeName(currentNodes, currentAssignment.getExecutorNode()); msg += "] on node [" + nodeName + "]"; } anomalyDetectionAuditor.info(jobId, msg); } else { if (alwaysAuditUnassigned) { if (anomalyDetectionAuditor.includeNodeInfo()) { anomalyDetectionAuditor.warning( jobId, "No node found to start datafeed [" + datafeedParams.getDatafeedId() + "]. Reasons [" + currentAssignment.getExplanation() + "]" ); } else { anomalyDetectionAuditor.warning( jobId, "Awaiting capacity to start datafeed [" + datafeedParams.getDatafeedId() + "]." ); } } else if (wasTaskAssigned) { if (anomalyDetectionAuditor.includeNodeInfo()) { String nodeName = nodeName(previousNodes, previousAssignment.getExecutorNode()); anomalyDetectionAuditor.info( jobId, "Datafeed [" + datafeedParams.getDatafeedId() + "] unassigned from node [" + nodeName + "]" ); } else { anomalyDetectionAuditor.info(jobId, "Datafeed [" + datafeedParams.getDatafeedId() + "] relocating."); } } else { logger.warn( "[{}] No node found to start datafeed [{}]. Reasons [{}]", jobId, datafeedParams.getDatafeedId(), currentAssignment.getExplanation() ); } } } } else if (MlTasks.DATA_FRAME_ANALYTICS_TASK_NAME.equals(currentTask.getTaskName())) { String id = ((StartDataFrameAnalyticsAction.TaskParams) currentTask.getParams()).getId(); if (isTaskAssigned) { if (anomalyDetectionAuditor.includeNodeInfo()) { String nodeName = nodeName(currentNodes, currentAssignment.getExecutorNode()); dataFrameAnalyticsAuditor.info(id, "Starting analytics on node [" + nodeName + "]"); } else { dataFrameAnalyticsAuditor.info(id, "Starting analytics."); } } else if (alwaysAuditUnassigned) { if (anomalyDetectionAuditor.includeNodeInfo()) { dataFrameAnalyticsAuditor.warning( id, "No node found to start analytics. Reasons [" + currentAssignment.getExplanation() + "]" ); } else { dataFrameAnalyticsAuditor.warning(id, "Awaiting capacity to start analytics."); } } else if (wasTaskAssigned) { if (anomalyDetectionAuditor.includeNodeInfo()) { String nodeName = nodeName(previousNodes, previousAssignment.getExecutorNode()); anomalyDetectionAuditor.info(id, "Analytics unassigned from node [" + nodeName + "]"); } else { anomalyDetectionAuditor.info(id, "Analytics relocating."); } } } } } static String nodeName(DiscoveryNodes nodes, String nodeId) { // It's possible that we're reporting on a node that left the // cluster in an earlier cluster state update, in which case // the cluster state we've got doesn't record its friendly // name. In this case we have no choice but to use the ID. (We // also use the ID in tests that don't bother to name nodes.) DiscoveryNode node = nodes.get(nodeId); if (node != null && Strings.hasLength(node.getName())) { return node.getName(); } return nodeId; } private void logLongTimeUnassigned(Instant now, ClusterState state) { state.forEachProject(project -> { PersistentTasksCustomMetadata tasks = project.metadata().custom(PersistentTasksCustomMetadata.TYPE); if (tasks == null) { return; } List<String> itemsToReport = findLongTimeUnassignedTasks(now, tasks); if (itemsToReport.isEmpty() == false) { logger.warn( "In project [{}] ML persistent tasks unassigned for a long time [{}]", project.projectId(), String.join("|", itemsToReport) ); } }); } /** * Creates a list of items to be logged to report ML job tasks that: * 1. Have been unassigned for a long time * 2. Have not been logged recently (to avoid log spam) * <p> * Only report on jobs, not datafeeds, on the assumption that jobs and their corresponding * datafeeds get assigned together. This may miss some obscure edge cases, but will avoid * the verbose and confusing messages that the duplication between jobs and datafeeds would * generally cause. * <p> * The time intervals used in this reporting reset each time the master node changes, as * the data structure used to record the information is in memory on the current master node, * not in cluster state. */ synchronized List<String> findLongTimeUnassignedTasks(Instant now, PersistentTasksCustomMetadata tasks) { assert tasks != null; final List<String> itemsToReport = new ArrayList<>(); final Map<TaskNameAndId, UnassignedTimeAndReportTime> oldUnassignedInfoByTask = unassignedInfoByTask; final Map<TaskNameAndId, UnassignedTimeAndReportTime> newUnassignedInfoByTask = new HashMap<>(); for (PersistentTask<?> task : tasks.tasks()) { if (task.getExecutorNode() == null) { final String taskName = task.getTaskName(); if (MlTasks.JOB_TASK_NAME.equals(taskName) || MlTasks.DATA_FRAME_ANALYTICS_TASK_NAME.equals(taskName)) { // Ignore failed tasks - they don't need to be assigned to a node if (task.getState() == null || ((MlTaskState) task.getState()).isFailed()) { continue; } final String mlId = ((MlTaskParams) task.getParams()).getMlId(); final TaskNameAndId key = new TaskNameAndId(taskName, mlId); final UnassignedTimeAndReportTime previousInfo = oldUnassignedInfoByTask.get(key); final Instant firstUnassignedTime; final Instant lastReportedTime; if (previousInfo != null) { firstUnassignedTime = previousInfo.unassignedTime(); if (firstUnassignedTime.plus(LONG_TIME_UNASSIGNED_INTERVAL).isBefore(now) && (previousInfo.reportTime() == null || previousInfo.reportTime().plus(MIN_REPORT_INTERVAL).isBefore(now))) { lastReportedTime = now; itemsToReport.add( Strings.format( "[%s]/[%s] unassigned for [%d] seconds", taskName, mlId, ChronoUnit.SECONDS.between(firstUnassignedTime, now) ) ); } else { lastReportedTime = previousInfo.reportTime(); } } else { firstUnassignedTime = now; lastReportedTime = null; } newUnassignedInfoByTask.put(key, new UnassignedTimeAndReportTime(firstUnassignedTime, lastReportedTime)); } } } unassignedInfoByTask = newUnassignedInfoByTask; return itemsToReport; } private record TaskNameAndId(String taskName, String mlId) {}; private record UnassignedTimeAndReportTime(Instant unassignedTime, Instant reportTime) {}; }
MlAssignmentNotifier
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/support/startup/EnvStartupCondition.java
{ "start": 1091, "end": 1954 }
class ____ implements StartupCondition { private final String env; public EnvStartupCondition(String env) { ObjectHelper.notNullOrEmpty(env, "ENV"); this.env = env; } @Override public String getName() { return "ENV"; } @Override public String getWaitMessage() { return "Waiting for OS Environment Variable: " + env; } @Override public String getFailureMessage() { return "OS Environment Variable: " + env + " does not exist"; } protected String lookupEnvironmentVariable(String env) { return IOHelper.lookupEnvironmentVariable(env); } @Override public boolean canContinue(CamelContext camelContext) throws Exception { String value = lookupEnvironmentVariable(env); return ObjectHelper.isNotEmpty(value); } }
EnvStartupCondition
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Baz.java
{ "start": 424, "end": 8718 }
class ____ implements Named, Serializable, Comparable { private SortedSet stringSet; private Map stringDateMap; private List stringList; private int[] intArray; private FooProxy[] fooArray; private String[] stringArray; private String code="aaa"; private List customs; private List topComponents; private Set fooSet; private FooComponent[] components; private Date[] timeArray; private int count; private String name; private Collection bag; private Set topFoos; private Map topGlarchez; private Set cascadingBars; private Map fooToGlarch; private Map fooComponentToFoo; private Map glarchToFoo; private List fees; private Collection fooBag; private Set cached; private Map cachedMap; private Map stringGlarchMap; private Map anyToAny; private List manyToAny; private Collection idFooBag; private Collection byteBag; private FooProxy foo; private List bazez; private SortedSet sortablez; private NestingComponent collectionComponent; private String text; private List parts; private List moreParts; public List subs; public Baz superBaz; Baz() {} public SortedSet getStringSet() { return stringSet; } public void setStringSet(SortedSet stringSet) { this.stringSet = stringSet; } public Map getStringDateMap() { return stringDateMap; } public void setStringDateMap(Map stringDateMap) { this.stringDateMap = stringDateMap; } public List getStringList() { return stringList; } public void setStringList(List stringList) { this.stringList = stringList; } public int[] getIntArray() { return intArray; } public void setIntArray(int[] intArray) { this.intArray = intArray; } public FooProxy[] getFooArray() { return fooArray; } public void setFooArray(FooProxy[] fooArray) { this.fooArray = fooArray; } public String[] getStringArray() { return stringArray; } public void setStringArray(String[] stringArray) { this.stringArray = stringArray; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public void setDefaults() { SortedSet set = new TreeSet(); set.add("foo"); set.add("bar"); set.add("baz"); setStringSet(set); Map map = new TreeMap(); map.put( "now", new Date() ); map.put( "never", null ); map.put( "big bang", new Date(0) ); setStringDateMap(map); List list = new ArrayList(); list.addAll(set); setStringList(list); setIntArray( new int[] { 1,3,3,7 } ); setFooArray( new Foo[0] ); setStringArray( (String[]) list.toArray( new String[0] ) ); fooSet = new HashSet(); components = new FooComponent[] { new FooComponent("foo", 42, null, null), new FooComponent("bar", 88, null, new FooComponent("sub", 69, null, null) ) }; timeArray = new Date[] { new Date(), new Date(), null, new Date(0) }; TreeSet x = new TreeSet(); x.add("w"); x.add("x"); x.add("y"); x.add("z"); TreeSet a = new TreeSet(); a.add("a"); a.add("b"); a.add("d"); a.add("c"); count = 667; name="Bazza"; topComponents = new ArrayList(); topComponents.add( new FooComponent("foo", 11, new Date[] { new Date(), new Date(123) }, null) ); topComponents.add( new FooComponent("bar", 22, new Date[] { new Date(7), new Date(456) }, null) ); topComponents.add( null ); bag = new ArrayList(); bag.add("duplicate"); bag.add("duplicate"); bag.add("duplicate"); bag.add("unique"); cached = new TreeSet(); CompositeElement ce = new CompositeElement(); ce.setFoo("foo"); ce.setBar("bar"); CompositeElement ce2 = new CompositeElement(); ce2.setFoo("fooxxx"); ce2.setBar("barxxx"); cached.add(ce); cached.add(ce2); cachedMap = new TreeMap(); cachedMap.put(this, ce); text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; for (int i=0; i<10; i++) text+=text; } public Set getFooSet() { return fooSet; } public void setFooSet(Set fooSet) { this.fooSet = fooSet; } public FooComponent[] getComponents() { return components; } public void setComponents(FooComponent[] components) { this.components = components; } public Date[] getTimeArray() { return timeArray; } public void setTimeArray(Date[] timeArray) { this.timeArray = timeArray; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getTopComponents() { return topComponents; } public void setTopComponents(List topComponents) { this.topComponents = topComponents; } public Collection getBag() { return bag; } public void setBag(Collection bag) { this.bag = bag; } public Set getTopFoos() { return topFoos; } public void setTopFoos(Set topFoos) { this.topFoos = topFoos; } public Map getTopGlarchez() { return topGlarchez; } public void setTopGlarchez(Map topGlarchez) { this.topGlarchez = topGlarchez; } public Set getCascadingBars() { return cascadingBars; } public void setCascadingBars(Set cascadingBars) { this.cascadingBars = cascadingBars; } public Map getFooToGlarch() { return fooToGlarch; } public void setFooToGlarch(Map fooToGlarch) { this.fooToGlarch = fooToGlarch; } public Map getFooComponentToFoo() { return fooComponentToFoo; } public void setFooComponentToFoo(Map fooComponentToFoo) { this.fooComponentToFoo = fooComponentToFoo; } public Map getGlarchToFoo() { return glarchToFoo; } public void setGlarchToFoo(Map glarchToFoo) { this.glarchToFoo = glarchToFoo; } public List getFees() { return fees; } public void setFees(List fees) { this.fees = fees; } public Collection getFooBag() { return fooBag; } public void setFooBag(Collection fooBag) { this.fooBag = fooBag; } /** * Returns the cached. * @return Set */ public Set getCached() { return cached; } /** * Sets the cached. * @param cached The cached to set */ public void setCached(Set cached) { this.cached = cached; } /** * Returns the cachedMap. * @return Map */ public Map getCachedMap() { return cachedMap; } /** * Sets the cachedMap. * @param cachedMap The cachedMap to set */ public void setCachedMap(Map cachedMap) { this.cachedMap = cachedMap; } /** * @see Comparable#compareTo(Object) */ public int compareTo(Object o) { return ( (Baz) o ).code.compareTo(code); } /** * Returns the stringGlarchMap. * @return Map */ public Map getStringGlarchMap() { return stringGlarchMap; } /** * Sets the stringGlarchMap. * @param stringGlarchMap The stringGlarchMap to set */ public void setStringGlarchMap(Map stringGlarchMap) { this.stringGlarchMap = stringGlarchMap; } /** * Returns the anyToAny. * @return Map */ public Map getAnyToAny() { return anyToAny; } /** * Sets the anyToAny. * @param anyToAny The anyToAny to set */ public void setAnyToAny(Map anyToAny) { this.anyToAny = anyToAny; } public Collection getIdFooBag() { return idFooBag; } public void setIdFooBag(Collection collection) { idFooBag = collection; } public Collection getByteBag() { return byteBag; } public void setByteBag(Collection list) { byteBag = list; } public FooProxy getFoo() { return foo; } public void setFoo(FooProxy foo) { this.foo = foo; } public List getBazez() { return bazez; } public void setBazez(List list) { bazez = list; } public SortedSet getSortablez() { return sortablez; } public void setSortablez(SortedSet set) { sortablez = set; } public NestingComponent getCollectionComponent() { return collectionComponent; } public void setCollectionComponent(NestingComponent collection) { collectionComponent = collection; } /** * @return */ public String getText() { return text; } /** * @param string */ public void setText(String string) { text = string; } public List getParts() { return parts; } public void setParts(List list) { parts = list; } public List getManyToAny() { return manyToAny; } public void setManyToAny(List manyToAny) { this.manyToAny = manyToAny; } public List getMoreParts() { return moreParts; } public void setMoreParts(List moreParts) { this.moreParts = moreParts; } }
Baz
java
spring-projects__spring-security
oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java
{ "start": 1989, "end": 5601 }
class ____ { @Mock private ReactiveJwtDecoder jwtDecoder; private JwtReactiveAuthenticationManager manager; private Jwt jwt; @BeforeEach public void setup() { this.manager = new JwtReactiveAuthenticationManager(this.jwtDecoder); // @formatter:off this.jwt = TestJwts.jwt() .claim("scope", "message:read message:write") .build(); // @formatter:on } @Test public void constructorWhenJwtDecoderNullThenIllegalArgumentException() { this.jwtDecoder = null; // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> new JwtReactiveAuthenticationManager(this.jwtDecoder)); // @formatter:on } @Test public void authenticateWhenWrongTypeThenEmpty() { TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar"); assertThat(this.manager.authenticate(token).block()).isNull(); } @Test public void authenticateWhenEmptyJwtThenEmpty() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(token.getToken())).willReturn(Mono.empty()); assertThat(this.manager.authenticate(token).block()).isNull(); } @Test public void authenticateWhenJwtExceptionThenOAuth2AuthenticationException() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(any())).willReturn(Mono.error(new BadJwtException("Oops"))); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.manager.authenticate(token).block()); } // gh-7549 @Test public void authenticateWhenDecoderThrowsIncompatibleErrorMessageThenWrapsWithGenericOne() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(token.getToken())).willThrow(new BadJwtException("with \"invalid\" chars")); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.manager.authenticate(token).block()) .satisfies((ex) -> assertThat(ex) .hasFieldOrPropertyWithValue("error.description", "Invalid token") ); // @formatter:on } // gh-7785 @Test public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(token.getToken())).willThrow(new JwtException("no jwk set")); // @formatter:off assertThatExceptionOfType(AuthenticationException.class) .isThrownBy(() -> this.manager.authenticate(token).block()) .isNotInstanceOf(OAuth2AuthenticationException.class); // @formatter:on } @Test public void authenticateWhenNotJwtExceptionThenPropagates() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(any())).willReturn(Mono.error(new RuntimeException("Oops"))); // @formatter:off assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> this.manager.authenticate(token).block()); // @formatter:on } @Test public void authenticateWhenJwtThenSuccess() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(token.getToken())).willReturn(Mono.just(this.jwt)); Authentication authentication = this.manager.authenticate(token).block(); assertThat(authentication).isNotNull(); assertThat(authentication.isAuthenticated()).isTrue(); SecurityAssertions.assertThat(authentication).hasAuthorities("SCOPE_message:read", "SCOPE_message:write"); } }
JwtReactiveAuthenticationManagerTests
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/util/ReflectionUtils.java
{ "start": 49723, "end": 49864 }
interface ____ traversing up the type * hierarchy until such a method is found or the type hierarchy is exhausted. * * @param clazz the
and
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/SimpleInvokerTest.java
{ "start": 448, "end": 1340 }
class ____ { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .beanClasses(MyService.class) .beanRegistrars(new InvokerHelperRegistrar(MyService.class, (bean, factory, invokers) -> { MethodInfo method = bean.getImplClazz().firstMethod("hello"); invokers.put(method.name(), factory.createInvoker(bean, method).build()); })) .build(); @Test public void test() throws Exception { InvokerHelper helper = Arc.container().instance(InvokerHelper.class).get(); InstanceHandle<MyService> service = Arc.container().instance(MyService.class); Invoker<MyService, String> hello = helper.getInvoker("hello"); assertEquals("foobar0[]", hello.invoke(service.get(), new Object[] { 0, List.of() })); } @Singleton static
SimpleInvokerTest
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/io/parsing/TestResolvingGrammarGenerator.java
{ "start": 2108, "end": 6646 }
class ____ { @ParameterizedTest @MethodSource("data") void test(Schema schema, JsonNode data) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); EncoderFactory factory = EncoderFactory.get(); Encoder e = factory.validatingEncoder(schema, factory.binaryEncoder(baos, null)); ResolvingGrammarGenerator.encode(e, schema, data); e.flush(); } @Test void recordMissingRequiredFieldError() throws Exception { Schema schemaWithoutField = SchemaBuilder.record("MyRecord").namespace("ns").fields().name("field1").type() .stringType().noDefault().endRecord(); Schema schemaWithField = SchemaBuilder.record("MyRecord").namespace("ns").fields().name("field1").type() .stringType().noDefault().name("field2").type().stringType().noDefault().endRecord(); GenericData.Record record = new GenericRecordBuilder(schemaWithoutField).set("field1", "someValue").build(); byte[] data = writeRecord(schemaWithoutField, record); try { readRecord(schemaWithField, data); Assertions.fail("Expected exception not thrown"); } catch (AvroTypeException typeException) { Assertions.assertEquals("Found ns.MyRecord, expecting ns.MyRecord, missing required field field2", typeException.getMessage(), "Incorrect exception message"); } } @Test void differingEnumNamespaces() throws Exception { Schema schema1 = SchemaBuilder.record("MyRecord").fields().name("field").type(ENUM1_AB_SCHEMA_NAMESPACE_1) .noDefault().endRecord(); Schema schema2 = SchemaBuilder.record("MyRecord").fields().name("field").type(ENUM1_AB_SCHEMA_NAMESPACE_2) .noDefault().endRecord(); GenericData.EnumSymbol genericEnumSymbol = new GenericData.EnumSymbol(ENUM1_AB_SCHEMA_NAMESPACE_1, "A"); GenericData.Record record = new GenericRecordBuilder(schema1).set("field", genericEnumSymbol).build(); byte[] data = writeRecord(schema1, record); Assertions.assertEquals(genericEnumSymbol, readRecord(schema1, data).get("field")); Assertions.assertEquals(genericEnumSymbol, readRecord(schema2, data).get("field")); } public static Stream<Arguments> data() { Collection<String[]> ret = Arrays.asList(new String[][] { { "{ \"type\": \"record\", \"name\": \"r\", \"fields\": [ " + " { \"name\" : \"f1\", \"type\": \"int\" }, " + " { \"name\" : \"f2\", \"type\": \"float\" } " + "] }", "{ \"f2\": 10.4, \"f1\": 10 } " }, { "{ \"type\": \"enum\", \"name\": \"e\", \"symbols\": " + "[ \"s1\", \"s2\"] }", " \"s1\" " }, { "{ \"type\": \"enum\", \"name\": \"e\", \"symbols\": " + "[ \"s1\", \"s2\"] }", " \"s2\" " }, { "{ \"type\": \"fixed\", \"name\": \"f\", \"size\": 10 }", "\"hello\"" }, { "{ \"type\": \"array\", \"items\": \"int\" }", "[ 10, 20, 30 ]" }, { "{ \"type\": \"map\", \"values\": \"int\" }", "{ \"k1\": 10, \"k3\": 20, \"k3\": 30 }" }, { "[ \"int\", \"long\" ]", "10" }, { "\"string\"", "\"hello\"" }, { "\"bytes\"", "\"hello\"" }, { "\"int\"", "10" }, { "\"long\"", "10" }, { "\"float\"", "10.0" }, { "\"double\"", "10.0" }, { "\"boolean\"", "true" }, { "\"boolean\"", "false" }, { "\"null\"", "null" }, }); final JsonFactory factory = new JsonFactory(); final ObjectMapper mapper = new ObjectMapper(factory); return ret.stream().map((String[] args) -> { Schema schema = new Schema.Parser().parse(args[0]); try { JsonNode data = mapper.readTree(new StringReader(args[1])); return Arguments.of(schema, data); } catch (IOException ex) { throw new UncheckedIOException(ex); } }); } private byte[] writeRecord(Schema schema, GenericData.Record record) throws Exception { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); GenericDatumWriter<GenericData.Record> datumWriter = new GenericDatumWriter<>(schema); try (DataFileWriter<GenericData.Record> writer = new DataFileWriter<>(datumWriter)) { writer.create(schema, byteStream); writer.append(record); } return byteStream.toByteArray(); } private GenericData.Record readRecord(Schema schema, byte[] data) throws Exception { ByteArrayInputStream byteStream = new ByteArrayInputStream(data); GenericDatumReader<GenericData.Record> datumReader = new GenericDatumReader<>(schema); try (DataFileStream<GenericData.Record> reader = new DataFileStream<>(byteStream, datumReader)) { return reader.next(); } } }
TestResolvingGrammarGenerator
java
netty__netty
handler/src/main/java/io/netty/handler/ssl/OpenSslCertificateException.java
{ "start": 1005, "end": 3075 }
class ____ extends CertificateException { private static final long serialVersionUID = 5542675253797129798L; private final int errorCode; /** * Construct a new exception with the * <a href="https://www.openssl.org/docs/manmaster/apps/verify.html">error code</a>. */ public OpenSslCertificateException(int errorCode) { this((String) null, errorCode); } /** * Construct a new exception with the msg and * <a href="https://www.openssl.org/docs/manmaster/apps/verify.html">error code</a> . */ public OpenSslCertificateException(String msg, int errorCode) { super(msg); this.errorCode = checkErrorCode(errorCode); } /** * Construct a new exception with the msg, cause and * <a href="https://www.openssl.org/docs/manmaster/apps/verify.html">error code</a> . */ public OpenSslCertificateException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = checkErrorCode(errorCode); } /** * Construct a new exception with the cause and * <a href="https://www.openssl.org/docs/manmaster/apps/verify.html">error code</a> . */ public OpenSslCertificateException(Throwable cause, int errorCode) { this(null, cause, errorCode); } /** * Return the <a href="https://www.openssl.org/docs/man1.0.2/apps/verify.html">error code</a> to use. */ public int errorCode() { return errorCode; } private static int checkErrorCode(int errorCode) { // Call OpenSsl.isAvailable() to ensure we try to load the native lib as CertificateVerifier.isValid(...) // will depend on it. If loading fails we will just skip the validation. if (OpenSsl.isAvailable() && !CertificateVerifier.isValid(errorCode)) { throw new IllegalArgumentException("errorCode '" + errorCode + "' invalid, see https://www.openssl.org/docs/man1.0.2/apps/verify.html."); } return errorCode; } }
OpenSslCertificateException
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/binding/ComponentDependencyProductionBinding.java
{ "start": 2225, "end": 2333 }
class ____ extends ContributionBinding.Builder<ComponentDependencyProductionBinding, Builder> {} }
Builder
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3104/Issue3104Mapper.java
{ "start": 573, "end": 838 }
interface ____ { Issue3104Mapper INSTANCE = Mappers.getMapper( Issue3104Mapper.class ); @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) void update(@MappingTarget Target target, Source source);
Issue3104Mapper
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/authorization/OAuth2AuthorizationCodeGrantTests.java
{ "start": 10411, "end": 62219 }
class ____ { private static final String DEFAULT_AUTHORIZATION_ENDPOINT_URI = "/oauth2/authorize"; private static final String DEFAULT_TOKEN_ENDPOINT_URI = "/oauth2/token"; // See RFC 7636: Appendix B. Example for the S256 code_challenge_method // https://tools.ietf.org/html/rfc7636#appendix-B private static final String S256_CODE_VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; private static final String S256_CODE_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"; private static final String AUTHORITIES_CLAIM = "authorities"; private static final String STATE_URL_UNENCODED = "awrD0fCnEcTUPFgmyy2SU89HZNcnAJ60ZW6l39YI0KyVjmIZ+004pwm9j55li7BoydXYysH4enZMF21Q"; private static final String STATE_URL_ENCODED = "awrD0fCnEcTUPFgmyy2SU89HZNcnAJ60ZW6l39YI0KyVjmIZ%2B004pwm9j55li7BoydXYysH4enZMF21Q"; private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.CODE); private static final OAuth2TokenType STATE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.STATE); private static EmbeddedDatabase db; private static JWKSource<SecurityContext> jwkSource; private static NimbusJwtEncoder jwtEncoder; private static NimbusJwtEncoder dPoPProofJwtEncoder; private static AuthorizationServerSettings authorizationServerSettings; private static HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenHttpResponseConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); private static AuthenticationConverter authorizationRequestConverter; private static Consumer<List<AuthenticationConverter>> authorizationRequestConvertersConsumer; private static AuthenticationProvider authorizationRequestAuthenticationProvider; private static Consumer<List<AuthenticationProvider>> authorizationRequestAuthenticationProvidersConsumer; private static AuthenticationSuccessHandler authorizationResponseHandler; private static AuthenticationFailureHandler authorizationErrorResponseHandler; private static SecurityContextRepository securityContextRepository; private static String consentPage = "/oauth2/consent"; public final SpringTestContext spring = new SpringTestContext(this); @Autowired private MockMvc mvc; @Autowired private JdbcOperations jdbcOperations; @Autowired private RegisteredClientRepository registeredClientRepository; @Autowired private OAuth2AuthorizationService authorizationService; @Autowired private JwtDecoder jwtDecoder; @Autowired(required = false) private OAuth2TokenGenerator<?> tokenGenerator; @BeforeAll public static void init() { JWKSet jwkSet = new JWKSet(TestJwks.DEFAULT_RSA_JWK); jwkSource = (jwkSelector, securityContext) -> jwkSelector.select(jwkSet); jwtEncoder = new NimbusJwtEncoder(jwkSource); JWKSet clientJwkSet = new JWKSet(TestJwks.DEFAULT_EC_JWK); JWKSource<SecurityContext> clientJwkSource = (jwkSelector, securityContext) -> jwkSelector.select(clientJwkSet); dPoPProofJwtEncoder = new NimbusJwtEncoder(clientJwkSource); authorizationServerSettings = AuthorizationServerSettings.builder() .authorizationEndpoint("/test/authorize") .tokenEndpoint("/test/token") .build(); authorizationRequestConverter = mock(AuthenticationConverter.class); authorizationRequestConvertersConsumer = mock(Consumer.class); authorizationRequestAuthenticationProvider = mock(AuthenticationProvider.class); authorizationRequestAuthenticationProvidersConsumer = mock(Consumer.class); authorizationResponseHandler = mock(AuthenticationSuccessHandler.class); authorizationErrorResponseHandler = mock(AuthenticationFailureHandler.class); securityContextRepository = spy(new HttpSessionSecurityContextRepository()); db = new EmbeddedDatabaseBuilder().generateUniqueName(true) .setType(EmbeddedDatabaseType.HSQL) .setScriptEncoding("UTF-8") .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql") .addScript( "org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql") .addScript( "org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql") .build(); } @BeforeEach public void setup() { reset(securityContextRepository); } @AfterEach public void tearDown() { this.jdbcOperations.update("truncate table oauth2_authorization"); this.jdbcOperations.update("truncate table oauth2_authorization_consent"); this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll public static void destroy() { db.shutdown(); } @Test public void requestWhenAuthorizationRequestNotAuthenticatedThenUnauthorized() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); this.registeredClientRepository.save(registeredClient); this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI) .queryParams(getAuthorizationRequestParameters(registeredClient))) .andExpect(status().isUnauthorized()) .andReturn(); } @Test public void requestWhenRegisteredClientMissingThenBadRequest() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); this.mvc .perform( get(DEFAULT_AUTHORIZATION_ENDPOINT_URI).params(getAuthorizationRequestParameters(registeredClient))) .andExpect(status().isBadRequest()) .andReturn(); } @Test public void requestWhenAuthorizationRequestAuthenticatedThenRedirectToClient() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); assertAuthorizationRequestRedirectsToClient(DEFAULT_AUTHORIZATION_ENDPOINT_URI); } @Test public void requestWhenAuthorizationRequestCustomEndpointThenRedirectToClient() throws Exception { this.spring.register(AuthorizationServerConfigurationCustomEndpoints.class).autowire(); assertAuthorizationRequestRedirectsToClient(authorizationServerSettings.getAuthorizationEndpoint()); } private void assertAuthorizationRequestRedirectsToClient(String authorizationEndpointUri) throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add("https://example.com/callback-1?param=encoded%20parameter%20value"); // gh-1011 }).build(); this.registeredClientRepository.save(registeredClient); MultiValueMap<String, String> authorizationRequestParameters = getAuthorizationRequestParameters( registeredClient); MvcResult mvcResult = this.mvc .perform(get(authorizationEndpointUri).queryParams(authorizationRequestParameters).with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); String redirectedUrl = mvcResult.getResponse().getRedirectedUrl(); String redirectUri = authorizationRequestParameters.getFirst(OAuth2ParameterNames.REDIRECT_URI); String code = extractParameterFromRedirectUri(redirectedUrl, "code"); assertThat(redirectedUrl).isEqualTo(redirectUri + "&code=" + code + "&state=" + STATE_URL_ENCODED); String authorizationCode = extractParameterFromRedirectUri(redirectedUrl, "code"); OAuth2Authorization authorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE); assertThat(authorization).isNotNull(); assertThat(authorization.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); } @Test public void requestWhenTokenRequestValidThenReturnAccessTokenResponse() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); this.registeredClientRepository.save(registeredClient); OAuth2Authorization authorization = createAuthorization(registeredClient); this.authorizationService.save(authorization); OAuth2AccessTokenResponse accessTokenResponse = assertTokenRequestReturnsAccessTokenResponse(registeredClient, authorization, DEFAULT_TOKEN_ENDPOINT_URI); // Assert user authorities was propagated as claim in JWT Jwt jwt = this.jwtDecoder.decode(accessTokenResponse.getAccessToken().getTokenValue()); List<String> authoritiesClaim = jwt.getClaim(AUTHORITIES_CLAIM); Authentication principal = authorization.getAttribute(Principal.class.getName()); Set<String> userAuthorities = new HashSet<>(); for (GrantedAuthority authority : principal.getAuthorities()) { userAuthorities.add(authority.getAuthority()); } assertThat(authoritiesClaim).containsExactlyInAnyOrderElementsOf(userAuthorities); } @Test public void requestWhenTokenRequestCustomEndpointThenReturnAccessTokenResponse() throws Exception { this.spring.register(AuthorizationServerConfigurationCustomEndpoints.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); this.registeredClientRepository.save(registeredClient); OAuth2Authorization authorization = createAuthorization(registeredClient); this.authorizationService.save(authorization); assertTokenRequestReturnsAccessTokenResponse(registeredClient, authorization, authorizationServerSettings.getTokenEndpoint()); } private OAuth2AccessTokenResponse assertTokenRequestReturnsAccessTokenResponse(RegisteredClient registeredClient, OAuth2Authorization authorization, String tokenEndpointUri) throws Exception { MvcResult mvcResult = this.mvc .perform(post(tokenEndpointUri).params(getTokenRequestParameters(registeredClient, authorization)) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.token_type").isNotEmpty()) .andExpect(jsonPath("$.expires_in").isNotEmpty()) .andExpect(jsonPath("$.refresh_token").isNotEmpty()) .andExpect(jsonPath("$.scope").isNotEmpty()) .andReturn(); OAuth2Authorization accessTokenAuthorization = this.authorizationService.findById(authorization.getId()); assertThat(accessTokenAuthorization).isNotNull(); assertThat(accessTokenAuthorization.getAccessToken()).isNotNull(); assertThat(accessTokenAuthorization.getRefreshToken()).isNotNull(); OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCodeToken = accessTokenAuthorization .getToken(OAuth2AuthorizationCode.class); assertThat(authorizationCodeToken).isNotNull(); assertThat(authorizationCodeToken.getMetadata().get(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME)) .isEqualTo(true); MockHttpServletResponse servletResponse = mvcResult.getResponse(); MockClientHttpResponse httpResponse = new MockClientHttpResponse(servletResponse.getContentAsByteArray(), HttpStatus.valueOf(servletResponse.getStatus())); return accessTokenHttpResponseConverter.read(OAuth2AccessTokenResponse.class, httpResponse); } @Test public void requestWhenPublicClientWithPkceThenReturnAccessTokenResponse() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); this.registeredClientRepository.save(registeredClient); MvcResult mvcResult = this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI) .queryParams(getAuthorizationRequestParameters(registeredClient)) .with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); String redirectedUrl = mvcResult.getResponse().getRedirectedUrl(); assertThat(redirectedUrl).matches("https://example.com\\?code=.{15,}&state=" + STATE_URL_ENCODED); String authorizationCode = extractParameterFromRedirectUri(redirectedUrl, "code"); OAuth2Authorization authorizationCodeAuthorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE); assertThat(authorizationCodeAuthorization).isNotNull(); assertThat(authorizationCodeAuthorization.getAuthorizationGrantType()) .isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI) .params(getTokenRequestParameters(registeredClient, authorizationCodeAuthorization)) .param(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId())) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andExpect(status().isOk()) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.token_type").isNotEmpty()) .andExpect(jsonPath("$.expires_in").isNotEmpty()) .andExpect(jsonPath("$.refresh_token").doesNotExist()) .andExpect(jsonPath("$.scope").isNotEmpty()); OAuth2Authorization accessTokenAuthorization = this.authorizationService .findById(authorizationCodeAuthorization.getId()); assertThat(accessTokenAuthorization).isNotNull(); assertThat(accessTokenAuthorization.getAccessToken()).isNotNull(); OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCodeToken = accessTokenAuthorization .getToken(OAuth2AuthorizationCode.class); assertThat(authorizationCodeToken).isNotNull(); assertThat(authorizationCodeToken.getMetadata().get(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME)) .isEqualTo(true); } // gh-1430 @Test public void requestWhenPublicClientWithPkceAndCustomRefreshTokenGeneratorThenReturnRefreshToken() throws Exception { this.spring.register(AuthorizationServerConfigurationWithCustomRefreshTokenGenerator.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient() .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .build(); this.registeredClientRepository.save(registeredClient); MvcResult mvcResult = this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI) .queryParams(getAuthorizationRequestParameters(registeredClient)) .with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); String redirectedUrl = mvcResult.getResponse().getRedirectedUrl(); assertThat(redirectedUrl).matches("https://example.com\\?code=.{15,}&state=" + STATE_URL_ENCODED); String authorizationCode = extractParameterFromRedirectUri(redirectedUrl, "code"); OAuth2Authorization authorizationCodeAuthorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE); assertThat(authorizationCodeAuthorization).isNotNull(); assertThat(authorizationCodeAuthorization.getAuthorizationGrantType()) .isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI) .params(getTokenRequestParameters(registeredClient, authorizationCodeAuthorization)) .param(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId())) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andExpect(status().isOk()) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.token_type").isNotEmpty()) .andExpect(jsonPath("$.expires_in").isNotEmpty()) .andExpect(jsonPath("$.refresh_token").isNotEmpty()) .andExpect(jsonPath("$.scope").isNotEmpty()); OAuth2Authorization authorization = this.authorizationService.findById(authorizationCodeAuthorization.getId()); assertThat(authorization).isNotNull(); assertThat(authorization.getAccessToken()).isNotNull(); assertThat(authorization.getRefreshToken()).isNotNull(); OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCodeToken = authorization .getToken(OAuth2AuthorizationCode.class); assertThat(authorizationCodeToken).isNotNull(); assertThat(authorizationCodeToken.getMetadata().get(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME)) .isEqualTo(true); } // gh-1680 @Test public void requestWhenPublicClientWithPkceAndEmptyCodeThenBadRequest() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); this.registeredClientRepository.save(registeredClient); MultiValueMap<String, String> tokenRequestParameters = new LinkedMultiValueMap<>(); tokenRequestParameters.set(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.AUTHORIZATION_CODE.getValue()); tokenRequestParameters.set(OAuth2ParameterNames.CODE, ""); tokenRequestParameters.set(OAuth2ParameterNames.REDIRECT_URI, registeredClient.getRedirectUris().iterator().next()); tokenRequestParameters.set(PkceParameterNames.CODE_VERIFIER, S256_CODE_VERIFIER); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI).params(tokenRequestParameters) .param(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId())) .andExpect(status().isBadRequest()); } @Test public void requestWhenConfidentialClientWithPkceAndMissingCodeVerifierThenBadRequest() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); this.registeredClientRepository.save(registeredClient); MultiValueMap<String, String> authorizationRequestParameters = getAuthorizationRequestParameters( registeredClient); MvcResult mvcResult = this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI).queryParams(authorizationRequestParameters) .with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); String redirectedUrl = mvcResult.getResponse().getRedirectedUrl(); String expectedRedirectUri = authorizationRequestParameters.getFirst(OAuth2ParameterNames.REDIRECT_URI); assertThat(redirectedUrl).matches(expectedRedirectUri + "\\?code=.{15,}&state=" + STATE_URL_ENCODED); String authorizationCode = extractParameterFromRedirectUri(redirectedUrl, "code"); OAuth2Authorization authorizationCodeAuthorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE); assertThat(authorizationCodeAuthorization).isNotNull(); assertThat(authorizationCodeAuthorization.getAuthorizationGrantType()) .isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); MultiValueMap<String, String> tokenRequestParameters = getTokenRequestParameters(registeredClient, authorizationCodeAuthorization); tokenRequestParameters.remove(PkceParameterNames.CODE_VERIFIER); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI).params(tokenRequestParameters) .param(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))) .andExpect(status().isBadRequest()); } // gh-1011 @Test public void requestWhenConfidentialClientWithPkceAndMissingCodeChallengeThenErrorResponseEncoded() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); String redirectUri = "https://example.com/callback-1?param=encoded%20parameter%20value"; RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add(redirectUri); }).build(); this.registeredClientRepository.save(registeredClient); MultiValueMap<String, String> authorizationRequestParameters = getAuthorizationRequestParameters( registeredClient); authorizationRequestParameters.remove(PkceParameterNames.CODE_CHALLENGE); MvcResult mvcResult = this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI).queryParams(authorizationRequestParameters) .with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); String redirectedUrl = mvcResult.getResponse().getRedirectedUrl(); String expectedRedirectUri = redirectUri + "&" + "error=invalid_request&" + "error_description=" + UriUtils.encode("OAuth 2.0 Parameter: code_challenge", StandardCharsets.UTF_8) + "&" + "error_uri=" + UriUtils.encode("https://datatracker.ietf.org/doc/html/rfc7636#section-4.4.1", StandardCharsets.UTF_8) + "&" + "state=" + STATE_URL_ENCODED; assertThat(redirectedUrl).isEqualTo(expectedRedirectUri); } @Test public void requestWhenConfidentialClientWithPkceAndMissingCodeChallengeButCodeVerifierProvidedThenBadRequest() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .clientSettings(ClientSettings.builder().requireProofKey(false).build()) .build(); this.registeredClientRepository.save(registeredClient); MultiValueMap<String, String> authorizationRequestParameters = getAuthorizationRequestParameters( registeredClient); authorizationRequestParameters.remove(PkceParameterNames.CODE_CHALLENGE); MvcResult mvcResult = this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI).queryParams(authorizationRequestParameters) .with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); String redirectedUrl = mvcResult.getResponse().getRedirectedUrl(); String expectedRedirectUri = authorizationRequestParameters.getFirst(OAuth2ParameterNames.REDIRECT_URI); assertThat(redirectedUrl).matches(expectedRedirectUri + "\\?code=.{15,}&state=" + STATE_URL_ENCODED); String authorizationCode = extractParameterFromRedirectUri(redirectedUrl, "code"); OAuth2Authorization authorizationCodeAuthorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE); assertThat(authorizationCodeAuthorization).isNotNull(); assertThat(authorizationCodeAuthorization.getAuthorizationGrantType()) .isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI) .params(getTokenRequestParameters(registeredClient, authorizationCodeAuthorization)) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))) .andExpect(status().isBadRequest()); } @Test public void requestWhenCustomTokenGeneratorThenUsed() throws Exception { this.spring.register(AuthorizationServerConfigurationWithTokenGenerator.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); this.registeredClientRepository.save(registeredClient); OAuth2Authorization authorization = createAuthorization(registeredClient); this.authorizationService.save(authorization); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI).params(getTokenRequestParameters(registeredClient, authorization)) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))) .andExpect(status().isOk()); verify(this.tokenGenerator, times(2)).generate(any()); } @Test public void requestWhenRequiresConsentThenDisplaysConsentPage() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add("message.read"); scopes.add("message.write"); }).clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()).build(); this.registeredClientRepository.save(registeredClient); String consentPage = this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI) .queryParams(getAuthorizationRequestParameters(registeredClient)) .with(user("user"))) .andExpect(status().is2xxSuccessful()) .andReturn() .getResponse() .getContentAsString(); assertThat(consentPage).contains("Consent required"); assertThat(consentPage).contains(scopeCheckbox("message.read")); assertThat(consentPage).contains(scopeCheckbox("message.write")); } @Test public void requestWhenConsentRequestThenReturnAccessTokenResponse() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add("message.read"); scopes.add("message.write"); }).clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()).build(); this.registeredClientRepository.save(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .principalName("user") .build(); Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, S256_CODE_CHALLENGE); additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"); OAuth2AuthorizationRequest authorizationRequest = authorization .getAttribute(OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest updatedAuthorizationRequest = OAuth2AuthorizationRequest.from(authorizationRequest) .state(STATE_URL_UNENCODED) .additionalParameters(additionalParameters) .build(); authorization = OAuth2Authorization.from(authorization) .attribute(OAuth2AuthorizationRequest.class.getName(), updatedAuthorizationRequest) .build(); this.authorizationService.save(authorization); MvcResult mvcResult = this.mvc .perform(post(DEFAULT_AUTHORIZATION_ENDPOINT_URI) .param(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()) .param(OAuth2ParameterNames.SCOPE, "message.read") .param(OAuth2ParameterNames.SCOPE, "message.write") .param(OAuth2ParameterNames.STATE, authorization.<String>getAttribute(OAuth2ParameterNames.STATE)) .with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); String redirectedUrl = mvcResult.getResponse().getRedirectedUrl(); assertThat(redirectedUrl) .matches(authorizationRequest.getRedirectUri() + "\\?code=.{15,}&state=" + STATE_URL_ENCODED); String authorizationCode = extractParameterFromRedirectUri(redirectedUrl, "code"); OAuth2Authorization authorizationCodeAuthorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI) .params(getTokenRequestParameters(registeredClient, authorizationCodeAuthorization)) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.token_type").isNotEmpty()) .andExpect(jsonPath("$.expires_in").isNotEmpty()) .andExpect(jsonPath("$.refresh_token").isNotEmpty()) .andExpect(jsonPath("$.scope").isNotEmpty()) .andReturn(); } @Test public void requestWhenCustomConsentPageConfiguredThenRedirect() throws Exception { this.spring.register(AuthorizationServerConfigurationCustomConsentPage.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add("message.read"); scopes.add("message.write"); }).clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()).build(); this.registeredClientRepository.save(registeredClient); MvcResult mvcResult = this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI) .queryParams(getAuthorizationRequestParameters(registeredClient)) .with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); String redirectedUrl = mvcResult.getResponse().getRedirectedUrl(); assertThat(redirectedUrl).matches("http://localhost/oauth2/consent\\?scope=.+&client_id=.+&state=.+"); String locationHeader = URLDecoder.decode(redirectedUrl, StandardCharsets.UTF_8.name()); UriComponents uriComponents = UriComponentsBuilder.fromUriString(locationHeader).build(); MultiValueMap<String, String> redirectQueryParams = uriComponents.getQueryParams(); assertThat(uriComponents.getPath()).isEqualTo(consentPage); assertThat(redirectQueryParams.getFirst(OAuth2ParameterNames.SCOPE)).isEqualTo("message.read message.write"); assertThat(redirectQueryParams.getFirst(OAuth2ParameterNames.CLIENT_ID)) .isEqualTo(registeredClient.getClientId()); String state = extractParameterFromRedirectUri(redirectedUrl, "state"); OAuth2Authorization authorization = this.authorizationService.findByToken(state, STATE_TOKEN_TYPE); assertThat(authorization).isNotNull(); } @Test public void requestWhenCustomConsentCustomizerConfiguredThenUsed() throws Exception { this.spring.register(AuthorizationServerConfigurationCustomConsentRequest.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .clientSettings(ClientSettings.builder() .requireAuthorizationConsent(true) .setting("custom.allowed-authorities", "authority-1 authority-2") .build()) .build(); this.registeredClientRepository.save(registeredClient); OAuth2Authorization authorization = createAuthorization(registeredClient); OAuth2AuthorizationRequest authorizationRequest = authorization .getAttribute(OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest updatedAuthorizationRequest = OAuth2AuthorizationRequest.from(authorizationRequest) .state(STATE_URL_UNENCODED) .build(); authorization = OAuth2Authorization.from(authorization) .attribute(OAuth2AuthorizationRequest.class.getName(), updatedAuthorizationRequest) .build(); this.authorizationService.save(authorization); MvcResult mvcResult = this.mvc .perform(post(DEFAULT_AUTHORIZATION_ENDPOINT_URI) .param(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()) .param("authority", "authority-1 authority-2") .param(OAuth2ParameterNames.STATE, authorization.<String>getAttribute(OAuth2ParameterNames.STATE)) .with(user("principal"))) .andExpect(status().is3xxRedirection()) .andReturn(); String redirectedUrl = mvcResult.getResponse().getRedirectedUrl(); assertThat(redirectedUrl) .matches(authorizationRequest.getRedirectUri() + "\\?code=.{15,}&state=" + STATE_URL_ENCODED); String authorizationCode = extractParameterFromRedirectUri(redirectedUrl, "code"); OAuth2Authorization authorizationCodeAuthorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE); mvcResult = this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI) .params(getTokenRequestParameters(registeredClient, authorizationCodeAuthorization)) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.access_token").value(new AssertionMatcher<String>() { @Override public void assertion(String accessToken) throws AssertionError { Jwt jwt = OAuth2AuthorizationCodeGrantTests.this.jwtDecoder.decode(accessToken); assertThat(jwt.getClaimAsStringList(AUTHORITIES_CLAIM)).containsExactlyInAnyOrder("authority-1", "authority-2"); } })) .andExpect(jsonPath("$.token_type").isNotEmpty()) .andExpect(jsonPath("$.expires_in").isNotEmpty()) .andExpect(jsonPath("$.refresh_token").isNotEmpty()) .andExpect(jsonPath("$.scope").doesNotExist()) .andReturn(); } @Test public void requestWhenAuthorizationEndpointCustomizedThenUsed() throws Exception { this.spring.register(AuthorizationServerConfigurationCustomAuthorizationEndpoint.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); TestingAuthenticationToken principal = new TestingAuthenticationToken("principalName", "password"); OAuth2AuthorizationCode authorizationCode = new OAuth2AuthorizationCode("code", Instant.now(), Instant.now().plus(5, ChronoUnit.MINUTES)); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( "https://provider.com/oauth2/authorize", registeredClient.getClientId(), principal, authorizationCode, registeredClient.getRedirectUris().iterator().next(), STATE_URL_UNENCODED, registeredClient.getScopes()); given(authorizationRequestConverter.convert(any())).willReturn(authorizationCodeRequestAuthenticationResult); given(authorizationRequestAuthenticationProvider .supports(eq(OAuth2AuthorizationCodeRequestAuthenticationToken.class))).willReturn(true); given(authorizationRequestAuthenticationProvider.authenticate(any())) .willReturn(authorizationCodeRequestAuthenticationResult); this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI).params(getAuthorizationRequestParameters(registeredClient)) .with(user("user"))) .andExpect(status().isOk()); verify(authorizationRequestConverter).convert(any()); @SuppressWarnings("unchecked") ArgumentCaptor<List<AuthenticationConverter>> authenticationConvertersCaptor = ArgumentCaptor .forClass(List.class); verify(authorizationRequestConvertersConsumer).accept(authenticationConvertersCaptor.capture()); List<AuthenticationConverter> authenticationConverters = authenticationConvertersCaptor.getValue(); assertThat(authenticationConverters).allMatch((converter) -> converter == authorizationRequestConverter || converter instanceof OAuth2AuthorizationCodeRequestAuthenticationConverter || converter instanceof OAuth2AuthorizationConsentAuthenticationConverter); verify(authorizationRequestAuthenticationProvider) .authenticate(eq(authorizationCodeRequestAuthenticationResult)); @SuppressWarnings("unchecked") ArgumentCaptor<List<AuthenticationProvider>> authenticationProvidersCaptor = ArgumentCaptor .forClass(List.class); verify(authorizationRequestAuthenticationProvidersConsumer).accept(authenticationProvidersCaptor.capture()); List<AuthenticationProvider> authenticationProviders = authenticationProvidersCaptor.getValue(); assertThat(authenticationProviders) .allMatch((provider) -> provider == authorizationRequestAuthenticationProvider || provider instanceof OAuth2AuthorizationCodeRequestAuthenticationProvider || provider instanceof OAuth2AuthorizationConsentAuthenticationProvider); verify(authorizationResponseHandler).onAuthenticationSuccess(any(), any(), eq(authorizationCodeRequestAuthenticationResult)); } // gh-482 @Test public void requestWhenClientObtainsAccessTokenThenClientAuthenticationNotPersisted() throws Exception { this.spring.register(AuthorizationServerConfigurationWithSecurityContextRepository.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); this.registeredClientRepository.save(registeredClient); MvcResult mvcResult = this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI) .queryParams(getAuthorizationRequestParameters(registeredClient)) .with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); ArgumentCaptor<org.springframework.security.core.context.SecurityContext> securityContextCaptor = ArgumentCaptor .forClass(org.springframework.security.core.context.SecurityContext.class); verify(securityContextRepository, times(1)).saveContext(securityContextCaptor.capture(), any(), any()); assertThat(securityContextCaptor.getValue().getAuthentication()) .isInstanceOf(UsernamePasswordAuthenticationToken.class); reset(securityContextRepository); String authorizationCode = extractParameterFromRedirectUri(mvcResult.getResponse().getRedirectedUrl(), "code"); OAuth2Authorization authorizationCodeAuthorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE); mvcResult = this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI) .params(getTokenRequestParameters(registeredClient, authorizationCodeAuthorization)) .param(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId())) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andExpect(status().isOk()) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.token_type").isNotEmpty()) .andExpect(jsonPath("$.expires_in").isNotEmpty()) .andExpect(jsonPath("$.refresh_token").doesNotExist()) .andExpect(jsonPath("$.scope").isNotEmpty()) .andReturn(); org.springframework.security.core.context.SecurityContext securityContext = securityContextRepository .loadDeferredContext(mvcResult.getRequest()) .get(); assertThat(securityContext.getAuthentication()).isNull(); } @Test public void requestWhenAuthorizationAndTokenRequestIncludesIssuerPathThenIssuerResolvedWithPath() throws Exception { this.spring.register(AuthorizationServerConfigurationWithMultipleIssuersAllowed.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); this.registeredClientRepository.save(registeredClient); String issuer = "https://example.com:8443/issuer1"; MvcResult mvcResult = this.mvc .perform(get(issuer.concat(DEFAULT_AUTHORIZATION_ENDPOINT_URI)) .queryParams(getAuthorizationRequestParameters(registeredClient)) .with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); String authorizationCode = extractParameterFromRedirectUri(mvcResult.getResponse().getRedirectedUrl(), "code"); OAuth2Authorization authorizationCodeAuthorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE); this.mvc .perform(post(issuer.concat(DEFAULT_TOKEN_ENDPOINT_URI)) .params(getTokenRequestParameters(registeredClient, authorizationCodeAuthorization)) .param(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId())) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andExpect(status().isOk()) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.token_type").isNotEmpty()) .andExpect(jsonPath("$.expires_in").isNotEmpty()) .andExpect(jsonPath("$.refresh_token").doesNotExist()) .andExpect(jsonPath("$.scope").isNotEmpty()) .andReturn(); ArgumentCaptor<OAuth2TokenContext> tokenContextCaptor = ArgumentCaptor.forClass(OAuth2TokenContext.class); verify(this.tokenGenerator).generate(tokenContextCaptor.capture()); OAuth2TokenContext tokenContext = tokenContextCaptor.getValue(); assertThat(tokenContext.getAuthorizationServerContext().getIssuer()).isEqualTo(issuer); } @Test public void requestWhenTokenRequestWithDPoPProofThenReturnDPoPBoundAccessToken() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); this.registeredClientRepository.save(registeredClient); OAuth2Authorization authorization = createAuthorization(registeredClient); this.authorizationService.save(authorization); String tokenEndpointUri = "http://localhost" + DEFAULT_TOKEN_ENDPOINT_URI; String dPoPProof = generateDPoPProof(tokenEndpointUri); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI).params(getTokenRequestParameters(registeredClient, authorization)) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient)) .header(OAuth2AccessToken.TokenType.DPOP.getValue(), dPoPProof)) .andExpect(status().isOk()) .andExpect(jsonPath("$.token_type").value(OAuth2AccessToken.TokenType.DPOP.getValue())); authorization = this.authorizationService.findById(authorization.getId()); assertThat(authorization.getAccessToken().getClaims()).containsKey("cnf"); @SuppressWarnings("unchecked") Map<String, Object> cnfClaims = (Map<String, Object>) authorization.getAccessToken().getClaims().get("cnf"); assertThat(cnfClaims).containsKey("jkt"); String jwkThumbprintClaim = (String) cnfClaims.get("jkt"); assertThat(jwkThumbprintClaim).isEqualTo(TestJwks.DEFAULT_EC_JWK.toPublicJWK().computeThumbprint().toString()); } @Test public void requestWhenPushedAuthorizationRequestThenReturnAccessTokenResponse() throws Exception { this.spring.register(AuthorizationServerConfigurationWithPushedAuthorizationRequests.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); this.registeredClientRepository.save(registeredClient); MvcResult mvcResult = this.mvc .perform(post("/oauth2/par").params(getAuthorizationRequestParameters(registeredClient)) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andExpect(status().isCreated()) .andExpect(jsonPath("$.request_uri").isNotEmpty()) .andExpect(jsonPath("$.expires_in").isNotEmpty()) .andReturn(); String requestUri = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.request_uri"); mvcResult = this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI) .queryParam(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()) .queryParam(OAuth2ParameterNames.REQUEST_URI, requestUri) .with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); String authorizationCode = extractParameterFromRedirectUri(mvcResult.getResponse().getRedirectedUrl(), "code"); OAuth2Authorization authorizationCodeAuthorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI) .params(getTokenRequestParameters(registeredClient, authorizationCodeAuthorization)) .param(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andExpect(status().isOk()) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.token_type").isNotEmpty()) .andExpect(jsonPath("$.expires_in").isNotEmpty()) .andExpect(jsonPath("$.refresh_token").isNotEmpty()) .andExpect(jsonPath("$.scope").isNotEmpty()) .andReturn(); OAuth2Authorization accessTokenAuthorization = this.authorizationService .findById(authorizationCodeAuthorization.getId()); assertThat(accessTokenAuthorization).isNotNull(); assertThat(accessTokenAuthorization.getAccessToken()).isNotNull(); OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCodeToken = accessTokenAuthorization .getToken(OAuth2AuthorizationCode.class); assertThat(authorizationCodeToken).isNotNull(); assertThat(authorizationCodeToken.getMetadata().get(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME)) .isEqualTo(true); } // gh-2182 @Test public void requestWhenPushedAuthorizationRequestAndRequiresConsentThenDisplaysConsentPage() throws Exception { this.spring.register(AuthorizationServerConfigurationWithPushedAuthorizationRequests.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add("message.read"); scopes.add("message.write"); }).clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()).build(); this.registeredClientRepository.save(registeredClient); MvcResult mvcResult = this.mvc .perform(post("/oauth2/par").params(getAuthorizationRequestParameters(registeredClient)) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andExpect(status().isCreated()) .andExpect(jsonPath("$.request_uri").isNotEmpty()) .andExpect(jsonPath("$.expires_in").isNotEmpty()) .andReturn(); String requestUri = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.request_uri"); String consentPage = this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI) .queryParam(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()) .queryParam(OAuth2ParameterNames.REQUEST_URI, requestUri) .with(user("user"))) .andExpect(status().is2xxSuccessful()) .andReturn() .getResponse() .getContentAsString(); assertThat(consentPage).contains("Consent required"); assertThat(consentPage).contains(scopeCheckbox("message.read")); assertThat(consentPage).contains(scopeCheckbox("message.write")); } // gh-2182 @Test public void requestWhenPushedAuthorizationRequestAndCustomConsentPageConfiguredThenRedirect() throws Exception { this.spring.register(AuthorizationServerConfigurationWithPushedAuthorizationRequestsAndCustomConsentPage.class) .autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add("message.read"); scopes.add("message.write"); }).clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()).build(); this.registeredClientRepository.save(registeredClient); MvcResult mvcResult = this.mvc .perform(post("/oauth2/par").params(getAuthorizationRequestParameters(registeredClient)) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andExpect(status().isCreated()) .andExpect(jsonPath("$.request_uri").isNotEmpty()) .andExpect(jsonPath("$.expires_in").isNotEmpty()) .andReturn(); String requestUri = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.request_uri"); mvcResult = this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI) .queryParam(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()) .queryParam(OAuth2ParameterNames.REQUEST_URI, requestUri) .with(user("user"))) .andExpect(status().is3xxRedirection()) .andReturn(); String redirectedUrl = mvcResult.getResponse().getRedirectedUrl(); assertThat(redirectedUrl).matches("http://localhost/oauth2/consent\\?scope=.+&client_id=.+&state=.+"); String locationHeader = URLDecoder.decode(redirectedUrl, StandardCharsets.UTF_8.name()); UriComponents uriComponents = UriComponentsBuilder.fromUriString(locationHeader).build(); MultiValueMap<String, String> redirectQueryParams = uriComponents.getQueryParams(); assertThat(uriComponents.getPath()).isEqualTo(consentPage); assertThat(redirectQueryParams.getFirst(OAuth2ParameterNames.SCOPE)).isEqualTo("message.read message.write"); assertThat(redirectQueryParams.getFirst(OAuth2ParameterNames.CLIENT_ID)) .isEqualTo(registeredClient.getClientId()); String state = extractParameterFromRedirectUri(redirectedUrl, "state"); OAuth2Authorization authorization = this.authorizationService.findByToken(state, STATE_TOKEN_TYPE); assertThat(authorization).isNotNull(); } private static OAuth2Authorization createAuthorization(RegisteredClient registeredClient) { Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, S256_CODE_CHALLENGE); additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"); return TestOAuth2Authorizations.authorization(registeredClient, additionalParameters).build(); } private static String generateDPoPProof(String tokenEndpointUri) { // @formatter:off Map<String, Object> publicJwk = TestJwks.DEFAULT_EC_JWK .toPublicJWK() .toJSONObject(); JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.ES256) .type("dpop+jwt") .jwk(publicJwk) .build(); JwtClaimsSet claims = JwtClaimsSet.builder() .issuedAt(Instant.now()) .claim("htm", "POST") .claim("htu", tokenEndpointUri) .id(UUID.randomUUID().toString()) .build(); // @formatter:on Jwt jwt = dPoPProofJwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims)); return jwt.getTokenValue(); } private static MultiValueMap<String, String> getAuthorizationRequestParameters(RegisteredClient registeredClient) { MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.set(OAuth2ParameterNames.RESPONSE_TYPE, OAuth2AuthorizationResponseType.CODE.getValue()); parameters.set(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()); parameters.set(OAuth2ParameterNames.REDIRECT_URI, registeredClient.getRedirectUris().iterator().next()); parameters.set(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " ")); parameters.set(OAuth2ParameterNames.STATE, STATE_URL_UNENCODED); parameters.set(PkceParameterNames.CODE_CHALLENGE, S256_CODE_CHALLENGE); parameters.set(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"); return parameters; } private static MultiValueMap<String, String> getTokenRequestParameters(RegisteredClient registeredClient, OAuth2Authorization authorization) { MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.set(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.AUTHORIZATION_CODE.getValue()); parameters.set(OAuth2ParameterNames.CODE, authorization.getToken(OAuth2AuthorizationCode.class).getToken().getTokenValue()); parameters.set(OAuth2ParameterNames.REDIRECT_URI, registeredClient.getRedirectUris().iterator().next()); parameters.set(PkceParameterNames.CODE_VERIFIER, S256_CODE_VERIFIER); return parameters; } private static String getAuthorizationHeader(RegisteredClient registeredClient) throws Exception { String clientId = registeredClient.getClientId(); String clientSecret = registeredClient.getClientSecret(); clientId = URLEncoder.encode(clientId, StandardCharsets.UTF_8); clientSecret = URLEncoder.encode(clientSecret, StandardCharsets.UTF_8); String credentialsString = clientId + ":" + clientSecret; byte[] encodedBytes = Base64.getEncoder().encode(credentialsString.getBytes(StandardCharsets.UTF_8)); return "Basic " + new String(encodedBytes, StandardCharsets.UTF_8); } private static String scopeCheckbox(String scope) { return MessageFormat.format( "<input class=\"form-check-input\" type=\"checkbox\" name=\"scope\" value=\"{0}\" id=\"{0}\">", scope); } private String extractParameterFromRedirectUri(String redirectUri, String param) throws UnsupportedEncodingException { String locationHeader = URLDecoder.decode(redirectUri, StandardCharsets.UTF_8.name()); UriComponents uriComponents = UriComponentsBuilder.fromUriString(locationHeader).build(); return uriComponents.getQueryParams().getFirst(param); } @EnableWebSecurity @Import(OAuth2AuthorizationServerConfiguration.class) static
OAuth2AuthorizationCodeGrantTests
java
apache__spark
common/variant/src/main/java/org/apache/spark/types/variant/VariantUtil.java
{ "start": 2346, "end": 11205 }
class ____ { public static final int BASIC_TYPE_BITS = 2; public static final int BASIC_TYPE_MASK = 0x3; public static final int TYPE_INFO_MASK = 0x3F; // The inclusive maximum value of the type info value. It is the size limit of `SHORT_STR`. public static final int MAX_SHORT_STR_SIZE = 0x3F; // Below is all possible basic type values. // Primitive value. The type info value must be one of the values in the below section. public static final int PRIMITIVE = 0; // Short string value. The type info value is the string size, which must be in `[0, // kMaxShortStrSize]`. // The string content bytes directly follow the header byte. public static final int SHORT_STR = 1; // Object value. The content contains a size, a list of field ids, a list of field offsets, and // the actual field data. The length of the id list is `size`, while the length of the offset // list is `size + 1`, where the last offset represent the total size of the field data. The // fields in an object must be sorted by the field name in alphabetical order. Duplicate field // names in one object are not allowed. // We use 5 bits in the type info to specify the integer type of the object header: it should // be 0_b4_b3b2_b1b0 (MSB is 0), where: // - b4 specifies the type of size. When it is 0/1, `size` is a little-endian 1/4-byte // unsigned integer. // - b3b2/b1b0 specifies the integer type of id and offset. When the 2 bits are 0/1/2, the // list contains 1/2/3-byte little-endian unsigned integers. public static final int OBJECT = 2; // Array value. The content contains a size, a list of field offsets, and the actual element // data. It is similar to an object without the id list. The length of the offset list // is `size + 1`, where the last offset represent the total size of the element data. // Its type info should be: 000_b2_b1b0: // - b2 specifies the type of size. // - b1b0 specifies the integer type of offset. public static final int ARRAY = 3; // Below is all possible type info values for `PRIMITIVE`. // JSON Null value. Empty content. public static final int NULL = 0; // True value. Empty content. public static final int TRUE = 1; // False value. Empty content. public static final int FALSE = 2; // 1-byte little-endian signed integer. public static final int INT1 = 3; // 2-byte little-endian signed integer. public static final int INT2 = 4; // 4-byte little-endian signed integer. public static final int INT4 = 5; // 4-byte little-endian signed integer. public static final int INT8 = 6; // 8-byte IEEE double. public static final int DOUBLE = 7; // 4-byte decimal. Content is 1-byte scale + 4-byte little-endian signed integer. public static final int DECIMAL4 = 8; // 8-byte decimal. Content is 1-byte scale + 8-byte little-endian signed integer. public static final int DECIMAL8 = 9; // 16-byte decimal. Content is 1-byte scale + 16-byte little-endian signed integer. public static final int DECIMAL16 = 10; // Date value. Content is 4-byte little-endian signed integer that represents the number of days // from the Unix epoch. public static final int DATE = 11; // Timestamp value. Content is 8-byte little-endian signed integer that represents the number of // microseconds elapsed since the Unix epoch, 1970-01-01 00:00:00 UTC. It is displayed to users in // their local time zones and may be displayed differently depending on the execution environment. public static final int TIMESTAMP = 12; // Timestamp_ntz value. It has the same content as `TIMESTAMP` but should always be interpreted // as if the local time zone is UTC. public static final int TIMESTAMP_NTZ = 13; // 4-byte IEEE float. public static final int FLOAT = 14; // Binary value. The content is (4-byte little-endian unsigned integer representing the binary // size) + (size bytes of binary content). public static final int BINARY = 15; // Long string value. The content is (4-byte little-endian unsigned integer representing the // string size) + (size bytes of string content). public static final int LONG_STR = 16; // UUID, 16-byte big-endian. public static final int UUID = 20; public static final byte VERSION = 1; // The lower 4 bits of the first metadata byte contain the version. public static final byte VERSION_MASK = 0x0F; public static final int U8_MAX = 0xFF; public static final int U16_MAX = 0xFFFF; public static final int U24_MAX = 0xFFFFFF; public static final int U24_SIZE = 3; public static final int U32_SIZE = 4; // Both variant value and variant metadata need to be no longer than 128MiB. // Note: to make tests more reliable, we set the max size to 16Mib to avoid OOM in tests. public static final int SIZE_LIMIT = JavaUtils.isTesting() ? U24_MAX + 1 : 128 * 1024 * 1024; public static final int MAX_DECIMAL4_PRECISION = 9; public static final int MAX_DECIMAL8_PRECISION = 18; public static final int MAX_DECIMAL16_PRECISION = 38; // Write the least significant `numBytes` bytes in `value` into `bytes[pos, pos + numBytes)` in // little endian. public static void writeLong(byte[] bytes, int pos, long value, int numBytes) { for (int i = 0; i < numBytes; ++i) { bytes[pos + i] = (byte) ((value >>> (8 * i)) & 0xFF); } } public static byte primitiveHeader(int type) { return (byte) (type << 2 | PRIMITIVE); } public static byte shortStrHeader(int size) { return (byte) (size << 2 | SHORT_STR); } public static byte objectHeader(boolean largeSize, int idSize, int offsetSize) { return (byte) (((largeSize ? 1 : 0) << (BASIC_TYPE_BITS + 4)) | ((idSize - 1) << (BASIC_TYPE_BITS + 2)) | ((offsetSize - 1) << BASIC_TYPE_BITS) | OBJECT); } public static byte arrayHeader(boolean largeSize, int offsetSize) { return (byte) (((largeSize ? 1 : 0) << (BASIC_TYPE_BITS + 2)) | ((offsetSize - 1) << BASIC_TYPE_BITS) | ARRAY); } // An exception indicating that the variant value or metadata doesn't static SparkRuntimeException malformedVariant() { return new SparkRuntimeException("MALFORMED_VARIANT", Map$.MODULE$.<String, String>empty(), null, new QueryContext[]{}, ""); } static SparkRuntimeException unknownPrimitiveTypeInVariant(int id) { return new SparkRuntimeException("UNKNOWN_PRIMITIVE_TYPE_IN_VARIANT", new scala.collection.immutable.Map.Map1<>("id", Integer.toString(id)), null, new QueryContext[]{}, ""); } // An exception indicating that an external caller tried to call the Variant constructor with // value or metadata exceeding the 16MiB size limit. We will never construct a Variant this large, // so it should only be possible to encounter this exception when reading a Variant produced by // another tool. static SparkRuntimeException variantConstructorSizeLimit() { return new SparkRuntimeException("VARIANT_CONSTRUCTOR_SIZE_LIMIT", Map$.MODULE$.<String, String>empty(), null, new QueryContext[]{}, ""); } // Check the validity of an array index `pos`. Throw `MALFORMED_VARIANT` if it is out of bound, // meaning that the variant is malformed. static void checkIndex(int pos, int length) { if (pos < 0 || pos >= length) throw malformedVariant(); } // Read a little-endian signed long value from `bytes[pos, pos + numBytes)`. static long readLong(byte[] bytes, int pos, int numBytes) { checkIndex(pos, bytes.length); checkIndex(pos + numBytes - 1, bytes.length); long result = 0; // All bytes except the most significant byte should be unsign-extended and shifted (so we need // `& 0xFF`). The most significant byte should be sign-extended and is handled after the loop. for (int i = 0; i < numBytes - 1; ++i) { long unsignedByteValue = bytes[pos + i] & 0xFF; result |= unsignedByteValue << (8 * i); } long signedByteValue = bytes[pos + numBytes - 1]; result |= signedByteValue << (8 * (numBytes - 1)); return result; } // Read a little-endian unsigned int value from `bytes[pos, pos + numBytes)`. The value must fit // into a non-negative int (`[0, Integer.MAX_VALUE]`). public static int readUnsigned(byte[] bytes, int pos, int numBytes) { checkIndex(pos, bytes.length); checkIndex(pos + numBytes - 1, bytes.length); int result = 0; // Similar to the `readLong` loop, but all bytes should be unsign-extended. for (int i = 0; i < numBytes; ++i) { int unsignedByteValue = bytes[pos + i] & 0xFF; result |= unsignedByteValue << (8 * i); } if (result < 0) throw malformedVariant(); return result; } // The value type of variant value. It is determined by the header byte but not a 1:1 mapping // (for example, INT1/2/4/8 all maps to `Type.LONG`). public
VariantUtil
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/net/impl/TrustAllTrustManager.java
{ "start": 707, "end": 1237 }
class ____ implements X509TrustManager { public static TrustAllTrustManager INSTANCE = new TrustAllTrustManager(); private TrustAllTrustManager() { } @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }
TrustAllTrustManager
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/kstream/Suppressed.java
{ "start": 1505, "end": 1607 }
interface ____ extends BufferConfig<StrictBufferConfig> { } /** * Marker
StrictBufferConfig
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/client/ApiVersionInserter.java
{ "start": 911, "end": 1342 }
interface ____ create one of * the built-in inserter type implementations: * <ul> * <li>{@link #useHeader(String)} * <li>{@link #useQueryParam(String)} * <li>{@link #useMediaTypeParam(String)} * <li>{@link #usePathSegment(Integer)} * </ul> * * <p>Use the {@link #builder()} for further options such as if you want to also * configure an {@link ApiVersionFormatter}. * * @author Rossen Stoyanchev * @since 7.0 */ public
to
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/LogicalTypes.java
{ "start": 9495, "end": 10262 }
class ____ extends LogicalType { private static final int UUID_BYTES = 2 * Long.BYTES; private Uuid() { super(UUID); } @Override public void validate(Schema schema) { super.validate(schema); if (schema.getType() != Schema.Type.STRING && schema.getType() != Schema.Type.FIXED) { throw new IllegalArgumentException("Uuid can only be used with an underlying string or fixed type"); } if (schema.getType() == Schema.Type.FIXED && schema.getFixedSize() != UUID_BYTES) { throw new IllegalArgumentException("Uuid with fixed type must have a size of " + UUID_BYTES + " bytes"); } } } /** * Duration represents a duration, consisting on months, days and milliseconds */ public static
Uuid
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/groovy/GroovyBeanDefinitionReader.java
{ "start": 27206, "end": 28682 }
class ____ extends RuntimeBeanReference implements GroovyObject { private final GroovyBeanDefinitionWrapper beanDefinition; private MetaClass metaClass; public GroovyRuntimeBeanReference(String beanName, GroovyBeanDefinitionWrapper beanDefinition, boolean toParent) { super(beanName, toParent); this.beanDefinition = beanDefinition; this.metaClass = InvokerHelper.getMetaClass(this); } @Override public MetaClass getMetaClass() { return this.metaClass; } @Override public @Nullable Object getProperty(String property) { if (property.equals("beanName")) { return getBeanName(); } else if (property.equals("source")) { return getSource(); } else { return new GroovyPropertyValue( property, this.beanDefinition.getBeanDefinition().getPropertyValues().get(property)); } } @Override public Object invokeMethod(String name, Object args) { return this.metaClass.invokeMethod(this, name, args); } @Override public void setMetaClass(MetaClass metaClass) { this.metaClass = metaClass; } @Override public void setProperty(String property, Object newValue) { if (!addDeferredProperty(property, newValue)) { this.beanDefinition.getBeanDefinition().getPropertyValues().add(property, newValue); } } /** * Wraps a bean definition property and ensures that any RuntimeBeanReference * additions to it are deferred for resolution later. */ private
GroovyRuntimeBeanReference
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestCombineOutputCollector.java
{ "start": 1433, "end": 4234 }
class ____ { private CombineOutputCollector<String, Integer> coc; Counters.Counter outCounter = new Counters.Counter() { private long value; @Override public void setValue(long value) { this.value = value; } @Override public void setDisplayName(String displayName) { // TODO Auto-generated method stub } @Override public void increment(long incr) { this.value += incr; } @Override public long getValue() { return value; } @Override public String getName() { // TODO Auto-generated method stub return null; } @Override public String getDisplayName() { // TODO Auto-generated method stub return null; } @Override public String makeEscapedCompactString() { // TODO Auto-generated method stub return null; } @Override public long getCounter() { return value; } @Override public boolean contentEquals(Counter counter) { // TODO Auto-generated method stub return false; } @Override public void write(DataOutput out) throws IOException { } @Override public void readFields(DataInput in) throws IOException { } }; @Test public void testCustomCollect() throws Throwable { //mock creation TaskReporter mockTaskReporter = mock(TaskReporter.class); @SuppressWarnings("unchecked") Writer<String, Integer> mockWriter = mock(Writer.class); Configuration conf = new Configuration(); conf.set(MRJobConfig.COMBINE_RECORDS_BEFORE_PROGRESS, "2"); coc = new CombineOutputCollector<String, Integer>(outCounter, mockTaskReporter, conf); coc.setWriter(mockWriter); verify(mockTaskReporter, never()).progress(); coc.collect("dummy", 1); verify(mockTaskReporter, never()).progress(); coc.collect("dummy", 2); verify(mockTaskReporter, times(1)).progress(); } @Test public void testDefaultCollect() throws Throwable { //mock creation TaskReporter mockTaskReporter = mock(TaskReporter.class); @SuppressWarnings("unchecked") Writer<String, Integer> mockWriter = mock(Writer.class); Configuration conf = new Configuration(); coc = new CombineOutputCollector<String, Integer>(outCounter, mockTaskReporter, conf); coc.setWriter(mockWriter); verify(mockTaskReporter, never()).progress(); for(int i = 0; i < Task.DEFAULT_COMBINE_RECORDS_BEFORE_PROGRESS; i++) { coc.collect("dummy", i); } verify(mockTaskReporter, times(1)).progress(); for(int i = 0; i < Task.DEFAULT_COMBINE_RECORDS_BEFORE_PROGRESS; i++) { coc.collect("dummy", i); } verify(mockTaskReporter, times(2)).progress(); } }
TestCombineOutputCollector
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/server/body/BodyLogFilter.java
{ "start": 591, "end": 1278 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(BodyLogFilter.class); @RequestFilter public void logBody(ServerHttpRequest<?> request) { // <2> try (CloseableByteBody ourCopy = // <4> request.byteBody() .split(ByteBody.SplitBackpressureMode.SLOWEST) // <3> .allowDiscard()) { // <5> Flux.from(ourCopy.toByteArrayPublisher()) // <6> .onErrorComplete(ByteBody.BodyDiscardedException.class) // <7> .subscribe(array -> LOG.info("Received body: {}", Base64.getEncoder().encodeToString(array))); // <8> } } } // end::clazz[]
BodyLogFilter
java
redisson__redisson
redisson/src/main/java/org/redisson/client/codec/BaseCodec.java
{ "start": 981, "end": 2355 }
class ____ implements Codec { public static final List<Class<?>> SKIPPED_CODECS = Arrays.asList( StringCodec.class, ByteArrayCodec.class, LocalCachedMessageCodec.class, BitSetCodec.class, JCacheEventCodec.class, LongCodec.class, IntegerCodec.class, ProtobufCodec.class); public static <T> T copy(ClassLoader classLoader, T codec) throws ReflectiveOperationException { if (codec == null) { return codec; } for (Class<?> clazz : SKIPPED_CODECS) { if (clazz.isAssignableFrom(codec.getClass())) { return codec; } } return (T) codec.getClass().getConstructor(ClassLoader.class, codec.getClass()).newInstance(classLoader, codec); } @Override public Decoder<Object> getMapValueDecoder() { return getValueDecoder(); } @Override public Encoder getMapValueEncoder() { return getValueEncoder(); } @Override public Decoder<Object> getMapKeyDecoder() { return getValueDecoder(); } @Override public Encoder getMapKeyEncoder() { return getValueEncoder(); } @Override public ClassLoader getClassLoader() { return getClass().getClassLoader(); } @Override public String toString() { return getClass().getName(); } }
BaseCodec
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/http/HttpClientStatsTracker.java
{ "start": 7999, "end": 10998 }
class ____ { final int id; final long openedTimeMillis; String agent; String localAddress; String remoteAddress; String lastUri; String forwardedFor; String opaqueId; long lastRequestTimeMillis = -1L; long requestCount; long requestSizeBytes; ClientStatsBuilder(int id, @Nullable String remoteAddress, long openedTimeMillis) { this.id = id; this.remoteAddress = remoteAddress; this.openedTimeMillis = openedTimeMillis; } synchronized void update(HttpRequest httpRequest, HttpChannel httpChannel, long currentTimeMillis) { if (agent == null) { final String elasticProductOrigin = getFirstValueForHeader(httpRequest, "x-elastic-product-origin"); if (elasticProductOrigin != null) { agent = elasticProductOrigin; } else { agent = getFirstValueForHeader(httpRequest, "User-Agent"); } } if (localAddress == null) { localAddress = formatAddress(httpChannel.getLocalAddress()); } if (remoteAddress == null) { remoteAddress = formatAddress(httpChannel.getRemoteAddress()); } if (forwardedFor == null) { forwardedFor = getFirstValueForHeader(httpRequest, "x-forwarded-for"); } if (opaqueId == null) { opaqueId = getFirstValueForHeader(httpRequest, "x-opaque-id"); } lastRequestTimeMillis = currentTimeMillis; lastUri = httpRequest.uri(); requestCount += 1; if (httpRequest.body().isFull()) { requestSizeBytes += httpRequest.body().asFull().bytes().length(); } else { httpRequest.body().asStream().addTracingHandler((chunk, last) -> requestSizeBytes += chunk.length()); } } private static String getFirstValueForHeader(final HttpRequest request, final String header) { for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) { if (entry.getKey().equalsIgnoreCase(header)) { if (entry.getValue().size() > 0) { return entry.getValue().get(0); } } } return null; } synchronized HttpStats.ClientStats build(long closedTimeMillis) { return new HttpStats.ClientStats( id, agent, localAddress, remoteAddress, lastUri, forwardedFor, opaqueId, openedTimeMillis, closedTimeMillis, lastRequestTimeMillis, requestCount, requestSizeBytes ); } } }
ClientStatsBuilder
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/logging/structured/ContextPairs.java
{ "start": 3651, "end": 7306 }
class ____<T> { private final Joiner joiner; private final List<BiConsumer<T, BiConsumer<String, ?>>> addedPairs; Pairs(Joiner joiner, Consumer<Pairs<T>> pairs) { this.joiner = joiner; this.addedPairs = new ArrayList<>(); pairs.accept(this); } /** * Add pairs from map entries. * @param <V> the map value type * @param extractor the extractor used to provide the map */ @SuppressWarnings("NullAway") // Doesn't detect lambda with correct nullability public <V> void addMapEntries(Function<T, Map<String, V>> extractor) { add(extractor.andThen(Map::entrySet), Map.Entry::getKey, Map.Entry::getValue); } /** * Add pairs from an iterable. * @param elementsExtractor the extractor used to provide the iterable * @param pairExtractor the extractor used to provide the name and value * @param <E> the element type */ public <E> void add(Function<T, @Nullable Iterable<E>> elementsExtractor, PairExtractor<E> pairExtractor) { add(elementsExtractor, pairExtractor::getName, pairExtractor::getValue); } /** * Add pairs from an iterable. * @param elementsExtractor the extractor used to provide the iterable * @param <E> the element type * @param <V> the value type * @param nameExtractor the extractor used to provide the name * @param valueExtractor the extractor used to provide the value */ public <E, V> void add(Function<T, @Nullable Iterable<E>> elementsExtractor, Function<E, String> nameExtractor, Function<E, V> valueExtractor) { add((item, pairs) -> { Iterable<E> elements = elementsExtractor.apply(item); if (elements != null) { elements.forEach((element) -> { String name = nameExtractor.apply(element); V value = valueExtractor.apply(element); pairs.accept(name, value); }); } }); } /** * Add pairs using the given callback. * @param <V> the value type * @param pairs callback provided with the item and consumer that can be called to * actually add the pairs */ @SuppressWarnings({ "unchecked", "rawtypes" }) public <V> void add(BiConsumer<T, BiConsumer<String, V>> pairs) { this.addedPairs.add((BiConsumer) pairs); } void flat(T item, BiConsumer<String, Object> pairs) { this.addedPairs.forEach((action) -> action.accept(item, joining(pairs))); } @SuppressWarnings("unchecked") void nested(T item, BiConsumer<String, Object> pairs) { LinkedHashMap<String, Object> result = new LinkedHashMap<>(); this.addedPairs.forEach((addedPair) -> { addedPair.accept(item, joining((name, value) -> { List<String> nameParts = List.of(name.split("\\.")); Map<String, Object> destination = result; for (int i = 0; i < nameParts.size() - 1; i++) { Object existing = destination.computeIfAbsent(nameParts.get(i), (key) -> new LinkedHashMap<>()); if (!(existing instanceof Map)) { String common = String.join(".", nameParts.subList(0, i + 1)); throw new IllegalStateException( "Duplicate nested pairs added under '%s'".formatted(common)); } destination = (Map<String, Object>) existing; } Object previous = destination.put(nameParts.get(nameParts.size() - 1), value); Assert.state(previous == null, () -> "Duplicate nested pairs added under '%s'".formatted(name)); })); }); result.forEach(pairs); } private <V> BiConsumer<String, V> joining(BiConsumer<String, V> pairs) { return (name, value) -> { name = this.joiner.join(ContextPairs.this.prefix, (name != null) ? name : ""); if (StringUtils.hasLength(name)) { pairs.accept(name, value); } }; } } }
Pairs
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-jackson/deployment/src/test/java/io/quarkus/resteasy/jackson/HelloResource.java
{ "start": 254, "end": 372 }
class ____ { @GET public DateDto hello() { return new DateDto(ZonedDateTime.now()); } }
HelloResource
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java
{ "start": 2485, "end": 13926 }
class ____ extends AbstractSaveEventListener<MergeContext> implements MergeEventListener { @Override protected Map<Object,Object> getMergeMap(MergeContext context) { return context.invertMap(); } /** * Handle the given merge event. * * @param event The merge event to be handled. * */ @Override public void onMerge(MergeEvent event) throws HibernateException { final var session = event.getSession(); final var entityCopyObserver = session.getFactory().getEntityCopyObserver().createEntityCopyObserver(); final var mergeContext = new MergeContext( session, entityCopyObserver ); try { onMerge( event, mergeContext ); entityCopyObserver.topLevelMergeComplete( session ); } finally { entityCopyObserver.clear(); mergeContext.clear(); } } /** * Handle the given merge event. * * @param event The merge event to be handled. * */ @Override public void onMerge(MergeEvent event, MergeContext copiedAlready) throws HibernateException { final Object original = event.getOriginal(); // NOTE: `original` is the value being merged if ( original != null ) { final var source = event.getSession(); final var lazyInitializer = extractLazyInitializer( original ); if ( lazyInitializer != null ) { if ( lazyInitializer.isUninitialized() ) { EVENT_LISTENER_LOGGER.ignoringUninitializedProxy(); event.setResult( source.getReference( lazyInitializer.getEntityName(), lazyInitializer.getInternalIdentifier() ) ); } else { doMerge( event, copiedAlready, lazyInitializer.getImplementation() ); } } else if ( isPersistentAttributeInterceptable( original ) ) { if ( asPersistentAttributeInterceptable( original ).$$_hibernate_getInterceptor() instanceof EnhancementAsProxyLazinessInterceptor proxyInterceptor ) { EVENT_LISTENER_LOGGER.ignoringUninitializedEnhancedProxy(); event.setResult( source.byId( proxyInterceptor.getEntityName() ) .getReference( proxyInterceptor.getIdentifier() ) ); } else { doMerge( event, copiedAlready, original ); } } else { doMerge( event, copiedAlready, original ); } } } private void doMerge(MergeEvent event, MergeContext copiedAlready, Object entity) { if ( copiedAlready.containsKey( entity ) && copiedAlready.isOperatedOn( entity ) ) { EVENT_LISTENER_LOGGER.alreadyInMergeProcess(); event.setResult( entity ); } else { if ( copiedAlready.containsKey( entity ) ) { EVENT_LISTENER_LOGGER.alreadyInMergeContext(); copiedAlready.setOperatedOn( entity, true ); } event.setEntity( entity ); merge( event, copiedAlready, entity ); } } private void merge(MergeEvent event, MergeContext copiedAlready, Object entity) { final var source = event.getSession(); // Check the persistence context for an entry relating to this // entity to be merged... final String entityName = event.getEntityName(); final var persistenceContext = source.getPersistenceContextInternal(); var entry = persistenceContext.getEntry( entity ); final EntityState entityState; final Object copiedId; final Object originalId; if ( entry == null ) { final var persister = source.getEntityPersister( entityName, entity ); originalId = persister.getIdentifier( entity, copiedAlready ); if ( originalId != null ) { final EntityKey entityKey; if ( persister.getIdentifierType() instanceof ComponentType compositeId ) { // this is needed in case of a composite id containing an association with a generated identifier // in such a case, generating the EntityKey will cause NPE when evaluating the hashcode of the null id copiedId = copyCompositeTypeId( originalId, compositeId, source, copiedAlready ); entityKey = source.generateEntityKey( copiedId, persister ); } else { copiedId = null; entityKey = source.generateEntityKey( originalId, persister ); } final Object managedEntity = persistenceContext.getEntity( entityKey ); entry = persistenceContext.getEntry( managedEntity ); if ( entry != null ) { // we have a special case of a detached entity from the // perspective of the merge operation. Specifically, we have // an incoming entity instance which has a corresponding // entry in the current persistence context, but registered // under a different entity instance entityState = EntityState.DETACHED; } else { entityState = getEntityState( entity, entityName, entry, source, false ); } } else { copiedId = null; entityState = getEntityState( entity, entityName, entry, source, false ); } } else { copiedId = null; originalId = null; entityState = getEntityState( entity, entityName, entry, source, false ); } switch ( entityState ) { case DETACHED: entityIsDetached( event, copiedId, originalId, copiedAlready ); break; case TRANSIENT: entityIsTransient( event, copiedId != null ? copiedId : originalId, copiedAlready ); break; case PERSISTENT: entityIsPersistent( event, copiedAlready ); break; default: //DELETED if ( persistenceContext.getEntry( entity ) == null ) { final var persister = source.getEntityPersister( entityName, entity ); assert persistenceContext.containsDeletedUnloadedEntityKey( source.generateEntityKey( persister.getIdentifier( entity, event.getSession() ), persister ) ); source.getActionQueue().unScheduleUnloadedDeletion( entity ); entityIsDetached( event, copiedId, originalId, copiedAlready ); break; } throw new ObjectDeletedException( "deleted instance passed to merge", originalId, getLoggableName( entityName, entity ) ); } } private static Object copyCompositeTypeId( Object id, CompositeType compositeType, EventSource session, MergeContext mergeContext) { final var factory = session.getSessionFactory(); final Object idCopy = compositeType.deepCopy( id, factory ); final Type[] subtypes = compositeType.getSubtypes(); final Object[] propertyValues = compositeType.getPropertyValues( id ); final Object[] copiedValues = compositeType.getPropertyValues( idCopy ); for ( int i = 0; i < subtypes.length; i++ ) { copiedValues[i] = copy( session, mergeContext, subtypes[i], propertyValues[i], factory ); } return compositeType.replacePropertyValues( idCopy, copiedValues, session ); } private static Object copy( EventSource session, MergeContext mergeContext, Type subtype, Object propertyValue, SessionFactoryImplementor factory) { if ( subtype instanceof EntityType ) { // the value of the copy in the MergeContext has the id assigned final Object object = mergeContext.get( propertyValue ); return object == null ? subtype.deepCopy( propertyValue, factory ) : object; } else if ( subtype instanceof AnyType anyType ) { return copyCompositeTypeId( propertyValue, anyType, session, mergeContext ); } else if ( subtype instanceof ComponentType componentType ) { return copyCompositeTypeId( propertyValue, componentType, session, mergeContext ); } else { return subtype.deepCopy( propertyValue, factory ); } } protected void entityIsPersistent(MergeEvent event, MergeContext copyCache) { //TODO: check that entry.getIdentifier().equals(requestedId) final Object entity = event.getEntity(); final var source = event.getSession(); final String entityName = event.getEntityName(); final var persister = source.getEntityPersister( entityName, entity ); if ( EVENT_LISTENER_LOGGER.isTraceEnabled() ) { EVENT_LISTENER_LOGGER.ignoringPersistentInstance( infoString( entityName, persister.getIdentifier( entity, copyCache ) ) ); } copyCache.put( entity, entity, true ); //before cascade! cascadeOnMerge( source, persister, entity, copyCache ); TypeHelper.replace( persister, entity, source, entity, copyCache ); event.setResult( entity ); } protected void entityIsTransient(MergeEvent event, Object id, MergeContext copyCache) { final Object entity = event.getEntity(); final var session = event.getSession(); final var interceptor = session.getInterceptor(); final String entityName = event.getEntityName(); final var persister = session.getEntityPersister( entityName, entity ); if ( EVENT_LISTENER_LOGGER.isTraceEnabled() ) { EVENT_LISTENER_LOGGER.mergingTransientInstance( infoString( entityName, id ) ); } final String[] propertyNames = persister.getPropertyNames(); final Type[] propertyTypes = persister.getPropertyTypes(); final Object copy = copyEntity( copyCache, entity, session, persister, id ); // cascade first, so that all unsaved objects get their // copy created before we actually copy //cascadeOnMerge(event, persister, entity, copyCache, Cascades.CASCADE_BEFORE_MERGE); super.cascadeBeforeSave( session, persister, entity, copyCache ); final Object[] sourceValues = persister.getValues( entity ); interceptor.preMerge( entity, sourceValues, propertyNames, propertyTypes ); final Object[] copiedValues = TypeHelper.replace( sourceValues, persister.getValues( copy ), propertyTypes, session, copy, copyCache, ForeignKeyDirection.FROM_PARENT ); persister.setValues( copy, copiedValues ); saveTransientEntity( copy, entityName, event.getRequestedId(), session, copyCache ); // cascade first, so that all unsaved objects get their // copy created before we actually copy super.cascadeAfterSave( session, persister, entity, copyCache ); // this is the second pass of a merge operation, so here we limit the // replacement to association types (value types were already replaced // during the first pass) // final Object[] newSourceValues = persister.getValues( entity ); final Object[] targetValues = TypeHelper.replaceAssociations( sourceValues, // newSourceValues, persister.getValues( copy ), propertyTypes, session, copy, copyCache, ForeignKeyDirection.TO_PARENT ); persister.setValues( copy, targetValues ); interceptor.postMerge( entity, copy, id, targetValues, null, propertyNames, propertyTypes ); // saveTransientEntity has been called using a copy that contains empty collections // (copyValues uses ForeignKeyDirection.FROM_PARENT) then the PC may contain a wrong // collection snapshot, the CollectionVisitor realigns the collection snapshot values // with the final copy new CollectionVisitor( copy, id, session ) .processEntityPropertyValues( persister.getPropertyValuesToInsert( copy, getMergeMap( copyCache ), session ), persister.getPropertyTypes() ); event.setResult( copy ); if ( isPersistentAttributeInterceptable( copy ) && asPersistentAttributeInterceptable( copy ).$$_hibernate_getInterceptor() == null ) { persister.getBytecodeEnhancementMetadata().injectInterceptor( copy, id, session ); } } private static Object copyEntity( MergeContext copyCache, Object entity, EventSource session, EntityPersister persister, Object id) { final Object existingCopy = copyCache.get( entity ); if ( existingCopy != null ) { persister.setIdentifier( existingCopy, id, session ); return existingCopy; } else { final Object copy = session.instantiate( persister, id ); //before cascade! copyCache.put( entity, copy, true ); return copy; } } private static
DefaultMergeEventListener
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/protobuf/Msg.java
{ "start": 9845, "end": 22830 }
class ____ extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:Msg) org.springframework.protobuf.MsgOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.springframework.protobuf.OuterSample.internal_static_Msg_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.springframework.protobuf.OuterSample.internal_static_Msg_fieldAccessorTable .ensureFieldAccessorsInitialized( org.springframework.protobuf.Msg.class, org.springframework.protobuf.Msg.Builder.class); } // Construct using org.springframework.protobuf.Msg.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { getBlahFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; foo_ = ""; blah_ = null; if (blahBuilder_ != null) { blahBuilder_.dispose(); blahBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.springframework.protobuf.OuterSample.internal_static_Msg_descriptor; } @java.lang.Override public org.springframework.protobuf.Msg getDefaultInstanceForType() { return org.springframework.protobuf.Msg.getDefaultInstance(); } @java.lang.Override public org.springframework.protobuf.Msg build() { org.springframework.protobuf.Msg result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public org.springframework.protobuf.Msg buildPartial() { org.springframework.protobuf.Msg result = new org.springframework.protobuf.Msg(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(org.springframework.protobuf.Msg result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.foo_ = foo_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.blah_ = blahBuilder_ == null ? blah_ : blahBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.springframework.protobuf.Msg) { return mergeFrom((org.springframework.protobuf.Msg)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.springframework.protobuf.Msg other) { if (other == org.springframework.protobuf.Msg.getDefaultInstance()) return this; if (other.hasFoo()) { foo_ = other.foo_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasBlah()) { mergeBlah(other.getBlah()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { foo_ = input.readBytes(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage( getBlahFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object foo_ = ""; /** * <code>optional string foo = 1;</code> * @return Whether the foo field is set. */ public boolean hasFoo() { return ((bitField0_ & 0x00000001) != 0); } /** * <code>optional string foo = 1;</code> * @return The foo. */ public java.lang.String getFoo() { java.lang.Object ref = foo_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { foo_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>optional string foo = 1;</code> * @return The bytes for foo. */ public com.google.protobuf.ByteString getFooBytes() { java.lang.Object ref = foo_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); foo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string foo = 1;</code> * @param value The foo to set. * @return This builder for chaining. */ public Builder setFoo( java.lang.String value) { if (value == null) { throw new NullPointerException(); } foo_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <code>optional string foo = 1;</code> * @return This builder for chaining. */ public Builder clearFoo() { foo_ = getDefaultInstance().getFoo(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <code>optional string foo = 1;</code> * @param value The bytes for foo to set. * @return This builder for chaining. */ public Builder setFooBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } foo_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private org.springframework.protobuf.SecondMsg blah_; private com.google.protobuf.SingleFieldBuilder< org.springframework.protobuf.SecondMsg, org.springframework.protobuf.SecondMsg.Builder, org.springframework.protobuf.SecondMsgOrBuilder> blahBuilder_; /** * <code>optional .SecondMsg blah = 2;</code> * @return Whether the blah field is set. */ public boolean hasBlah() { return ((bitField0_ & 0x00000002) != 0); } /** * <code>optional .SecondMsg blah = 2;</code> * @return The blah. */ public org.springframework.protobuf.SecondMsg getBlah() { if (blahBuilder_ == null) { return blah_ == null ? org.springframework.protobuf.SecondMsg.getDefaultInstance() : blah_; } else { return blahBuilder_.getMessage(); } } /** * <code>optional .SecondMsg blah = 2;</code> */ public Builder setBlah(org.springframework.protobuf.SecondMsg value) { if (blahBuilder_ == null) { if (value == null) { throw new NullPointerException(); } blah_ = value; } else { blahBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * <code>optional .SecondMsg blah = 2;</code> */ public Builder setBlah( org.springframework.protobuf.SecondMsg.Builder builderForValue) { if (blahBuilder_ == null) { blah_ = builderForValue.build(); } else { blahBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * <code>optional .SecondMsg blah = 2;</code> */ public Builder mergeBlah(org.springframework.protobuf.SecondMsg value) { if (blahBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && blah_ != null && blah_ != org.springframework.protobuf.SecondMsg.getDefaultInstance()) { getBlahBuilder().mergeFrom(value); } else { blah_ = value; } } else { blahBuilder_.mergeFrom(value); } if (blah_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * <code>optional .SecondMsg blah = 2;</code> */ public Builder clearBlah() { bitField0_ = (bitField0_ & ~0x00000002); blah_ = null; if (blahBuilder_ != null) { blahBuilder_.dispose(); blahBuilder_ = null; } onChanged(); return this; } /** * <code>optional .SecondMsg blah = 2;</code> */ public org.springframework.protobuf.SecondMsg.Builder getBlahBuilder() { bitField0_ |= 0x00000002; onChanged(); return getBlahFieldBuilder().getBuilder(); } /** * <code>optional .SecondMsg blah = 2;</code> */ public org.springframework.protobuf.SecondMsgOrBuilder getBlahOrBuilder() { if (blahBuilder_ != null) { return blahBuilder_.getMessageOrBuilder(); } else { return blah_ == null ? org.springframework.protobuf.SecondMsg.getDefaultInstance() : blah_; } } /** * <code>optional .SecondMsg blah = 2;</code> */ private com.google.protobuf.SingleFieldBuilder< org.springframework.protobuf.SecondMsg, org.springframework.protobuf.SecondMsg.Builder, org.springframework.protobuf.SecondMsgOrBuilder> getBlahFieldBuilder() { if (blahBuilder_ == null) { blahBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.springframework.protobuf.SecondMsg, org.springframework.protobuf.SecondMsg.Builder, org.springframework.protobuf.SecondMsgOrBuilder>( getBlah(), getParentForChildren(), isClean()); blah_ = null; } return blahBuilder_; } // @@protoc_insertion_point(builder_scope:Msg) } // @@protoc_insertion_point(class_scope:Msg) private static final org.springframework.protobuf.Msg DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new org.springframework.protobuf.Msg(); } public static org.springframework.protobuf.Msg getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Msg> PARSER = new com.google.protobuf.AbstractParser<Msg>() { @java.lang.Override public Msg parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<Msg> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Msg> getParserForType() { return PARSER; } @java.lang.Override public org.springframework.protobuf.Msg getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
Builder
java
elastic__elasticsearch
x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/transforms/TransformRetryableStartUpListener.java
{ "start": 564, "end": 1624 }
class ____<Response> implements TransformScheduler.Listener { private final String transformId; private final Consumer<ActionListener<Response>> action; private final ActionListener<Response> actionListener; private final ActionListener<Boolean> retryScheduledListener; private final Supplier<Boolean> shouldRetry; private final TransformContext context; private final AtomicBoolean isFirstRun; private final AtomicBoolean shouldRunAction; /** * @param transformId the transform associated with this listener. All events to this listener must be for the same transformId. * @param action the action this listener will take. When the TransformScheduler invokes {@link #triggered(TransformScheduler.Event)}, * the call is forwarded to this action. * @param actionListener actionListener will be notified via #onResponse when the action succeeds or via #onFailure when retries have * stopped. If the Transform Stop API deregisters this
TransformRetryableStartUpListener
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/antlr/EnhancedSuggestLexer.java
{ "start": 1200, "end": 2707 }
class ____ extends SuggestLexer { private Token current = null; private final PainlessLookup painlessLookup; public EnhancedSuggestLexer(CharStream charStream, PainlessLookup painlessLookup) { super(charStream); this.painlessLookup = painlessLookup; } @Override public Token nextToken() { current = super.nextToken(); return current; } @Override public void recover(final LexerNoViableAltException lnvae) { if (this._mode != PainlessLexer.DEFAULT_MODE) { this._mode = DEFAULT_MODE; } else { throw new IllegalStateException("unexpected token [" + lnvae.getOffendingToken().getText() + "]", lnvae); } } @Override protected boolean isSlashRegex() { Token lastToken = current; if (lastToken == null) { return true; } switch (lastToken.getType()) { case PainlessLexer.RBRACE: case PainlessLexer.RP: case PainlessLexer.OCTAL: case PainlessLexer.HEX: case PainlessLexer.INTEGER: case PainlessLexer.DECIMAL: case PainlessLexer.ID: case PainlessLexer.DOTINTEGER: case PainlessLexer.DOTID: return false; default: return true; } } @Override protected boolean isType(String text) { return painlessLookup.isValidCanonicalClassName(text); } }
EnhancedSuggestLexer
java
apache__rocketmq
example/src/main/java/org/apache/rocketmq/example/benchmark/BatchProducer.java
{ "start": 15944, "end": 19682 }
class ____ { private final LongAdder sendRequestSuccessCount = new LongAdder(); private final LongAdder sendRequestFailedCount = new LongAdder(); private final LongAdder sendMessageSuccessTimeTotal = new LongAdder(); private final AtomicLong sendMessageMaxRT = new AtomicLong(0L); private final LongAdder sendMessageSuccessCount = new LongAdder(); private final LongAdder sendMessageFailedCount = new LongAdder(); private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl( "BenchmarkTimerThread", Boolean.TRUE)); private final LinkedList<Long[]> snapshotList = new LinkedList<>(); private final int reportInterval; public StatsBenchmarkBatchProducer(int reportInterval) { this.reportInterval = reportInterval; } public Long[] createSnapshot() { Long[] snap = new Long[] { System.currentTimeMillis(), this.sendRequestSuccessCount.longValue(), this.sendRequestFailedCount.longValue(), this.sendMessageSuccessCount.longValue(), this.sendMessageFailedCount.longValue(), this.sendMessageSuccessTimeTotal.longValue(), }; return snap; } public LongAdder getSendRequestSuccessCount() { return sendRequestSuccessCount; } public LongAdder getSendRequestFailedCount() { return sendRequestFailedCount; } public LongAdder getSendMessageSuccessTimeTotal() { return sendMessageSuccessTimeTotal; } public AtomicLong getSendMessageMaxRT() { return sendMessageMaxRT; } public LongAdder getSendMessageSuccessCount() { return sendMessageSuccessCount; } public LongAdder getSendMessageFailedCount() { return sendMessageFailedCount; } public void start() { executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { snapshotList.addLast(createSnapshot()); if (snapshotList.size() > 10) { snapshotList.removeFirst(); } } }, 1000, 1000, TimeUnit.MILLISECONDS); executorService.scheduleAtFixedRate(new Runnable() { private void printStats() { if (snapshotList.size() >= 10) { Long[] begin = snapshotList.getFirst(); Long[] end = snapshotList.getLast(); final long sendTps = (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L); final long sendMps = (long) (((end[3] - begin[3]) / (double) (end[0] - begin[0])) * 1000L); final double averageRT = (end[5] - begin[5]) / (double) (end[1] - begin[1]); final double averageMsgRT = (end[5] - begin[5]) / (double) (end[3] - begin[3]); System.out.printf("Current Time: %s | Send TPS: %d | Send MPS: %d | Max RT(ms): %d | Average RT(ms): %7.3f | Average Message RT(ms): %7.3f | Send Failed: %d | Send Message Failed: %d%n", UtilAll.timeMillisToHumanString2(System.currentTimeMillis()), sendTps, sendMps, getSendMessageMaxRT().longValue(), averageRT, averageMsgRT, end[2], end[4]); } } @Override public void run() { try { this.printStats(); } catch (Exception e) { e.printStackTrace(); } } }, reportInterval, reportInterval, TimeUnit.MILLISECONDS); } public void shutdown() { executorService.shutdown(); } }
StatsBenchmarkBatchProducer
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointMetricsBuilder.java
{ "start": 1317, "end": 6054 }
class ____ { private CompletableFuture<Long> bytesProcessedDuringAlignment = new CompletableFuture<>(); private long bytesPersistedDuringAlignment = -1L; private CompletableFuture<Long> alignmentDurationNanos = new CompletableFuture<>(); private long syncDurationMillis = -1L; private long asyncDurationMillis = -1L; private long checkpointStartDelayNanos = -1L; private long totalBytesPersisted = -1L; private long bytesPersistedOfThisCheckpoint = -1L; public CheckpointMetricsBuilder setBytesProcessedDuringAlignment( long bytesProcessedDuringAlignment) { checkState( this.bytesProcessedDuringAlignment.complete(bytesProcessedDuringAlignment), "bytesProcessedDuringAlignment has already been completed by someone else"); return this; } public CheckpointMetricsBuilder setBytesProcessedDuringAlignment( CompletableFuture<Long> bytesProcessedDuringAlignment) { this.bytesProcessedDuringAlignment = bytesProcessedDuringAlignment; return this; } public CompletableFuture<Long> getBytesProcessedDuringAlignment() { return bytesProcessedDuringAlignment; } public CheckpointMetricsBuilder setBytesPersistedDuringAlignment( long bytesPersistedDuringAlignment) { this.bytesPersistedDuringAlignment = bytesPersistedDuringAlignment; return this; } public long getAlignmentDurationNanosOrDefault() { return FutureUtils.getOrDefault(alignmentDurationNanos, -1L); } public CheckpointMetricsBuilder setAlignmentDurationNanos(long alignmentDurationNanos) { checkState( this.alignmentDurationNanos.complete(alignmentDurationNanos), "alignmentDurationNanos has already been completed by someone else"); return this; } public CheckpointMetricsBuilder setAlignmentDurationNanos( CompletableFuture<Long> alignmentDurationNanos) { checkState( !this.alignmentDurationNanos.isDone(), "alignmentDurationNanos has already been completed by someone else"); this.alignmentDurationNanos = alignmentDurationNanos; return this; } public CompletableFuture<Long> getAlignmentDurationNanos() { return alignmentDurationNanos; } public CheckpointMetricsBuilder setSyncDurationMillis(long syncDurationMillis) { this.syncDurationMillis = syncDurationMillis; return this; } public long getSyncDurationMillis() { return syncDurationMillis; } public CheckpointMetricsBuilder setAsyncDurationMillis(long asyncDurationMillis) { this.asyncDurationMillis = asyncDurationMillis; return this; } public long getAsyncDurationMillis() { return asyncDurationMillis; } public CheckpointMetricsBuilder setCheckpointStartDelayNanos(long checkpointStartDelayNanos) { this.checkpointStartDelayNanos = checkpointStartDelayNanos; return this; } public long getCheckpointStartDelayNanos() { return checkpointStartDelayNanos; } public CheckpointMetricsBuilder setTotalBytesPersisted(long totalBytesPersisted) { this.totalBytesPersisted = totalBytesPersisted; return this; } public long getBytesPersistedOfThisCheckpoint() { return bytesPersistedOfThisCheckpoint; } public CheckpointMetricsBuilder setBytesPersistedOfThisCheckpoint( long bytesPersistedOfThisCheckpoint) { this.bytesPersistedOfThisCheckpoint = bytesPersistedOfThisCheckpoint; return this; } public CheckpointMetrics build() { return new CheckpointMetrics( checkStateAndGet(bytesProcessedDuringAlignment), bytesPersistedDuringAlignment, checkStateAndGet(alignmentDurationNanos), syncDurationMillis, asyncDurationMillis, checkpointStartDelayNanos, bytesPersistedDuringAlignment > 0, bytesPersistedOfThisCheckpoint, totalBytesPersisted); } public CheckpointMetrics buildIncomplete() { return new CheckpointMetrics( bytesProcessedDuringAlignment.getNow(CheckpointMetrics.UNSET), bytesPersistedDuringAlignment, alignmentDurationNanos.getNow(CheckpointMetrics.UNSET), syncDurationMillis, asyncDurationMillis, checkpointStartDelayNanos, bytesPersistedDuringAlignment > 0, bytesPersistedOfThisCheckpoint, totalBytesPersisted); } }
CheckpointMetricsBuilder
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/SuperClass.java
{ "start": 276, "end": 628 }
class ____<T> { @POST @Path("/super") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public List<T> reverseListFromSuper(List<T> list) { List<T> reversed = new ArrayList<>(list.size()); for (T t : list) { reversed.add(0, t); } return reversed; } }
SuperClass
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/features/MapFeature.java
{ "start": 2982, "end": 3084 }
interface ____ { MapFeature[] value() default {}; MapFeature[] absent() default {}; } }
Require
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/statistics/impl/DynamicIOStatistics.java
{ "start": 1349, "end": 3726 }
class ____ extends AbstractIOStatisticsImpl { /** * Counter evaluators. */ private final EvaluatingStatisticsMap<Long> counters = new EvaluatingStatisticsMap<>(); private final EvaluatingStatisticsMap<Long> gauges = new EvaluatingStatisticsMap<>(); private final EvaluatingStatisticsMap<Long> minimums = new EvaluatingStatisticsMap<>(); private final EvaluatingStatisticsMap<Long> maximums = new EvaluatingStatisticsMap<>(); private final EvaluatingStatisticsMap<MeanStatistic> meanStatistics = new EvaluatingStatisticsMap<>(MeanStatistic::copy); DynamicIOStatistics() { } @Override public Map<String, Long> counters() { return Collections.unmodifiableMap(counters); } @Override public Map<String, Long> gauges() { return Collections.unmodifiableMap(gauges); } @Override public Map<String, Long> minimums() { return Collections.unmodifiableMap(minimums); } @Override public Map<String, Long> maximums() { return Collections.unmodifiableMap(maximums); } @Override public Map<String, MeanStatistic> meanStatistics() { return Collections.unmodifiableMap(meanStatistics); } /** * add a mapping of a key to a counter function. * @param key the key * @param eval the evaluator */ void addCounterFunction(String key, Function<String, Long> eval) { counters.addFunction(key, eval); } /** * add a mapping of a key to a gauge function. * @param key the key * @param eval the evaluator */ void addGaugeFunction(String key, Function<String, Long> eval) { gauges.addFunction(key, eval); } /** * add a mapping of a key to a minimum function. * @param key the key * @param eval the evaluator */ void addMinimumFunction(String key, Function<String, Long> eval) { minimums.addFunction(key, eval); } /** * add a mapping of a key to a maximum function. * @param key the key * @param eval the evaluator */ void addMaximumFunction(String key, Function<String, Long> eval) { maximums.addFunction(key, eval); } /** * add a mapping of a key to a meanStatistic function. * @param key the key * @param eval the evaluator */ void addMeanStatisticFunction(String key, Function<String, MeanStatistic> eval) { meanStatistics.addFunction(key, eval); } }
DynamicIOStatistics
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/lookup/ArgumentLookupBuiltinBeansTest.java
{ "start": 4426, "end": 4507 }
class ____ implements MyInterface { } @Singleton static
MyInterfaceImpl1
java
netty__netty
transport-sctp/src/main/java/io/netty/channel/sctp/oio/OioSctpChannel.java
{ "start": 17067, "end": 17380 }
class ____ extends DefaultSctpChannelConfig { private OioSctpChannelConfig(OioSctpChannel channel, SctpChannel javaChannel) { super(channel, javaChannel); } @Override protected void autoReadCleared() { clearReadPending(); } } }
OioSctpChannelConfig
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/action/admin/indices/diskusage/AnalyzeIndexDiskUsageTestUtils.java
{ "start": 576, "end": 1390 }
class ____ { private AnalyzeIndexDiskUsageTestUtils() {} @Nullable public static IndexDiskUsageStats getIndexStats(final AnalyzeIndexDiskUsageResponse diskUsageResponse, final String indexName) { var stats = diskUsageResponse.getStats(); if (stats != null) { return stats.get(indexName); } return null; } @Nullable public static IndexDiskUsageStats.PerFieldDiskUsage getPerFieldDiskUsage( final IndexDiskUsageStats indexDiskUsageStats, final String fieldName ) { if (indexDiskUsageStats != null) { var fields = indexDiskUsageStats.getFields(); if (fields != null) { return fields.get(fieldName); } } return null; } }
AnalyzeIndexDiskUsageTestUtils
java
grpc__grpc-java
api/src/main/java/io/grpc/ServerTransportFilter.java
{ "start": 1300, "end": 2246 }
class ____ { /** * Called when a transport is ready to process streams. All necessary handshakes, e.g., TLS * handshake, are done at this point. * * <p>Note the implementation should always inherit the passed-in attributes using {@code * Attributes.newBuilder(transportAttrs)}, instead of creating one from scratch. * * @param transportAttrs current transport attributes * * @return new transport attributes. Default implementation returns the passed-in attributes * intact. */ public Attributes transportReady(Attributes transportAttrs) { return transportAttrs; } /** * Called when a transport is terminated. Default implementation is no-op. * * @param transportAttrs the effective transport attributes, which is what returned by {@link * #transportReady} of the last executed filter. */ public void transportTerminated(Attributes transportAttrs) { } }
ServerTransportFilter
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/source/TimestampsAndWatermarks.java
{ "start": 1998, "end": 2141 }
interface ____<T> { /** Lets the owner/creator of the output know about latest emitted watermark. */ @Internal
TimestampsAndWatermarks
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetJavaTypeRegistrationTests.java
{ "start": 1619, "end": 2258 }
class ____ { @Id private Integer id; private BitSet bitSet; //Constructors, getters, and setters are omitted for brevity //end::basic-bitset-example-java-type-global[] public Product() { } public Product(Number id, BitSet bitSet) { this.id = id.intValue(); this.bitSet = bitSet; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public BitSet getBitSet() { return bitSet; } public void setBitSet(BitSet bitSet) { this.bitSet = bitSet; } //tag::basic-bitset-example-java-type-global[] } //end::basic-bitset-example-java-type-global[] }
Product
java
elastic__elasticsearch
x-pack/plugin/profiling/src/main/java/org/elasticsearch/xpack/profiling/action/TransportGetFlamegraphAction.java
{ "start": 7026, "end": 15027 }
class ____ { private int currentNode = 0; // size is the number of nodes in the flamegraph private int size = 0; private long selfCPU; private long totalCPU; // totalSamples is the total number of samples in the stacktraces private final long totalSamples; // Map: FrameGroupId -> NodeId private final List<Map<String, Integer>> edges; private final List<String> fileIds; private final List<Integer> frameTypes; private final List<Boolean> inlineFrames; private final List<String> fileNames; private final List<Integer> addressOrLines; private final List<String> functionNames; private final List<Integer> functionOffsets; private final List<String> sourceFileNames; private final List<Integer> sourceLines; private final List<Long> countInclusive; private final List<Long> countExclusive; private final List<Double> annualCO2TonsExclusive; private final List<Double> annualCO2TonsInclusive; private final List<Double> annualCostsUSDExclusive; private final List<Double> annualCostsUSDInclusive; private final double samplingRate; FlamegraphBuilder(long totalSamples, int frames, double samplingRate) { // as the number of frames does not account for inline frames we slightly overprovision. int capacity = (int) (frames * 1.1d); this.edges = new ArrayList<>(capacity); this.fileIds = new ArrayList<>(capacity); this.frameTypes = new ArrayList<>(capacity); this.inlineFrames = new ArrayList<>(capacity); this.fileNames = new ArrayList<>(capacity); this.addressOrLines = new ArrayList<>(capacity); this.functionNames = new ArrayList<>(capacity); this.functionOffsets = new ArrayList<>(capacity); this.sourceFileNames = new ArrayList<>(capacity); this.sourceLines = new ArrayList<>(capacity); this.countInclusive = new ArrayList<>(capacity); this.countExclusive = new ArrayList<>(capacity); this.annualCO2TonsInclusive = new ArrayList<>(capacity); this.annualCO2TonsExclusive = new ArrayList<>(capacity); this.annualCostsUSDInclusive = new ArrayList<>(capacity); this.annualCostsUSDExclusive = new ArrayList<>(capacity); this.totalSamples = totalSamples; this.samplingRate = samplingRate; // always insert root node int nodeId = this.addNode("", FRAMETYPE_ROOT, false, "", 0, "", 0, "", 0, 0, 0.0, 0.0, null); this.setCurrentNode(nodeId); } // returns the new node's id public int addNode( String fileId, int frameType, boolean inline, String fileName, int addressOrLine, String functionName, int functionOffset, String sourceFileName, int sourceLine, long samples, double annualCO2Tons, double annualCostsUSD, String frameGroupId ) { int node = this.size; this.edges.add(new HashMap<>()); this.fileIds.add(fileId); this.frameTypes.add(frameType); this.inlineFrames.add(inline); this.fileNames.add(fileName); this.addressOrLines.add(addressOrLine); this.functionNames.add(functionName); this.functionOffsets.add(functionOffset); this.sourceFileNames.add(sourceFileName); this.sourceLines.add(sourceLine); this.countInclusive.add(samples); this.totalCPU += samples; this.countExclusive.add(0L); this.annualCO2TonsInclusive.add(annualCO2Tons); this.annualCO2TonsExclusive.add(0.0); this.annualCostsUSDInclusive.add(annualCostsUSD); this.annualCostsUSDExclusive.add(0.0); if (frameGroupId != null) { this.edges.get(currentNode).put(frameGroupId, node); } this.size++; return node; } public void addToRootNode(long samples, double annualCO2Tons, double annualCostsUSD) { addSamplesInclusive(0, samples); addAnnualCO2TonsInclusive(0, annualCO2Tons); addAnnualCostsUSDInclusive(0, annualCostsUSD); } public void addOrUpdateAggregationNode(String name, long samples, double annualCO2Tons, double annualCostsUSD, int frameType) { String frameGroupId = Integer.toString(Objects.hash(name, frameType)); int nodeId = getNodeId(frameGroupId); if (nodeId != -1) { addSamplesInclusive(nodeId, samples); addAnnualCO2TonsInclusive(nodeId, annualCO2Tons); addAnnualCostsUSDInclusive(nodeId, annualCostsUSD); setCurrentNode(nodeId); } else { setCurrentNode(addNode("", frameType, false, name, 0, "", 0, "", 0, samples, annualCO2Tons, annualCostsUSD, frameGroupId)); } } public void setCurrentNode(int nodeId) { this.currentNode = nodeId; } public boolean isExists(String frameGroupId) { return this.edges.get(currentNode).containsKey(frameGroupId); } public int getNodeId(String frameGroupId) { return this.edges.get(currentNode).getOrDefault(frameGroupId, -1); } public void addSamplesInclusive(int nodeId, long sampleCount) { Long priorSampleCount = this.countInclusive.get(nodeId); this.countInclusive.set(nodeId, priorSampleCount + sampleCount); this.totalCPU += sampleCount; } public void addSamplesExclusive(int nodeId, long sampleCount) { Long priorSampleCount = this.countExclusive.get(nodeId); this.countExclusive.set(nodeId, priorSampleCount + sampleCount); this.selfCPU += sampleCount; } public void addAnnualCO2TonsInclusive(int nodeId, double annualCO2Tons) { Double priorAnnualCO2Tons = this.annualCO2TonsInclusive.get(nodeId); this.annualCO2TonsInclusive.set(nodeId, priorAnnualCO2Tons + annualCO2Tons); } public void addAnnualCO2TonsExclusive(int nodeId, double annualCO2Tons) { Double priorAnnualCO2Tons = this.annualCO2TonsExclusive.get(nodeId); this.annualCO2TonsExclusive.set(nodeId, priorAnnualCO2Tons + annualCO2Tons); } public void addAnnualCostsUSDInclusive(int nodeId, double annualCostsUSD) { Double priorAnnualCostsUSD = this.annualCostsUSDInclusive.get(nodeId); this.annualCostsUSDInclusive.set(nodeId, priorAnnualCostsUSD + annualCostsUSD); } public void addAnnualCostsUSDExclusive(int nodeId, double annualCostsUSD) { Double priorAnnualCostsUSD = this.annualCostsUSDExclusive.get(nodeId); this.annualCostsUSDExclusive.set(nodeId, priorAnnualCostsUSD + annualCostsUSD); } public GetFlamegraphResponse build() { return new GetFlamegraphResponse( size, samplingRate, edges, fileIds, frameTypes, inlineFrames, fileNames, addressOrLines, functionNames, functionOffsets, sourceFileNames, sourceLines, countInclusive, countExclusive, annualCO2TonsInclusive, annualCO2TonsExclusive, annualCostsUSDInclusive, annualCostsUSDExclusive, selfCPU, totalCPU, totalSamples ); } } }
FlamegraphBuilder
java
alibaba__nacos
naming/src/test/java/com/alibaba/nacos/naming/core/ClusterOperatorV2ImplTest.java
{ "start": 1371, "end": 2291 }
class ____ { private ClusterOperatorV2Impl clusterOperatorV2Impl; @Mock private NamingMetadataOperateService metadataOperateServiceMock; private ClusterMetadata clusterMetadata; @BeforeEach void setUp() throws Exception { Service service = Service.newService("namespace_test", "group_test", "name_test"); ServiceManager.getInstance().getSingleton(service); clusterOperatorV2Impl = new ClusterOperatorV2Impl(metadataOperateServiceMock); clusterMetadata = new ClusterMetadata(); } @Test void testUpdateClusterMetadata() throws NacosException { clusterOperatorV2Impl.updateClusterMetadata("namespace_test", "group_test@@name_test", "clusterName_test", clusterMetadata); verify(metadataOperateServiceMock).addClusterMetadata(any(Service.class), anyString(), any(ClusterMetadata.class)); } }
ClusterOperatorV2ImplTest
java
quarkusio__quarkus
integration-tests/smallrye-config/src/main/java/io/quarkus/it/smallrye/config/Server.java
{ "start": 1720, "end": 1870 }
interface ____ { @JsonProperty boolean enable(); @JsonProperty int timeout(); } @RegisterForReflection
Proxy
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxRefCountGrace.java
{ "start": 5413, "end": 10024 }
class ____<T> implements QueueSubscription<T>, InnerOperator<T, T> { final CoreSubscriber<? super T> actual; final FluxRefCountGrace<T> parent; @Nullable RefConnection connection; @SuppressWarnings("NotNullFieldNotInitialized") // s initialized in onSubscribe Subscription s; @SuppressWarnings("NotNullFieldNotInitialized") // qs initialized in fusion mode QueueSubscription<T> qs; @Nullable Throwable error; static final int MONITOR_SET_FLAG = 0b0010_0000_0000_0000_0000_0000_0000_0000; static final int TERMINATED_FLAG = 0b0100_0000_0000_0000_0000_0000_0000_0000; static final int CANCELLED_FLAG = 0b1000_0000_0000_0000_0000_0000_0000_0000; volatile int state; //used to guard against doubly terminating subscribers (e.g. double cancel) @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater<RefCountInner> STATE = AtomicIntegerFieldUpdater.newUpdater(RefCountInner.class, "state"); RefCountInner(CoreSubscriber<? super T> actual, FluxRefCountGrace<T> parent) { this.actual = actual; this.parent = parent; } void setRefConnection(RefConnection connection) { this.connection = connection; this.actual.onSubscribe(this); for (;;) { int previousState = this.state; if (isCancelled(previousState)) { return; } if (isTerminated(previousState)) { this.parent.terminated(connection); Throwable e = this.error; if (e != null) { this.actual.onError(e); } else { this.actual.onComplete(); } return; } if (STATE.compareAndSet(this, previousState, previousState | MONITOR_SET_FLAG)) { return; } } } @Override public void onNext(T t) { actual.onNext(t); } @Override public void onError(Throwable t) { this.error = t; for (;;) { int previousState = this.state; if (isTerminated(previousState) || isCancelled(previousState)) { Operators.onErrorDropped(t, actual.currentContext()); return; } if (STATE.compareAndSet(this, previousState, previousState | TERMINATED_FLAG)) { if (isMonitorSet(previousState)) { assert connection != null : "connection must not be null when monitor is set"; this.parent.terminated(connection); this.actual.onError(t); } return; } } } @Override public void onComplete() { for (;;) { int previousState = this.state; if (isTerminated(previousState) || isCancelled(previousState)) { return; } if (STATE.compareAndSet(this, previousState, previousState | TERMINATED_FLAG)) { if (isMonitorSet(previousState)) { assert connection != null : "connection must not be null when monitor is set"; this.parent.terminated(connection); this.actual.onComplete(); } return; } } } @Override public void request(long n) { s.request(n); } @Override public void cancel() { s.cancel(); int previousState = this.state; if (isTerminated(previousState) || isCancelled(previousState)) { return; } if (STATE.compareAndSet(this, previousState, previousState | CANCELLED_FLAG)) { assert connection != null : "connection must not be null when cancelling"; parent.cancel(connection); } } @Override public void onSubscribe(Subscription s) { if (Operators.validate(this.s, s)) { this.s = s; } } @Override @SuppressWarnings("unchecked") public int requestFusion(int requestedMode) { if(s instanceof QueueSubscription){ qs = (QueueSubscription<T>)s; return qs.requestFusion(requestedMode); } return Fuseable.NONE; } @Override public @Nullable T poll() { return qs.poll(); } @Override public int size() { return qs.size(); } @Override public boolean isEmpty() { return qs.isEmpty(); } @Override public void clear() { qs.clear(); } @Override public CoreSubscriber<? super T> actual() { return actual; } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; if (key == Attr.PARENT) return s; if (key == Attr.TERMINATED) return isTerminated(state); if (key == Attr.CANCELLED) return isCancelled(state); return InnerOperator.super.scanUnsafe(key); } static boolean isTerminated(int state) { return (state & TERMINATED_FLAG) == TERMINATED_FLAG; } static boolean isCancelled(int state) { return (state & CANCELLED_FLAG) == CANCELLED_FLAG; } static boolean isMonitorSet(int state) { return (state & MONITOR_SET_FLAG) == MONITOR_SET_FLAG; } } }
RefCountInner
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/misc/DropUpdateBeforeFunction.java
{ "start": 1292, "end": 1545 }
class ____ implements FilterFunction<RowData> { private static final long serialVersionUID = 1L; @Override public boolean filter(RowData value) { return !RowKind.UPDATE_BEFORE.equals(value.getRowKind()); } }
DropUpdateBeforeFunction
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/TableEnvironment.java
{ "start": 62910, "end": 63566 }
class ____ for the format of the path. * @return true if model existed in the given path and was dropped, false if model didn't exist * in the given path. */ boolean dropModel(String path); /** * Drops a model registered in the given path. * * <p>This method can only drop permanent objects. Temporary objects can shadow permanent ones. * If a temporary object exists in a given path, make sure to drop the temporary object first * using {@link #dropTemporaryModel}. * * @param path The given path under which the model will be dropped. See also the {@link * TableEnvironment}
description
java
quarkusio__quarkus
integration-tests/test-extension/extension/deployment/src/main/java/io/quarkus/extest/deployment/PublicKeyBuildItem.java
{ "start": 148, "end": 410 }
class ____ extends SimpleBuildItem { private DSAPublicKey publicKey; public PublicKeyBuildItem(DSAPublicKey publicKey) { this.publicKey = publicKey; } public DSAPublicKey getPublicKey() { return publicKey; } }
PublicKeyBuildItem
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/LambdaFunctionalInterfaceTest.java
{ "start": 1651, "end": 2836 }
class ____ { // BUG: Diagnostic contains: [LambdaFunctionalInterface] private double fooIntToDoubleFunctionPr(int x, Function<Integer, Double> fn) { return fn.apply(x); } // BUG: Diagnostic contains: [LambdaFunctionalInterface] private long fooIntToLongFunction(int x, Function<Integer, Long> fn) { return fn.apply(x); } // BUG: Diagnostic contains: [LambdaFunctionalInterface] private long fooIntToIntFunction(int x, Function<Integer, Long> fn) { return fn.apply(x); } // BUG: Diagnostic contains: [LambdaFunctionalInterface] private double fooDoubleToDoubleFunction(double x, Function<Double, Double> fn) { return fn.apply(x); } // BUG: Diagnostic contains: [LambdaFunctionalInterface] private int fooDoubleToIntFunction(double x, Function<Double, Integer> fn) { return fn.apply(x); } // BUG: Diagnostic contains: [LambdaFunctionalInterface] private void fooInterface(String str, Function<Integer, Double> func) {} // BUG: Diagnostic contains: [LambdaFunctionalInterface] private double fooDouble(double x, Function<Double, Integer> fn) { return fn.apply(x); } public static
LambdaFunctionalInterfacePositiveCases
java
google__guice
extensions/assistedinject/test/com/google/inject/assistedinject/FactoryModuleBuilderTest.java
{ "start": 21111, "end": 21262 }
interface ____ { AssistedSingleton create(String string); } @SuppressWarnings("GuiceAssistedInjectScoping") @Singleton static
SingletonFactory
java
apache__camel
components/camel-jcache/src/test/java/org/apache/camel/component/jcache/JCacheProducerPutTest.java
{ "start": 1317, "end": 6026 }
class ____ extends JCacheComponentTestSupport { @Test public void testPut() throws Exception { final Map<String, Object> headers = new HashMap<>(); final Cache<Object, Object> cache = getCacheFromEndpoint("jcache://test-cache"); final String key = randomString(); final String val = randomString(); headers.clear(); headers.put(JCacheConstants.ACTION, "PUT"); headers.put(JCacheConstants.KEY, key); sendBody("direct:put", val, headers); assertTrue(cache.containsKey(key)); assertEquals(val, cache.get(key)); } @Test public void testPutWithDefaultAction() throws Exception { final Map<String, Object> headers = new HashMap<>(); final Cache<Object, Object> cache = getCacheFromEndpoint("jcache://test-cache?action=PUT"); final String key = randomString(); final String val = randomString(); headers.clear(); headers.put(JCacheConstants.KEY, key); sendBody("direct:put-with-default-action", val, headers); assertTrue(cache.containsKey(key)); assertEquals(val, cache.get(key)); } @Test public void testPutIfAbsent() throws Exception { final Map<String, Object> headers = new HashMap<>(); final Cache<Object, Object> cache = getCacheFromEndpoint("jcache://test-cache"); final String key = randomString(); final String val = randomString(); headers.clear(); headers.put(JCacheConstants.ACTION, "PUTIFABSENT"); headers.put(JCacheConstants.KEY, key); sendBody("direct:put-if-absent", val, headers); assertTrue(cache.containsKey(key)); assertEquals(val, cache.get(key)); MockEndpoint mock = getMockEndpoint("mock:put-if-absent"); mock.expectedMinimumMessageCount(1); mock.expectedHeaderReceived(JCacheConstants.KEY, key); mock.expectedHeaderReceived(JCacheConstants.RESULT, true); mock.expectedMessagesMatches(new Predicate() { @Override public boolean matches(Exchange exchange) { assertNotNull(exchange.getIn().getBody(), "body"); return exchange.getIn().getBody().equals(val); } }); mock.assertIsSatisfied(); } @Test public void testPutIfAbsentFailure() throws Exception { final Map<String, Object> headers = new HashMap<>(); final Cache<Object, Object> cache = getCacheFromEndpoint("jcache://test-cache"); final String key = randomString(); final String val = randomString(); cache.put(key, val); headers.clear(); headers.put(JCacheConstants.ACTION, "PUTIFABSENT"); headers.put(JCacheConstants.KEY, key); sendBody("direct:put-if-absent", val, headers); MockEndpoint mock = getMockEndpoint("mock:put-if-absent"); mock.expectedMinimumMessageCount(1); mock.expectedHeaderReceived(JCacheConstants.KEY, key); mock.expectedHeaderReceived(JCacheConstants.RESULT, false); mock.expectedMessagesMatches(new Predicate() { @Override public boolean matches(Exchange exchange) { assertNotNull(exchange.getIn().getBody(), "body"); return exchange.getIn().getBody().equals(val); } }); mock.assertIsSatisfied(); } @Test public void testPutAll() throws Exception { final Map<String, Object> headers = new HashMap<>(); final Cache<Object, Object> cache = getCacheFromEndpoint("jcache://test-cache"); Map<Object, Object> values = generateRandomMap(2); headers.clear(); headers.put(JCacheConstants.ACTION, "PUTALL"); headers.put(JCacheConstants.KEY, values); sendBody("direct:put", values, headers); for (Map.Entry<Object, Object> entry : values.entrySet()) { assertTrue(cache.containsKey(entry.getKey())); assertEquals(entry.getValue(), cache.get(entry.getKey())); } } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:put") .to("jcache://test-cache"); from("direct:put-with-default-action") .to("jcache://test-cache?action=PUT"); from("direct:put-if-absent") .to("jcache://test-cache") .to("mock:put-if-absent"); from("direct:put-all") .to("jcache://test-cache"); } }; } }
JCacheProducerPutTest
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/security/inheritance/SubPaths.java
{ "start": 753, "end": 4385 }
class ____. */ String IMPL_ON_INTERFACE = "/impl-on-interface"; String SUB_DECLARED_ON = "/sub-resource-declared-on-"; /** * Following 3 constants refer to where method like {@code @Path("sub") SubResource subResource} with JAX-RS * sub-resource declaring annotations are declared. */ String SUB_DECLARED_ON_INTERFACE = SUB_DECLARED_ON + "interface"; String SUB_DECLARED_ON_BASE = SUB_DECLARED_ON + "base"; String SUB_DECLARED_ON_PARENT = SUB_DECLARED_ON + "parent"; String SECURED_SUB_RESOURCE_ENDPOINT_PATH = "/secured"; /** * Following 3 constants refer to where method like {@code @Override SubResource subResource() { return new SubResource(); * }} * is implemented. That is whether actually invoked sub-resource endpoint is placed on a base, parent or an interface. */ String SUB_IMPL_ON_BASE = "/sub-impl-on-base"; String SUB_IMPL_ON_PARENT = "/sub-impl-on-parent"; String SUB_IMPL_ON_INTERFACE = "/sub-impl-on-interface"; String IMPL_METHOD_WITH_PATH = "/impl-met-with-path"; String PARENT_METHOD_WITH_PATH = "/parent-met-with-path"; String INTERFACE_METHOD_WITH_PATH = "/interface-met-with-path"; String CLASS_NO_ANNOTATION_PREFIX = "/class-no-annotation-"; String CLASS_ROLES_ALLOWED_PREFIX = "/class-roles-allowed-"; String CLASS_DENY_ALL_PREFIX = "/class-deny-all-"; String CLASS_PERMIT_ALL_PREFIX = "/class-permit-all-"; String NO_SECURITY_ANNOTATION_PATH = "/no-security-annotation"; String METHOD_ROLES_ALLOWED_PATH = "/method-roles-allowed"; String METHOD_DENY_ALL_PATH = "/method-deny-all"; String METHOD_PERMIT_ALL_PATH = "/method-permit-all"; String CLASS_ROLES_ALLOWED_PATH = "/class-roles-allowed"; String CLASS_DENY_ALL_PATH = "/class-deny-all"; String CLASS_PERMIT_ALL_PATH = "/class-permit-all"; String CLASS_DENY_ALL_METHOD_ROLES_ALLOWED_PATH = "/class-deny-all-method-roles-allowed"; String CLASS_DENY_ALL_METHOD_PERMIT_ALL_PATH = "/class-deny-all-method-permit-all"; String CLASS_PERMIT_ALL_METHOD_PERMIT_ALL_PATH = "/class-permit-all-method-permit-all"; String MULTIPLE_INHERITANCE = "multiple-inheritance-"; /** * Interface implemented by a base/parent resource. */ String FIRST_INTERFACE = "/first-interface"; /** * Interface that extends {@link #FIRST_INTERFACE}. */ String SECOND_INTERFACE = "/second-interface"; /** * Interface that extends {@link #SECOND_INTERFACE}. */ String THIRD_INTERFACE = "/third-interface"; SubPath NO_SECURITY_ANNOTATION = new SubPath(CLASS_NO_ANNOTATION_PREFIX, NO_SECURITY_ANNOTATION_PATH); SubPath METHOD_ROLES_ALLOWED = new SubPath(CLASS_NO_ANNOTATION_PREFIX, METHOD_ROLES_ALLOWED_PATH); SubPath METHOD_DENY_ALL = new SubPath(CLASS_NO_ANNOTATION_PREFIX, METHOD_DENY_ALL_PATH); SubPath METHOD_PERMIT_ALL = new SubPath(CLASS_NO_ANNOTATION_PREFIX, METHOD_PERMIT_ALL_PATH); SubPath CLASS_ROLES_ALLOWED = new SubPath(CLASS_ROLES_ALLOWED_PREFIX, CLASS_ROLES_ALLOWED_PATH); SubPath CLASS_DENY_ALL = new SubPath(CLASS_DENY_ALL_PREFIX, CLASS_DENY_ALL_PATH); SubPath CLASS_PERMIT_ALL = new SubPath(CLASS_PERMIT_ALL_PREFIX, CLASS_PERMIT_ALL_PATH); SubPath CLASS_DENY_ALL_METHOD_ROLES_ALLOWED = new SubPath(CLASS_DENY_ALL_PREFIX, CLASS_DENY_ALL_METHOD_ROLES_ALLOWED_PATH); SubPath CLASS_DENY_ALL_METHOD_PERMIT_ALL = new SubPath(CLASS_DENY_ALL_PREFIX, CLASS_DENY_ALL_METHOD_PERMIT_ALL_PATH); SubPath CLASS_PERMIT_ALL_METHOD_PERMIT_ALL = new SubPath(CLASS_PERMIT_ALL_PREFIX, CLASS_PERMIT_ALL_METHOD_PERMIT_ALL_PATH); }
hierarchy
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/Base64Test.java
{ "start": 142, "end": 403 }
class ____ extends TestCase { public void test_base64() throws Exception { Assert.assertEquals(IOUtils.decodeBase64(new char[0], 0, 0).length, 0); Assert.assertEquals(IOUtils.decodeBase64("ABC".toCharArray(), 0, 3).length, 2); } }
Base64Test
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/complex_column/PersonMapper.java
{ "start": 981, "end": 2663 }
interface ____ { Person getWithoutComplex(Long id); Person getWithComplex(Long id); Person getParentWithComplex(Person person); // @formatter:off @Select({ "SELECT id, firstName, lastName, parent_id, parent_firstName, parent_lastName", "FROM Person", "WHERE id = #{id,jdbcType=INTEGER}" }) // @formatter:on @ResultMap("personMapComplex") Person getWithComplex2(Long id); // @formatter:off @Select({ "SELECT id, firstName, lastName, parent_id, parent_firstName, parent_lastName", "FROM Person", "WHERE id = #{id,jdbcType=INTEGER}" }) // @formatter:on @ResultMap("org.apache.ibatis.submitted.complex_column.PersonMapper.personMapComplex") Person getWithComplex3(Long id); // @formatter:off @Select({ "SELECT id, firstName, lastName, parent_id, parent_firstName, parent_lastName", "FROM Person", "WHERE id = #{id,jdbcType=INTEGER}" }) @Results({ @Result(id = true, column = "id", property = "id"), @Result(property = "parent", column = "{firstName=parent_firstName,lastName=parent_lastName}", one = @One(select = "getParentWithParamAttributes")) }) // @formatter:on Person getComplexWithParamAttributes(Long id); @Select(""" SELECT id\ , firstName\ , lastName\ , parent_id\ , parent_firstName\ , parent_lastName\ FROM Person\ WHERE firstName = #{firstName, jdbcType=VARCHAR}\ AND lastName = #{lastName, jdbcType=VARCHAR}\ LIMIT 1\ """) Person getParentWithParamAttributes(@Param("firstName") String firstName, @Param("lastName") String lastname); }
PersonMapper
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/NameSpaceTablesInformation.java
{ "start": 388, "end": 1124 }
class ____ { private final IdentifierHelper identifierHelper; private final Map<String, TableInformation> tables = new HashMap<>(); public NameSpaceTablesInformation(IdentifierHelper identifierHelper) { this.identifierHelper = identifierHelper; } public void addTableInformation(TableInformation tableInformation) { tables.put( tableInformation.getName().getTableName().getText(), tableInformation ); } public @Nullable TableInformation getTableInformation(Table table) { return tables.get( identifierHelper.toMetaDataObjectName( table.getQualifiedTableName().getTableName() ) ); } public @Nullable TableInformation getTableInformation(String tableName) { return tables.get( tableName ); } }
NameSpaceTablesInformation
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/reverse/Target.java
{ "start": 228, "end": 982 }
class ____ { private String stringPropY; private Integer integerPropY; private String propertyNotToIgnoreUpstream; public String getStringPropY() { return stringPropY; } public void setStringPropY(String stringPropY) { this.stringPropY = stringPropY; } public Integer getIntegerPropY() { return integerPropY; } public void setIntegerPropY(Integer integerPropY) { this.integerPropY = integerPropY; } public String getPropertyNotToIgnoreUpstream() { return propertyNotToIgnoreUpstream; } public void setPropertyNotToIgnoreUpstream(String propertyNotToIgnoreUpstream) { this.propertyNotToIgnoreUpstream = propertyNotToIgnoreUpstream; } }
Target
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/UpdateCalendarJobAction.java
{ "start": 761, "end": 1103 }
class ____ extends ActionType<PutCalendarAction.Response> { public static final UpdateCalendarJobAction INSTANCE = new UpdateCalendarJobAction(); public static final String NAME = "cluster:admin/xpack/ml/calendars/jobs/update"; private UpdateCalendarJobAction() { super(NAME); } public static
UpdateCalendarJobAction
java
redisson__redisson
redisson/src/main/java/org/redisson/spring/support/RedissonDefinitionParser.java
{ "start": 2252, "end": 7186 }
enum ____ { slaveAddress, sentinelAddress, nodeAddress; public static boolean contains(String type) { try { valueOf(type); return true; } catch (IllegalArgumentException e) { return false; } } } private final RedissonNamespaceParserSupport helper; RedissonDefinitionParser(RedissonNamespaceParserSupport helper) { this.helper = helper; } private void parseChildElements(Element element, String parentId, String redissonRef, BeanDefinitionBuilder redissonDef, ParserContext parserContext) { if (element.hasChildNodes()) { CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(parentId, parserContext.extractSource(element)); parserContext.pushContainingComponent(compositeDef); List<Element> childElts = DomUtils.getChildElements(element); for (Element elt : childElts) { if (BeanDefinitionParserDelegate.QUALIFIER_ELEMENT.equals(elt.getLocalName())) { continue; //parsed elsewhere } String localName = parserContext.getDelegate().getLocalName(elt); localName = Conventions.attributeNameToPropertyName(localName); if (ConfigType.contains(localName)) { parseConfigTypes(elt, localName, redissonDef, parserContext); } else if (AddressType.contains(localName)) { parseAddressTypes(elt, localName, redissonDef, parserContext); } else if (helper.isRedissonNS(elt)) { elt.setAttribute(REDISSON_REF, redissonRef); parserContext.getDelegate().parseCustomElement(elt); } } parserContext.popContainingComponent(); } } private void parseConfigTypes(Element element, String configType, BeanDefinitionBuilder redissonDef, ParserContext parserContext) { BeanDefinitionBuilder builder = helper.createBeanDefinitionBuilder(element, parserContext, null); //Use factory method on the Config bean AbstractBeanDefinition bd = builder.getRawBeanDefinition(); bd.setFactoryMethodName("use" + StringUtils.capitalize(configType)); bd.setFactoryBeanName(parserContext.getContainingComponent().getName()); String id = parserContext.getReaderContext().generateBeanName(bd); helper.registerBeanDefinition(builder, id, helper.parseAliase(element), parserContext); helper.parseAttributes(element, parserContext, builder); redissonDef.addDependsOn(id); parseChildElements(element, id, null, redissonDef, parserContext); parserContext.getDelegate().parseQualifierElements(element, bd); } private void parseAddressTypes(Element element, String addressType, BeanDefinitionBuilder redissonDef, ParserContext parserContext) { BeanComponentDefinition invoker = helper.invoker(element, parserContext.getContainingComponent().getName(), "add" + StringUtils.capitalize(addressType), new String[]{element.getAttribute("value")}, parserContext); String id = invoker.getName(); redissonDef.addDependsOn(id); } @Override public BeanDefinition parse(Element element, ParserContext parserContext) { //Sort out the Config Class BeanDefinitionBuilder configBuilder = helper.createBeanDefinitionBuilder(element, parserContext, Config.class); String configId = helper.getId(null, configBuilder, parserContext); helper.parseAttributes(element, parserContext, configBuilder); helper.registerBeanDefinition(configBuilder, configId, null, parserContext); //Do the main Redisson bean BeanDefinitionBuilder builder = helper.createBeanDefinitionBuilder(element, parserContext, Redisson.class); builder.setFactoryMethod("create"); builder.setDestroyMethodName("shutdown"); builder.addConstructorArgReference(configId); parserContext.getDelegate().parseQualifierElements(element, builder.getRawBeanDefinition()); String id = helper.getId(element, builder, parserContext); helper.parseAttributes(element, parserContext, configBuilder); //Sort out all the nested elements parseChildElements(element, configId, id, builder, parserContext); helper.registerBeanDefinition(builder, id, helper.parseAliase(element), parserContext); return builder.getBeanDefinition(); } }
AddressType
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/transport/RemoteConnectionManagerTests.java
{ "start": 1924, "end": 10870 }
class ____ extends ESTestCase { private Transport transport; private RemoteConnectionManager remoteConnectionManager; private ConnectionManager.ConnectionValidator validator = (connection, profile, listener) -> listener.onResponse(null); private TransportAddress address = new TransportAddress(InetAddress.getLoopbackAddress(), 1000); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception { super.setUp(); transport = mock(Transport.class); remoteConnectionManager = new RemoteConnectionManager( "remote-cluster", RemoteClusterCredentialsManager.EMPTY, new ClusterConnectionManager(Settings.EMPTY, transport, new ThreadContext(Settings.EMPTY)) ); doAnswer(invocationOnMock -> { ActionListener<Transport.Connection> listener = (ActionListener<Transport.Connection>) invocationOnMock.getArguments()[2]; listener.onResponse(new TestRemoteConnection((DiscoveryNode) invocationOnMock.getArguments()[0])); return null; }).when(transport).openConnection(any(DiscoveryNode.class), any(ConnectionProfile.class), any(ActionListener.class)); } public void testGetConnection() { DiscoveryNode node1 = DiscoveryNodeUtils.create("node-1", address); PlainActionFuture<Void> future1 = new PlainActionFuture<>(); remoteConnectionManager.connectToRemoteClusterNode(node1, validator, future1); assertTrue(future1.isDone()); // Add duplicate connect attempt to ensure that we do not get duplicate connections in the round robin remoteConnectionManager.connectToRemoteClusterNode(node1, validator, new PlainActionFuture<>()); DiscoveryNode node2 = DiscoveryNodeUtils.create("node-2", address); PlainActionFuture<Void> future2 = new PlainActionFuture<>(); remoteConnectionManager.connectToRemoteClusterNode(node2, validator, future2); assertTrue(future2.isDone()); assertEquals(node1, remoteConnectionManager.getConnection(node1).getNode()); assertEquals(node2, remoteConnectionManager.getConnection(node2).getNode()); DiscoveryNode node4 = DiscoveryNodeUtils.create("node-4", address); assertThat(remoteConnectionManager.getConnection(node4), instanceOf(ProxyConnection.class)); // Test round robin Set<String> proxyNodes = new HashSet<>(); proxyNodes.add(((ProxyConnection) remoteConnectionManager.getConnection(node4)).getConnection().getNode().getId()); proxyNodes.add(((ProxyConnection) remoteConnectionManager.getConnection(node4)).getConnection().getNode().getId()); assertThat(proxyNodes, containsInAnyOrder("node-1", "node-2")); // Test that the connection is cleared from the round robin list when it is closed remoteConnectionManager.getConnection(node1).close(); proxyNodes.clear(); proxyNodes.add(((ProxyConnection) remoteConnectionManager.getConnection(node4)).getConnection().getNode().getId()); proxyNodes.add(((ProxyConnection) remoteConnectionManager.getConnection(node4)).getConnection().getNode().getId()); assertThat(proxyNodes, containsInAnyOrder("node-2")); assertWarnings( "The remote cluster connection to [remote-cluster] is using the certificate-based security model. " + "The certificate-based security model is deprecated and will be removed in a future major version. " + "Migrate the remote cluster from the certificate-based to the API key-based security model." ); } public void testDisconnectedException() { assertEquals( "Unable to connect to [remote-cluster]", expectThrows(ConnectTransportException.class, remoteConnectionManager::getAnyRemoteConnection).getMessage() ); assertEquals( "Unable to connect to [remote-cluster]", expectThrows( ConnectTransportException.class, () -> remoteConnectionManager.getConnection(DiscoveryNodeUtils.create("node-1", address)) ).getMessage() ); } public void testResolveRemoteClusterAlias() throws ExecutionException, InterruptedException { DiscoveryNode remoteNode1 = DiscoveryNodeUtils.create("remote-node-1", address); PlainActionFuture<Void> future = new PlainActionFuture<>(); remoteConnectionManager.connectToRemoteClusterNode(remoteNode1, validator, future); assertTrue(future.isDone()); Transport.Connection remoteConnection = remoteConnectionManager.getConnection(remoteNode1); final String remoteClusterAlias = "remote-cluster"; assertThat(RemoteConnectionManager.resolveRemoteClusterAlias(remoteConnection).get(), equalTo(remoteClusterAlias)); Transport.Connection localConnection = mock(Transport.Connection.class); assertThat(RemoteConnectionManager.resolveRemoteClusterAlias(localConnection).isPresent(), equalTo(false)); DiscoveryNode remoteNode2 = DiscoveryNodeUtils.create("remote-node-2", address); Transport.Connection proxyConnection = remoteConnectionManager.getConnection(remoteNode2); assertThat(proxyConnection, instanceOf(ProxyConnection.class)); assertThat(RemoteConnectionManager.resolveRemoteClusterAlias(proxyConnection).get(), equalTo(remoteClusterAlias)); PlainActionFuture<Transport.Connection> future2 = new PlainActionFuture<>(); remoteConnectionManager.openConnection(remoteNode1, null, future2); assertThat(RemoteConnectionManager.resolveRemoteClusterAlias(future2.get()).get(), equalTo(remoteClusterAlias)); assertWarnings( "The remote cluster connection to [" + remoteClusterAlias + "] is using the certificate-based security model. " + "The certificate-based security model is deprecated and will be removed in a future major version. " + "Migrate the remote cluster from the certificate-based to the API key-based security model." ); } public void testRewriteHandshakeAction() throws IOException { final Transport.Connection connection = mock(Transport.Connection.class); final String clusterAlias = randomAlphaOfLengthBetween(3, 8); final RemoteClusterCredentialsManager credentialsResolver = mock(RemoteClusterCredentialsManager.class); when(credentialsResolver.resolveCredentials(clusterAlias)).thenReturn(new SecureString(randomAlphaOfLength(42))); final Transport.Connection wrappedConnection = RemoteConnectionManager.wrapConnectionWithRemoteClusterInfo( connection, clusterAlias, credentialsResolver ); final long requestId = randomLong(); final TransportRequest request = mock(TransportRequest.class); final TransportRequestOptions options = mock(TransportRequestOptions.class); wrappedConnection.sendRequest(requestId, TransportService.HANDSHAKE_ACTION_NAME, request, options); verify(connection).sendRequest(requestId, REMOTE_CLUSTER_HANDSHAKE_ACTION_NAME, request, options); final String anotherAction = randomValueOtherThan( TransportService.HANDSHAKE_ACTION_NAME, () -> randomFrom("cluster:", "indices:", "internal:", randomAlphaOfLengthBetween(3, 10) + ":") + Strings .collectionToDelimitedString(randomList(1, 5, () -> randomAlphaOfLengthBetween(3, 20)), "/") ); Mockito.reset(connection); wrappedConnection.sendRequest(requestId, anotherAction, request, options); verify(connection).sendRequest(requestId, anotherAction, request, options); } public void testWrapAndResolveConnectionRoundTrip() { final Transport.Connection connection = mock(Transport.Connection.class); final String clusterAlias = randomAlphaOfLengthBetween(3, 8); final RemoteClusterCredentialsManager credentialsResolver = mock(RemoteClusterCredentialsManager.class); final SecureString credentials = new SecureString(randomAlphaOfLength(42)); // second credential will never be resolved when(credentialsResolver.resolveCredentials(clusterAlias)).thenReturn(credentials, (SecureString) null); final Transport.Connection wrappedConnection = RemoteConnectionManager.wrapConnectionWithRemoteClusterInfo( connection, clusterAlias, credentialsResolver ); final Optional<RemoteConnectionManager.RemoteClusterAliasWithCredentials> actual = RemoteConnectionManager .resolveRemoteClusterAliasWithCredentials(wrappedConnection); assertThat(actual, isPresentWith(new RemoteConnectionManager.RemoteClusterAliasWithCredentials(clusterAlias, credentials))); } private static
RemoteConnectionManagerTests
java
google__guava
android/guava/src/com/google/common/io/TempFileCreator.java
{ "start": 11403, "end": 12103 }
class ____ extends TempFileCreator { private static final String MESSAGE = "Guava cannot securely create temporary files or directories under SDK versions before" + " Jelly Bean. You can create one yourself, either in the insecure default directory" + " or in a more secure directory, such as context.getCacheDir(). For more information," + " see the Javadoc for Files.createTempDir()."; @Override File createTempDir() { throw new IllegalStateException(MESSAGE); } @Override File createTempFile(String prefix) throws IOException { throw new IOException(MESSAGE); } } private TempFileCreator() {} }
ThrowingCreator
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalNumericMetricsAggregation.java
{ "start": 955, "end": 1175 }
class ____ extends InternalAggregation { private static final DocValueFormat DEFAULT_FORMAT = DocValueFormat.RAW; protected final DocValueFormat format; public abstract static
InternalNumericMetricsAggregation
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvProgramIdClass.java
{ "start": 730, "end": 1025 }
class ____ { @Id @JoinColumn(nullable=false) public Channel channel; @Id @JoinColumn(nullable=false) public Presenter presenter; @Temporal( TemporalType.TIME ) @Column(name="`time`") Date time; @Column( name = "TXT", table = "TV_PROGRAM_IDCLASS" ) public String text; }
TvProgramIdClass
java
grpc__grpc-java
xds/src/main/java/io/grpc/xds/client/LoadReportClient.java
{ "start": 5999, "end": 14034 }
class ____ implements EventHandler<LoadStatsResponse> { boolean initialResponseReceived; boolean closed; long intervalNano = -1; boolean reportAllClusters; List<String> clusterNames; // clusters to report loads for, if not report all. ScheduledHandle loadReportTimer; private final StreamingCall<LoadStatsRequest, LoadStatsResponse> call; LrsStream() { this.call = xdsTransport.createStreamingCall(method.getFullMethodName(), method.getRequestMarshaller(), method.getResponseMarshaller()); call.start(this); logger.log(XdsLogLevel.DEBUG, "Sending initial LRS request"); sendLoadStatsRequest(Collections.<ClusterStats>emptyList()); } @Override public void onReady() {} @Override public void onRecvMessage(LoadStatsResponse response) { syncContext.execute(new Runnable() { @Override public void run() { logger.log(XdsLogLevel.DEBUG, "Received LRS response:\n{0}", response); handleRpcResponse(response.getClustersList(), response.getSendAllClusters(), Durations.toNanos(response.getLoadReportingInterval())); call.startRecvMessage(); } }); } @Override public void onStatusReceived(final Status status) { syncContext.execute(new Runnable() { @Override public void run() { if (status.isOk()) { handleStreamClosed(Status.UNAVAILABLE.withDescription("Closed by server")); } else { handleStreamClosed(status); } } }); } void sendLoadStatsRequest(List<ClusterStats> clusterStatsList) { LoadStatsRequest.Builder requestBuilder = LoadStatsRequest.newBuilder().setNode(node.toEnvoyProtoNode()); for (ClusterStats stats : clusterStatsList) { requestBuilder.addClusterStats(buildClusterStats(stats)); } LoadStatsRequest request = requestBuilder.build(); call.sendMessage(request); logger.log(XdsLogLevel.DEBUG, "Sent LoadStatsRequest\n{0}", request); } void handleRpcResponse(List<String> clusters, boolean sendAllClusters, long loadReportIntervalNano) { if (closed) { return; } if (!initialResponseReceived) { logger.log(XdsLogLevel.DEBUG, "Initial LRS response received"); initialResponseReceived = true; } reportAllClusters = sendAllClusters; if (reportAllClusters) { logger.log(XdsLogLevel.INFO, "Report loads for all clusters"); } else { logger.log(XdsLogLevel.INFO, "Report loads for clusters: ", clusters); clusterNames = clusters; } intervalNano = loadReportIntervalNano; logger.log(XdsLogLevel.INFO, "Update load reporting interval to {0} ns", intervalNano); scheduleNextLoadReport(); } private void sendLoadReport() { if (closed) { return; } List<ClusterStats> clusterStatsList; if (reportAllClusters) { clusterStatsList = loadStatsManager.getAllClusterStatsReports(); } else { clusterStatsList = new ArrayList<>(); for (String name : clusterNames) { clusterStatsList.addAll(loadStatsManager.getClusterStatsReports(name)); } } sendLoadStatsRequest(clusterStatsList); scheduleNextLoadReport(); } private void scheduleNextLoadReport() { // Cancel pending load report and reschedule with updated load reporting interval. if (loadReportTimer != null && loadReportTimer.isPending()) { loadReportTimer.cancel(); loadReportTimer = null; } if (intervalNano > 0) { loadReportTimer = syncContext.schedule( new LoadReportingTask(this), intervalNano, TimeUnit.NANOSECONDS, timerService); } } private void handleStreamClosed(Status status) { checkArgument(!status.isOk(), "unexpected OK status"); if (closed) { return; } logger.log( XdsLogLevel.ERROR, "LRS stream closed with status {0}: {1}. Cause: {2}", status.getCode(), status.getDescription(), status.getCause()); closed = true; cleanUp(); if (initialResponseReceived || lrsRpcRetryPolicy == null) { // Reset the backoff sequence if balancer has sent the initial response, or backoff sequence // has never been initialized. lrsRpcRetryPolicy = backoffPolicyProvider.get(); } // The back-off policy determines the interval between consecutive RPC upstarts, thus the // actual delay may be smaller than the value from the back-off policy, or even negative, // depending on how much time was spent in the previous RPC. long delayNanos = lrsRpcRetryPolicy.nextBackoffNanos() - retryStopwatch.elapsed(TimeUnit.NANOSECONDS); logger.log(XdsLogLevel.INFO, "Retry LRS stream in {0} ns", delayNanos); if (delayNanos <= 0) { startLrsRpc(); } else { lrsRpcRetryTimer = syncContext.schedule( new LrsRpcRetryTask(), delayNanos, TimeUnit.NANOSECONDS, timerService); } } private void close(Exception error) { if (closed) { return; } closed = true; cleanUp(); call.sendError(error); } private void cleanUp() { if (loadReportTimer != null && loadReportTimer.isPending()) { loadReportTimer.cancel(); loadReportTimer = null; } if (lrsStream == this) { lrsStream = null; } } private io.envoyproxy.envoy.config.endpoint.v3.ClusterStats buildClusterStats( ClusterStats stats) { io.envoyproxy.envoy.config.endpoint.v3.ClusterStats.Builder builder = io.envoyproxy.envoy.config.endpoint.v3.ClusterStats.newBuilder() .setClusterName(stats.clusterName()); if (stats.clusterServiceName() != null) { builder.setClusterServiceName(stats.clusterServiceName()); } for (UpstreamLocalityStats upstreamLocalityStats : stats.upstreamLocalityStatsList()) { builder.addUpstreamLocalityStats( io.envoyproxy.envoy.config.endpoint.v3.UpstreamLocalityStats.newBuilder() .setLocality( io.envoyproxy.envoy.config.core.v3.Locality.newBuilder() .setRegion(upstreamLocalityStats.locality().region()) .setZone(upstreamLocalityStats.locality().zone()) .setSubZone(upstreamLocalityStats.locality().subZone())) .setTotalSuccessfulRequests(upstreamLocalityStats.totalSuccessfulRequests()) .setTotalErrorRequests(upstreamLocalityStats.totalErrorRequests()) .setTotalRequestsInProgress(upstreamLocalityStats.totalRequestsInProgress()) .setTotalIssuedRequests(upstreamLocalityStats.totalIssuedRequests()) .addAllLoadMetricStats( upstreamLocalityStats.loadMetricStatsMap().entrySet().stream().map( e -> io.envoyproxy.envoy.config.endpoint.v3.EndpointLoadMetricStats.newBuilder() .setMetricName(e.getKey()) .setNumRequestsFinishedWithMetric( e.getValue().numRequestsFinishedWithMetric()) .setTotalMetricValue(e.getValue().totalMetricValue()) .build()) .collect(Collectors.toList()))); } for (DroppedRequests droppedRequests : stats.droppedRequestsList()) { builder.addDroppedRequests( io.envoyproxy.envoy.config.endpoint.v3.ClusterStats.DroppedRequests.newBuilder() .setCategory(droppedRequests.category()) .setDroppedCount(droppedRequests.droppedCount())); } return builder .setTotalDroppedRequests(stats.totalDroppedRequests()) .setLoadReportInterval(Durations.fromNanos(stats.loadReportIntervalNano())) .build(); } } }
LrsStream
java
spring-projects__spring-security
config/src/integration-test/java/org/springframework/security/config/ldap/LdapPasswordComparisonAuthenticationManagerFactoryITests.java
{ "start": 2000, "end": 2819 }
class ____ { public final SpringTestContext spring = new SpringTestContext(this); @Autowired private MockMvc mockMvc; @Test public void authenticationManagerFactoryWhenCustomPasswordEncoderThenUsed() throws Exception { this.spring.register(CustomPasswordEncoderConfig.class).autowire(); this.mockMvc.perform(formLogin().user("bcrypt").password("password")) .andExpect(authenticated().withUsername("bcrypt")); } @Test public void authenticationManagerFactoryWhenCustomPasswordAttributeThenUsed() throws Exception { this.spring.register(CustomPasswordAttributeConfig.class).autowire(); this.mockMvc.perform(formLogin().user("bob").password("bob")).andExpect(authenticated().withUsername("bob")); } @Configuration @EnableWebSecurity static
LdapPasswordComparisonAuthenticationManagerFactoryITests
java
quarkusio__quarkus
extensions/smallrye-graphql-client/deployment/src/test/java/io/quarkus/smallrye/graphql/client/deployment/TypesafeGraphQLClientInjectionWithQuarkusConfigTest.java
{ "start": 715, "end": 2164 }
class ____ { static String url = "http://" + System.getProperty("quarkus.http.host", "localhost") + ":" + System.getProperty("quarkus.http.test-port", "8081") + "/graphql"; @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(TestingGraphQLApi.class, TestingGraphQLClientApi.class, Person.class, PersonDto.class) .addAsResource(new StringAsset("quarkus.smallrye-graphql-client.typesafeclient.url=" + url + "\n" + "quarkus.smallrye-graphql-client.typesafeclient.header.My-Header=My-Value"), "application.properties") .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")); @Inject TestingGraphQLClientApi client; @Test public void performQuery() { List<Person> people = client.people(); assertEquals("John", people.get(0).getFirstName()); assertEquals("Arthur", people.get(1).getFirstName()); } /** * Verify that configured HTTP headers are applied by the client. * We do this by asking the server side to read the header received from the client and send * its value back to the client. */ @Test public void checkHeaders() { assertEquals("My-Value", client.returnHeader("My-Header")); } }
TypesafeGraphQLClientInjectionWithQuarkusConfigTest
java
spring-projects__spring-boot
module/spring-boot-data-elasticsearch-test/src/dockerTest/java/org/springframework/boot/data/elasticsearch/test/autoconfigure/ExampleDocument.java
{ "start": 1025, "end": 1371 }
class ____ { @Id private @Nullable String id; private @Nullable String text; public @Nullable String getId() { return this.id; } public void setId(@Nullable String id) { this.id = id; } public @Nullable String getText() { return this.text; } public void setText(@Nullable String text) { this.text = text; } }
ExampleDocument
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/aroundconstruct/AroundConstructWithParameterChangeTest.java
{ "start": 1562, "end": 1891 }
class ____ { final String value; MyDependency() { this("default"); } MyDependency(String value) { this.value = value; } } @Target({ ElementType.TYPE, ElementType.CONSTRUCTOR }) @Retention(RetentionPolicy.RUNTIME) @InterceptorBinding @
MyDependency
java
google__auto
value/src/test/java/com/google/auto/value/extension/toprettystring/ToPrettyStringTest.java
{ "start": 24469, "end": 24722 }
class ____<A> { @Override public String toString() { throw new AssertionError(); } @ToPrettyString String toPrettyString() { return "custom\n@ToPrettyString\nmethod"; } } static
HasToPrettyString