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
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleAlterTablespaceItem.java
|
{
"start": 745,
"end": 809
}
|
interface ____ extends OracleSQLObject {
}
|
OracleAlterTablespaceItem
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/StringConcatToTextBlockTest.java
|
{
"start": 3018,
"end": 3259
}
|
class ____ {}
\""");
}
""")
.doTest();
}
@Test
public void noTrailing() {
refactoringHelper
.addInputLines(
"Test.java",
"""
|
NotAbstract
|
java
|
quarkusio__quarkus
|
extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java
|
{
"start": 2691,
"end": 91219
}
|
class ____ extends AbstractOidcAuthenticationMechanism {
public static final String SESSION_MAX_AGE_PARAM = "session-max-age";
static final String AMP = "&";
static final String QUESTION_MARK = "?";
static final String EQ = "=";
static final String COOKIE_DELIM = "|";
static final Pattern COOKIE_PATTERN = Pattern.compile("\\" + COOKIE_DELIM);
static final Uni<Void> VOID_UNI = Uni.createFrom().voidItem();
static final String NO_OIDC_COOKIES_AVAILABLE = "no_oidc_cookies";
static final String HTTP_SCHEME = "http";
private static final String INTERNAL_IDTOKEN_HEADER = "internal";
private static final Logger LOG = Logger.getLogger(CodeAuthenticationMechanism.class);
private final BlockingTaskRunner<String> createTokenStateRequestContext;
private final BlockingTaskRunner<AuthorizationCodeTokens> getTokenStateRequestContext;
private final SecureRandom secureRandom = new SecureRandom();
public CodeAuthenticationMechanism(BlockingSecurityExecutor blockingExecutor) {
this.createTokenStateRequestContext = new BlockingTaskRunner<>(blockingExecutor);
this.getTokenStateRequestContext = new BlockingTaskRunner<>(blockingExecutor);
}
public Uni<SecurityIdentity> authenticate(RoutingContext context,
IdentityProviderManager identityProviderManager, OidcTenantConfig oidcTenantConfig) {
final Map<String, Cookie> cookies = context.request().cookieMap();
final String sessionCookieValue = OidcUtils.getSessionCookie(context.data(), cookies, oidcTenantConfig);
// If the session is already established then try to re-authenticate
if (sessionCookieValue != null) {
LOG.debug("Session cookie is present, starting the reauthentication");
Uni<TenantConfigContext> resolvedContext = resolver.resolveContext(context);
return resolvedContext.onItem()
.transformToUni(new Function<TenantConfigContext, Uni<? extends SecurityIdentity>>() {
@Override
public Uni<SecurityIdentity> apply(TenantConfigContext tenantContext) {
return reAuthenticate(sessionCookieValue, context, identityProviderManager, tenantContext);
}
});
}
// Check if the state cookie is available
if (isStateCookieAvailable(cookies)) {
// Authorization code flow is in progress, however it is not necessarily tied to the current request.
if (ResponseMode.FORM_POST == oidcTenantConfig.authentication().responseMode().orElse(ResponseMode.QUERY)) {
if (OidcUtils.isFormUrlEncodedRequest(context)) {
return OidcUtils.getFormUrlEncodedData(context).onItem()
.transformToUni(new Function<MultiMap, Uni<? extends SecurityIdentity>>() {
@Override
public Uni<? extends SecurityIdentity> apply(MultiMap requestParams) {
return processRedirectFromOidc(context, oidcTenantConfig, identityProviderManager,
requestParams, cookies);
}
});
}
LOG.debug("HTTP POST and " + HttpHeaders.APPLICATION_X_WWW_FORM_URLENCODED.toString()
+ " content type must be used with the form_post response mode");
return Uni.createFrom().failure(new AuthenticationFailedException());
} else {
return processRedirectFromOidc(context, oidcTenantConfig, identityProviderManager,
context.queryParams(), cookies);
}
}
// return an empty identity - this will lead to a challenge redirecting the user to OpenId Connect provider
// unless it is detected it is a redirect from the provider in which case HTTP 401 will be returned.
context.put(NO_OIDC_COOKIES_AVAILABLE, Boolean.TRUE);
return Uni.createFrom().optional(Optional.empty());
}
private boolean isStateCookieAvailable(Map<String, Cookie> cookies) {
for (String name : cookies.keySet()) {
if (name.startsWith(OidcUtils.STATE_COOKIE_NAME)) {
return true;
}
}
return false;
}
private Uni<SecurityIdentity> processRedirectFromOidc(RoutingContext context, OidcTenantConfig oidcTenantConfig,
IdentityProviderManager identityProviderManager, MultiMap requestParams,
Map<String, Cookie> cookies) {
// At this point it has already been detected that some state cookie is available.
// If the state query parameter is not available or is available but no matching state cookie is found then if
// 1) the redirect path matches the current request path
// or
// 2) no parallel code flows from the same browser is allowed
// then 401 will be returned, otherwise a new authentication challenge will be created
//
// Once the state cookie matching the state query parameter has been found,
// the state cookie first part value must always match the state query value
List<String> stateQueryParam = requestParams.getAll(OidcConstants.CODE_FLOW_STATE);
if (stateQueryParam.size() != 1) {
return stateParamIsMissing(oidcTenantConfig, context, cookies, stateQueryParam.size() > 1);
}
String stateCookieNameSuffix = oidcTenantConfig.authentication().allowMultipleCodeFlows() ? "_" + stateQueryParam.get(0)
: "";
final Cookie stateCookie = context.request().getCookie(
getStateCookieName(oidcTenantConfig) + stateCookieNameSuffix);
if (stateCookie == null) {
return stateCookieIsMissing(oidcTenantConfig, context, cookies);
}
String[] parsedStateCookieValue = COOKIE_PATTERN.split(stateCookie.getValue());
OidcUtils.removeCookie(context, oidcTenantConfig, stateCookie.getName());
if (!parsedStateCookieValue[0].equals(stateQueryParam.get(0))) {
final String error = "State cookie value does not match the state query parameter value, "
+ "completing the code flow with HTTP status 401";
LOG.error(error);
return Uni.createFrom().failure(new AuthenticationCompletionException(error));
}
// State cookie is available, try to complete the code flow and start a new session
LOG.debug("State cookie is present, processing an expected redirect from the OIDC provider");
if (requestParams.contains(OidcConstants.CODE_FLOW_CODE)) {
LOG.debug("Authorization code is present, completing the code flow");
Uni<TenantConfigContext> resolvedContext = resolver.resolveContext(context);
return resolvedContext.onItem()
.transformToUni(new Function<TenantConfigContext, Uni<? extends SecurityIdentity>>() {
@Override
public Uni<SecurityIdentity> apply(TenantConfigContext tenantContext) {
return performCodeFlow(identityProviderManager, context, tenantContext, requestParams,
parsedStateCookieValue);
}
});
} else if (requestParams.contains(OidcConstants.CODE_FLOW_ERROR)) {
OidcUtils.removeCookie(context, oidcTenantConfig, stateCookie.getName());
String error = requestParams.get(OidcConstants.CODE_FLOW_ERROR);
String errorDescription = requestParams.get(OidcConstants.CODE_FLOW_ERROR_DESCRIPTION);
LOG.debugf("Authentication has failed, error: %s, description: %s", error, errorDescription);
if (oidcTenantConfig.authentication().errorPath().isPresent()) {
Uni<TenantConfigContext> resolvedContext = resolver.resolveContext(context);
return resolvedContext.onItem()
.transformToUni(new Function<TenantConfigContext, Uni<? extends SecurityIdentity>>() {
@Override
public Uni<SecurityIdentity> apply(TenantConfigContext tenantContext) {
URI absoluteUri = URI.create(context.request().absoluteURI());
String userQuery = null;
// This is an original redirect from IDP, check if the original request path and query need to be restored
CodeAuthenticationStateBean stateBean = getCodeAuthenticationBean(parsedStateCookieValue,
tenantContext);
if (stateBean != null && stateBean.getRestorePath() != null) {
String restorePath = stateBean.getRestorePath();
int userQueryIndex = restorePath.indexOf("?");
if (userQueryIndex >= 0 && userQueryIndex + 1 < restorePath.length()) {
userQuery = restorePath.substring(userQueryIndex + 1);
}
}
StringBuilder errorUri = new StringBuilder(buildUri(context,
isForceHttps(oidcTenantConfig),
absoluteUri.getAuthority(),
oidcTenantConfig.authentication().errorPath().get()));
errorUri.append('?')
.append(getRequestParametersAsQuery(absoluteUri, requestParams, oidcTenantConfig));
if (userQuery != null) {
errorUri.append('&').append(userQuery);
}
String finalErrorUri = errorUri.toString();
LOG.debugf("Error URI: %s", finalErrorUri);
return Uni.createFrom().failure(new AuthenticationRedirectException(
filterRedirect(context, tenantContext, finalErrorUri, Redirect.Location.ERROR_PAGE)));
}
});
} else {
final String errorMessage = """
Authorization code flow has failed, error code: %s, error description: %s.
Error handler path is not configured. Have a public JAX-RS resource listening
on a path such as '/error' and point to it with 'quarkus.oidc.authentication.error-path=/error'.
Completing the flow with HTTP status 401.
""".formatted(error, errorDescription == null ? "" : errorDescription);
LOG.error(errorMessage);
return Uni.createFrom().failure(new AuthenticationCompletionException(errorMessage));
}
} else {
final String error = "State cookie is present but neither 'code' nor 'error' query parameter is returned";
LOG.error(error);
return Uni.createFrom().failure(new AuthenticationCompletionException(error));
}
}
private static String filterRedirect(RoutingContext context,
TenantConfigContext tenantContext, String redirectUri, Redirect.Location location) {
List<OidcRedirectFilter> redirectFilters = tenantContext.getOidcRedirectFilters(location);
if (!redirectFilters.isEmpty()) {
OidcRedirectContext redirectContext = new OidcRedirectContext(context, tenantContext.getOidcTenantConfig(),
redirectUri, MultiMap.caseInsensitiveMultiMap());
for (OidcRedirectFilter filter : redirectFilters) {
filter.filter(redirectContext);
}
MultiMap queries = redirectContext.additionalQueryParams();
if (!queries.isEmpty()) {
String encoded = OidcCommonUtils.encodeForm(new io.vertx.mutiny.core.MultiMap(queries)).toString();
String sep = redirectUri.lastIndexOf("?") > 0 ? AMP : QUESTION_MARK;
redirectUri += (sep + encoded);
}
}
return redirectUri;
}
private Uni<SecurityIdentity> stateParamIsMissing(OidcTenantConfig oidcTenantConfig, RoutingContext context,
Map<String, Cookie> cookies, boolean multipleStateQueryParams) {
if (multipleStateQueryParams) {
final String error = "State query parameter can not be multi-valued if the state cookie is present";
LOG.error(error);
removeStateCookies(oidcTenantConfig, context, cookies);
return Uni.createFrom().failure(new AuthenticationCompletionException(error));
}
LOG.debug("State parameter can not be empty if the state cookie is present");
return stateCookieIsNotMatched(oidcTenantConfig, context, cookies);
}
private Uni<SecurityIdentity> stateCookieIsMissing(OidcTenantConfig oidcTenantConfig, RoutingContext context,
Map<String, Cookie> cookies) {
LOG.debug("Matching state cookie is not found");
return stateCookieIsNotMatched(oidcTenantConfig, context, cookies);
}
private Uni<SecurityIdentity> stateCookieIsNotMatched(OidcTenantConfig oidcTenantConfig, RoutingContext context,
Map<String, Cookie> cookies) {
if (!oidcTenantConfig.authentication().allowMultipleCodeFlows()
|| context.request().path().equals(getRedirectPath(oidcTenantConfig, context))) {
if (oidcTenantConfig.authentication().failOnMissingStateParam()) {
removeStateCookies(oidcTenantConfig, context, cookies);
final String error = "State query parameter is missing";
LOG.error(error);
return Uni.createFrom().failure(new AuthenticationCompletionException(error));
}
if (!oidcTenantConfig.authentication().allowMultipleCodeFlows()) {
removeStateCookies(oidcTenantConfig, context, cookies);
}
}
context.put(NO_OIDC_COOKIES_AVAILABLE, Boolean.TRUE);
return Uni.createFrom().optional(Optional.empty());
}
private void removeStateCookies(OidcTenantConfig oidcTenantConfig, RoutingContext context, Map<String, Cookie> cookies) {
for (String name : cookies.keySet()) {
if (name.startsWith(OidcUtils.STATE_COOKIE_NAME)) {
OidcUtils.removeCookie(context, oidcTenantConfig, name);
}
}
}
private String getRequestParametersAsQuery(URI requestUri, MultiMap requestParams, OidcTenantConfig oidcConfig) {
if (ResponseMode.FORM_POST == oidcConfig.authentication().responseMode().orElse(ResponseMode.QUERY)) {
return OidcCommonUtils.encodeForm(new io.vertx.mutiny.core.MultiMap(requestParams)).toString();
} else {
return requestUri.getRawQuery();
}
}
private Uni<SecurityIdentity> reAuthenticate(String sessionCookie,
RoutingContext context,
IdentityProviderManager identityProviderManager,
TenantConfigContext configContext) {
context.put(TenantConfigContext.class.getName(), configContext);
return resolver.getTokenStateManager().getTokens(context, configContext.oidcConfig(),
sessionCookie, getTokenStateRequestContext)
.onFailure(Throwable.class)
.recoverWithUni(
new Function<Throwable, Uni<? extends AuthorizationCodeTokens>>() {
@Override
public Uni<AuthorizationCodeTokens> apply(Throwable t) {
Throwable failure = t instanceof AuthenticationFailedException ? t
: new AuthenticationFailedException(t);
return removeSessionCookie(context, configContext.oidcConfig())
.replaceWith(Uni.createFrom().failure(failure));
}
})
.chain(new Function<AuthorizationCodeTokens, Uni<? extends SecurityIdentity>>() {
@Override
public Uni<? extends SecurityIdentity> apply(AuthorizationCodeTokens tokens) {
AuthorizationCodeTokens decryptedtokens = decryptTokens(context, configContext.oidcConfig(), tokens);
context.put(OidcConstants.ACCESS_TOKEN_VALUE, decryptedtokens.getAccessToken());
context.put(AuthorizationCodeTokens.class.getName(), decryptedtokens);
// Default token state manager may have encrypted ID token when it was saved in a cookie
final String currentIdToken = decryptIdToken(configContext, decryptedtokens.getIdToken());
return authenticate(identityProviderManager, context,
new IdTokenCredential(currentIdToken,
isInternalIdToken(currentIdToken, configContext)))
.call(new LogoutCall(context, configContext, decryptedtokens.getIdToken())).onFailure()
.recoverWithUni(new Function<Throwable, Uni<? extends SecurityIdentity>>() {
@Override
public Uni<? extends SecurityIdentity> apply(Throwable t) {
if (t instanceof AuthenticationRedirectException) {
LOG.debug("Redirecting after the reauthentication");
return Uni.createFrom().failure((AuthenticationRedirectException) t);
}
if (t instanceof LogoutException) {
LOG.debugf("User has been logged out, authentication challenge is required");
return Uni.createFrom()
.failure(new AuthenticationFailedException(t, tokenMap(currentIdToken)));
}
if (!(t instanceof TokenAutoRefreshException)) {
boolean expired = (t.getCause() instanceof InvalidJwtException)
&& ((InvalidJwtException) t.getCause())
.hasErrorCode(ErrorCodes.EXPIRED);
if (!expired) {
Throwable failure = null;
boolean unresolvedKey = t.getCause() instanceof InvalidJwtException
&& (t.getCause().getCause() instanceof UnresolvableKeyException);
if (unresolvedKey
&& !configContext.oidcConfig().authentication().failOnUnresolvedKid()
&& OidcUtils.isJwtTokenExpired(currentIdToken)) {
// It can happen in multi-tab applications where a user login causes a JWK set refresh
// due to the key rotation, discarding old keys, and the old tab still keeps the session
// whose signature can only be verified with the now discarded key.
LOG.debugf(
"Session can not be verified due to an unresolved key exception, reauthentication is required");
// Redirect the user to the OIDC provider to re-authenticate
failure = new AuthenticationFailedException(tokenMap(currentIdToken));
} else {
// Failures such as the signature verification failures require 401 status
String error = logAuthenticationError(context, t);
failure = t.getCause() instanceof AuthenticationCompletionException
? t.getCause()
: new AuthenticationCompletionException(error, t.getCause());
}
return removeSessionCookie(context, configContext.oidcConfig())
.replaceWith(Uni.createFrom().failure(failure));
}
// Token has expired, try to refresh
if (isRpInitiatedLogout(context, configContext)) {
LOG.debug("Session has expired, performing an RP initiated logout");
fireEvent(SecurityEvent.Type.OIDC_LOGOUT_RP_INITIATED_SESSION_EXPIRED,
Map.of(SecurityEvent.SESSION_TOKENS_PROPERTY, decryptedtokens));
return Uni.createFrom().item((SecurityIdentity) null)
.call(() -> buildLogoutRedirectUriUni(context, configContext,
currentIdToken));
}
if (!configContext.oidcConfig().token().refreshExpired()) {
LOG.debug(
"Token has expired, token refresh is not allowed, redirecting to re-authenticate");
return refreshIsNotPossible(context, configContext, t);
}
if (decryptedtokens.getRefreshToken() == null) {
LOG.debug(
"Token has expired, token refresh is not possible because the refresh token is null");
return refreshIsNotPossible(context, configContext, t);
}
if (OidcUtils.isJwtTokenExpired(decryptedtokens.getRefreshToken())) {
LOG.debug(
"Token has expired, token refresh is not possible because the refresh token has expired");
return refreshIsNotPossible(context, configContext, t);
}
LOG.debug("Token has expired, trying to refresh it");
return refreshSecurityIdentity(configContext,
currentIdToken,
decryptedtokens.getRefreshToken(),
context,
identityProviderManager, false, null);
} else {
// Token auto-refresh, security identity is still valid
SecurityIdentity currentIdentity = ((TokenAutoRefreshException) t)
.getSecurityIdentity();
if (isLogout(context, configContext, currentIdentity)) {
// No need to refresh the token since the user is requesting a logout
return Uni.createFrom().item(currentIdentity).call(
new LogoutCall(context, configContext, decryptedtokens.getIdToken()));
}
// Token has nearly expired, try to refresh
if (decryptedtokens.getRefreshToken() == null) {
LOG.debug(
"Token auto-refresh is required but is not possible because the refresh token is null");
return autoRefreshIsNotPossible(context, configContext, currentIdentity, t);
}
if (OidcUtils.isJwtTokenExpired(decryptedtokens.getRefreshToken())) {
LOG.debug(
"Token auto-refresh is required but is not possible because the refresh token has expired");
return autoRefreshIsNotPossible(context, configContext, currentIdentity, t);
}
LOG.debug("Token auto-refresh is starting");
return refreshSecurityIdentity(configContext,
currentIdToken,
decryptedtokens.getRefreshToken(),
context,
identityProviderManager, true,
currentIdentity);
}
}
});
}
});
}
private Uni<SecurityIdentity> refreshIsNotPossible(RoutingContext context, TenantConfigContext configContext,
Throwable t) {
if (configContext.oidcConfig().authentication().sessionExpiredPath().isPresent()) {
return redirectToSessionExpiredPage(context, configContext);
}
return Uni.createFrom()
.failure(new AuthenticationFailedException(t.getCause()));
}
private Uni<SecurityIdentity> autoRefreshIsNotPossible(RoutingContext context, TenantConfigContext configContext,
SecurityIdentity currentIdentity, Throwable t) {
// Auto-refreshing is not possible, just continue with the current security identity
if (currentIdentity != null) {
return Uni.createFrom().item(currentIdentity);
} else {
return refreshIsNotPossible(context, configContext, t);
}
}
private Uni<SecurityIdentity> redirectToSessionExpiredPage(RoutingContext context, TenantConfigContext configContext) {
URI absoluteUri = URI.create(context.request().absoluteURI());
StringBuilder sessionExpired = new StringBuilder(buildUri(context,
isForceHttps(configContext.oidcConfig()),
absoluteUri.getAuthority(),
configContext.oidcConfig().authentication().sessionExpiredPath().get()));
String sessionExpiredUri = sessionExpired.toString();
LOG.debugf("Session Expired URI: %s", sessionExpiredUri);
return removeSessionCookie(context, configContext.oidcConfig())
.chain(() -> Uni.createFrom().failure(new AuthenticationRedirectException(
filterRedirect(context, configContext, sessionExpiredUri, Redirect.Location.SESSION_EXPIRED_PAGE))));
}
private boolean isLogout(RoutingContext context, TenantConfigContext configContext, SecurityIdentity identity) {
return isRpInitiatedLogout(context, configContext) || isBackChannelLogoutPending(configContext, identity)
|| isFrontChannelLogoutValid(context, configContext, identity);
}
private boolean isBackChannelLogoutPending(TenantConfigContext configContext, SecurityIdentity identity) {
if (configContext.oidcConfig().logout().backchannel().path().isEmpty()) {
return false;
}
BackChannelLogoutTokenCache tokens = resolver.getBackChannelLogoutTokens()
.get(configContext.oidcConfig().tenantId().get());
if (tokens != null) {
JsonObject idTokenJson = OidcCommonUtils.decodeJwtContent(((JsonWebToken) (identity.getPrincipal())).getRawToken());
String logoutTokenKeyValue = idTokenJson
.getString(configContext.oidcConfig().logout().backchannel().logoutTokenKey());
return tokens.containsTokenVerification(logoutTokenKeyValue);
}
return false;
}
private boolean isBackChannelLogoutPendingAndValid(TenantConfigContext configContext, SecurityIdentity identity) {
if (configContext.oidcConfig().logout().backchannel().path().isEmpty()) {
return false;
}
BackChannelLogoutTokenCache tokens = resolver.getBackChannelLogoutTokens()
.get(configContext.oidcConfig().tenantId().get());
if (tokens != null) {
JsonObject idTokenJson = OidcCommonUtils.decodeJwtContent(((JsonWebToken) (identity.getPrincipal())).getRawToken());
String logoutTokenKeyValue = idTokenJson
.getString(configContext.oidcConfig().logout().backchannel().logoutTokenKey());
TokenVerificationResult backChannelLogoutTokenResult = tokens.removeTokenVerification(logoutTokenKeyValue);
if (backChannelLogoutTokenResult == null) {
return false;
}
String idTokenIss = idTokenJson.getString(Claims.iss.name());
String logoutTokenIss = backChannelLogoutTokenResult.localVerificationResult.getString(Claims.iss.name());
if (logoutTokenIss != null && !logoutTokenIss.equals(idTokenIss)) {
LOG.debugf("Logout token issuer does not match the ID token issuer");
return false;
}
String idTokenSub = idTokenJson.getString(Claims.sub.name());
String logoutTokenSub = backChannelLogoutTokenResult.localVerificationResult.getString(Claims.sub.name());
if (logoutTokenSub != null && idTokenSub != null && !logoutTokenSub.equals(idTokenSub)) {
LOG.debugf("Logout token subject does not match the ID token subject");
return false;
}
String idTokenSid = idTokenJson.getString(OidcConstants.ID_TOKEN_SID_CLAIM);
String logoutTokenSid = backChannelLogoutTokenResult.localVerificationResult
.getString(OidcConstants.BACK_CHANNEL_LOGOUT_SID_CLAIM);
if (logoutTokenSid != null && idTokenSid != null && !logoutTokenSid.equals(idTokenSid)) {
LOG.debugf("Logout token session id does not match the ID token session id");
return false;
}
LOG.debugf("Backchannel logout request for the tenant %s has been completed",
configContext.oidcConfig().tenantId().get());
fireEvent(SecurityEvent.Type.OIDC_BACKCHANNEL_LOGOUT_COMPLETED, identity);
return true;
}
return false;
}
private boolean isFrontChannelLogoutValid(RoutingContext context, TenantConfigContext configContext,
SecurityIdentity identity) {
if (isEqualToRequestPath(configContext.oidcConfig().logout().frontchannel().path(), context, configContext)) {
JsonObject idTokenJson = OidcCommonUtils.decodeJwtContent(((JsonWebToken) (identity.getPrincipal())).getRawToken());
String idTokenIss = idTokenJson.getString(Claims.iss.name());
List<String> frontChannelIss = context.queryParam(Claims.iss.name());
if (frontChannelIss != null && frontChannelIss.size() == 1 && !frontChannelIss.get(0).equals(idTokenIss)) {
LOG.debugf("Frontchannel issuer parameter does not match the ID token issuer");
return false;
}
String idTokenSid = idTokenJson.getString(OidcConstants.ID_TOKEN_SID_CLAIM);
List<String> frontChannelSid = context.queryParam(OidcConstants.FRONT_CHANNEL_LOGOUT_SID_PARAM);
if (frontChannelSid != null && frontChannelSid.size() == 1 && !frontChannelSid.get(0).equals(idTokenSid)) {
LOG.debugf("Frontchannel session id parameter does not match the ID token session id");
return false;
}
LOG.debugf("Frontchannel logout request for the tenant %s has been completed",
configContext.oidcConfig().tenantId().get());
fireEvent(SecurityEvent.Type.OIDC_FRONTCHANNEL_LOGOUT_COMPLETED, identity);
return true;
}
return false;
}
private boolean isInternalIdToken(String idToken, TenantConfigContext configContext) {
if (!configContext.oidcConfig().authentication().idTokenRequired().orElse(true)) {
JsonObject headers = OidcUtils.decodeJwtHeaders(idToken);
if (headers != null) {
return headers.getBoolean(INTERNAL_IDTOKEN_HEADER, false);
}
}
return false;
}
private boolean isIdTokenRequired(TenantConfigContext configContext) {
return configContext.oidcConfig().authentication().idTokenRequired().orElse(true);
}
private boolean isJavaScript(RoutingContext context) {
JavaScriptRequestChecker checker = resolver.getJavaScriptRequestChecker();
if (checker != null) {
return checker.isJavaScriptRequest(context);
}
String value = context.request().getHeader("X-Requested-With");
return "JavaScript".equals(value) || "XMLHttpRequest".equals(value);
}
// This test determines if the default behavior of returning a 302 should go forward
// The only case that shouldn't return a 302 is if the call is a XHR and the
// user has set the auto direct application property to false indicating that
// the client application will manually handle the redirect to account for SPA behavior
private boolean shouldAutoRedirect(TenantConfigContext configContext, RoutingContext context) {
return isJavaScript(context) ? configContext.oidcConfig().authentication().javaScriptAutoRedirect() : true;
}
public Uni<ChallengeData> getChallenge(RoutingContext context) {
Uni<TenantConfigContext> tenantContext = resolver.resolveContext(context);
return tenantContext.onItem().transformToUni(new Function<TenantConfigContext, Uni<? extends ChallengeData>>() {
@Override
public Uni<ChallengeData> apply(TenantConfigContext tenantContext) {
return getChallengeInternal(context, tenantContext);
}
});
}
public Uni<ChallengeData> getChallengeInternal(RoutingContext context, TenantConfigContext configContext) {
LOG.debugf("Starting an authentication challenge for tenant %s.", configContext.oidcConfig().tenantId().get());
if (configContext.oidcConfig().clientName().isPresent()) {
LOG.debugf(" Client name: %s", configContext.oidcConfig().clientName().get());
}
OidcTenantConfig sessionCookieConfig = configContext.oidcConfig();
String sessionTenantIdSetByCookie = context.get(OidcUtils.TENANT_ID_SET_BY_SESSION_COOKIE);
if (sessionTenantIdSetByCookie != null
&& !sessionTenantIdSetByCookie.equals(sessionCookieConfig.tenantId().get())) {
// New tenant id has been chosen during the tenant resolution process
// Get the already resolved configuration, avoiding calling the tenant resolvers
OidcTenantConfig previousTenantConfig = resolver.getResolvedConfig(sessionTenantIdSetByCookie);
if (previousTenantConfig != null) {
sessionCookieConfig = previousTenantConfig;
LOG.debugf("Removing the session cookie for the previous tenant id: %s", sessionTenantIdSetByCookie);
OidcUtils.getSessionCookie(context, sessionCookieConfig);
}
}
return removeSessionCookie(context, sessionCookieConfig)
.chain(new Function<Void, Uni<? extends ChallengeData>>() {
@Override
public Uni<ChallengeData> apply(Void t) {
if (context.get(NO_OIDC_COOKIES_AVAILABLE) != null
&& isRedirectFromProvider(context, configContext)) {
LOG.warn(
"The state cookie is missing after the redirect from OpenId Connect Provider, authentication has failed");
return Uni.createFrom().item(new ChallengeData(401, "WWW-Authenticate", "OIDC"));
}
if (!shouldAutoRedirect(configContext, context)) {
// If the client (usually an SPA) wants to handle the redirect manually, then
// return status code 499 and WWW-Authenticate header with the 'OIDC' value.
return Uni.createFrom().item(new ChallengeData(499, "WWW-Authenticate", "OIDC"));
}
StringBuilder codeFlowParams = new StringBuilder(168); // experimentally determined to be a good size for preventing resizing and not wasting space
// response_type
codeFlowParams.append(OidcConstants.CODE_FLOW_RESPONSE_TYPE).append(EQ)
.append(OidcConstants.CODE_FLOW_CODE);
// response_mode
if (ResponseMode.FORM_POST == configContext.oidcConfig().authentication().responseMode()
.orElse(ResponseMode.QUERY)) {
codeFlowParams.append(AMP).append(OidcConstants.CODE_FLOW_RESPONSE_MODE).append(EQ)
.append(configContext.oidcConfig().authentication().responseMode().get().toString()
.toLowerCase());
}
// client_id
codeFlowParams.append(AMP).append(OidcConstants.CLIENT_ID).append(EQ)
.append(OidcCommonUtils.urlEncode(configContext.oidcConfig().clientId().get()));
// scope
codeFlowParams.append(AMP).append(OidcConstants.TOKEN_SCOPE).append(EQ)
.append(OidcUtils.encodeScopes(configContext.oidcConfig()));
MultiMap requestQueryParams = null;
if (!configContext.oidcConfig().authentication().forwardParams().isEmpty()) {
requestQueryParams = context.queryParams();
for (String forwardedParam : configContext.oidcConfig().authentication().forwardParams().get()) {
if (requestQueryParams.contains(forwardedParam)) {
for (String requestQueryParamValue : requestQueryParams.getAll(forwardedParam))
codeFlowParams.append(AMP).append(forwardedParam).append(EQ)
.append(OidcCommonUtils.urlEncode(requestQueryParamValue));
requestQueryParams.remove(forwardedParam);
}
}
}
// redirect_uri
String redirectPath = getRedirectPath(configContext.oidcConfig(), context);
String redirectUriParam = buildUri(context, isForceHttps(configContext.oidcConfig()), redirectPath);
LOG.debugf("Authentication request redirect_uri parameter: %s", redirectUriParam);
codeFlowParams.append(AMP).append(OidcConstants.CODE_FLOW_REDIRECT_URI).append(EQ)
.append(OidcCommonUtils.urlEncode(redirectUriParam));
// pkce
PkceStateBean pkceStateBean = createPkceStateBean(configContext);
// state
String nonce = configContext.oidcConfig().authentication().nonceRequired()
? UUID.randomUUID().toString()
: null;
codeFlowParams.append(AMP).append(OidcConstants.CODE_FLOW_STATE).append(EQ)
.append(generateCodeFlowState(context, configContext, redirectPath, requestQueryParams,
(pkceStateBean != null ? pkceStateBean.getCodeVerifier() : null), nonce));
if (pkceStateBean != null) {
codeFlowParams
.append(AMP).append(OidcConstants.PKCE_CODE_CHALLENGE).append(EQ)
.append(pkceStateBean.getCodeChallenge());
codeFlowParams
.append(AMP).append(OidcConstants.PKCE_CODE_CHALLENGE_METHOD).append(EQ)
.append(OidcConstants.PKCE_CODE_CHALLENGE_S256);
}
if (nonce != null) {
codeFlowParams.append(AMP).append(OidcConstants.NONCE).append(EQ).append(nonce);
}
// extra redirect parameters, see https://openid.net/specs/openid-connect-core-1_0.html#AuthRequests
addExtraParamsToUri(codeFlowParams, configContext.oidcConfig().authentication().extraParams());
String authorizationURL = configContext.provider().getMetadata().getAuthorizationUri() + "?"
+ codeFlowParams;
authorizationURL = filterRedirect(context, configContext, authorizationURL,
Redirect.Location.OIDC_AUTHORIZATION);
LOG.debugf("Code flow redirect to: %s", authorizationURL);
return Uni.createFrom().item(new ChallengeData(HttpResponseStatus.FOUND.code(), HttpHeaders.LOCATION,
authorizationURL));
}
});
}
private boolean isRedirectFromProvider(RoutingContext context, TenantConfigContext configContext) {
// The referrer check is the best effort at attempting to avoid the redirect loop after
// the user has authenticated at the OpenId Connect Provider page but the state cookie has been lost
// during the redirect back to Quarkus.
String referer = context.request().getHeader(HttpHeaders.REFERER);
return referer != null && referer.startsWith(configContext.provider().getMetadata().getAuthorizationUri());
}
private PkceStateBean createPkceStateBean(TenantConfigContext configContext) {
if (configContext.oidcConfig().authentication().pkceRequired().orElse(false)) {
PkceStateBean bean = new PkceStateBean();
Encoder encoder = Base64.getUrlEncoder().withoutPadding();
// code verifier
byte[] codeVerifierBytes = new byte[32];
secureRandom.nextBytes(codeVerifierBytes);
String codeVerifier = encoder.encodeToString(codeVerifierBytes);
bean.setCodeVerifier(codeVerifier);
// code challenge
try {
byte[] codeChallengeBytes = OidcUtils.getSha256Digest(codeVerifier.getBytes(StandardCharsets.ISO_8859_1));
String codeChallenge = encoder.encodeToString(codeChallengeBytes);
bean.setCodeChallenge(codeChallenge);
} catch (Exception ex) {
LOG.errorf("Code challenge creation failure: %s", ex.getMessage());
throw new AuthenticationCompletionException(ex);
}
return bean;
}
return null;
}
private Uni<SecurityIdentity> performCodeFlow(IdentityProviderManager identityProviderManager,
RoutingContext context, TenantConfigContext configContext, MultiMap requestParams,
String[] parsedStateCookieValue) {
String userPath = null;
String userQuery = null;
// This is an original redirect from IDP, check if the original request path and query need to be restored
CodeAuthenticationStateBean stateBean = getCodeAuthenticationBean(parsedStateCookieValue, configContext);
if (stateBean != null && stateBean.getRestorePath() != null) {
String restorePath = stateBean.getRestorePath();
int userQueryIndex = restorePath.indexOf("?");
if (userQueryIndex >= 0) {
userPath = isRestorePath(configContext.oidcConfig().authentication()) ? restorePath.substring(0, userQueryIndex)
: null;
if (userQueryIndex + 1 < restorePath.length()) {
userQuery = restorePath.substring(userQueryIndex + 1);
}
} else {
userPath = restorePath;
}
}
final String finalUserPath = userPath;
final String finalUserQuery = userQuery;
final String code = requestParams.get(OidcConstants.CODE_FLOW_CODE);
LOG.debug("Exchanging the authorization code for the tokens");
Uni<AuthorizationCodeTokens> codeFlowTokensUni = getCodeFlowTokensUni(context, configContext, code,
stateBean != null ? stateBean.getCodeVerifier() : null);
return codeFlowTokensUni
.onItemOrFailure()
.transformToUni(new BiFunction<AuthorizationCodeTokens, Throwable, Uni<? extends SecurityIdentity>>() {
@Override
public Uni<SecurityIdentity> apply(final AuthorizationCodeTokens tokens, final Throwable tOuter) {
if (tOuter != null) {
LOG.errorf("Exception during the code to token exchange: %s", tOuter.getMessage());
return Uni.createFrom().failure(new AuthenticationCompletionException(tOuter));
}
final boolean internalIdToken;
if (tokens.getIdToken() == null) {
if (isIdTokenRequired(configContext)) {
LOG.errorf("ID token is not available in the authorization code grant response");
return Uni.createFrom().failure(new AuthenticationCompletionException());
} else if (tokens.getAccessToken() != null) {
tokens.setIdToken(generateInternalIdToken(configContext, null, null,
tokens.getAccessTokenExpiresIn()));
internalIdToken = true;
} else {
LOG.errorf(
"Neither ID token nor access tokens are available in the authorization code grant response."
+ " Please check logs for more details, enable debug log level if no details are visible.");
return Uni.createFrom().failure(new AuthenticationCompletionException());
}
} else {
if (!prepareNonceForVerification(context, configContext.oidcConfig(), stateBean)) {
return Uni.createFrom().failure(new AuthenticationCompletionException());
}
internalIdToken = false;
}
context.put(NEW_AUTHENTICATION, Boolean.TRUE);
context.put(OidcConstants.ACCESS_TOKEN_VALUE, tokens.getAccessToken());
context.put(AuthorizationCodeTokens.class.getName(), tokens);
// Default token state manager may have encrypted ID token
final String idToken = decryptIdToken(configContext, tokens.getIdToken());
LOG.debug("Authorization code has been exchanged, verifying ID token");
return authenticate(identityProviderManager, context,
new IdTokenCredential(idToken, internalIdToken))
.call(new Function<SecurityIdentity, Uni<?>>() {
@Override
public Uni<Void> apply(SecurityIdentity identity) {
if (internalIdToken
&& OidcUtils.cacheUserInfoInIdToken(resolver, configContext.oidcConfig())) {
tokens.setIdToken(generateInternalIdToken(configContext,
identity.getAttribute(OidcUtils.USER_INFO_ATTRIBUTE), null,
tokens.getAccessTokenExpiresIn()));
}
return processSuccessfulAuthentication(context, configContext,
tokens, idToken, identity);
}
})
.map(new Function<SecurityIdentity, SecurityIdentity>() {
@Override
public SecurityIdentity apply(SecurityIdentity identity) {
boolean removeRedirectParams = configContext.oidcConfig().authentication()
.removeRedirectParameters();
if (removeRedirectParams || finalUserPath != null
|| finalUserQuery != null) {
URI absoluteUri = URI.create(context.request().absoluteURI());
StringBuilder finalUriWithoutQuery = new StringBuilder(buildUri(context,
isForceHttps(configContext.oidcConfig()),
absoluteUri.getAuthority(),
(finalUserPath != null ? finalUserPath
: absoluteUri.getRawPath())));
if (!removeRedirectParams) {
finalUriWithoutQuery.append('?')
.append(getRequestParametersAsQuery(absoluteUri, requestParams,
configContext.oidcConfig()));
}
if (finalUserQuery != null) {
finalUriWithoutQuery.append(!removeRedirectParams ? "&" : "?");
finalUriWithoutQuery.append(finalUserQuery);
}
String finalRedirectUri = finalUriWithoutQuery.toString();
LOG.debugf("Removing code flow redirect parameters, final redirect URI: %s",
finalRedirectUri);
throw new AuthenticationRedirectException(
filterRedirect(context, configContext, finalRedirectUri,
Redirect.Location.LOCAL_ENDPOINT_CALLBACK));
} else {
return identity;
}
}
}).onFailure().transform(new Function<Throwable, Throwable>() {
@Override
public Throwable apply(Throwable tInner) {
if (tInner instanceof AuthenticationRedirectException) {
LOG.debugf("Starting the final redirect");
return tInner;
}
final String errorMessage = logAuthenticationError(context, tInner);
return new AuthenticationCompletionException(errorMessage, tInner);
}
});
}
});
}
private static String logAuthenticationError(RoutingContext context, Throwable t) {
String errorMessage = null;
final boolean accessTokenFailure = context.get(OidcUtils.CODE_ACCESS_TOKEN_FAILURE) != null;
if (accessTokenFailure) {
errorMessage = """
Access token verification has failed: %s
""".formatted(errorMessage(t));
LOG.error(errorMessage);
} else {
errorMessage = """
ID token verification has failed: %s
""".formatted(errorMessage(t));
LOG.error(errorMessage);
}
return errorMessage;
}
private static boolean prepareNonceForVerification(RoutingContext context, OidcTenantConfig oidcConfig,
CodeAuthenticationStateBean stateBean) {
if (oidcConfig.authentication().nonceRequired()) {
if (stateBean != null && stateBean.getNonce() != null) {
// Avoid parsing the token now
context.put(OidcConstants.NONCE, stateBean.getNonce());
return true;
}
LOG.errorf("ID token 'nonce' is required but the authentication request 'nonce' is not found in the state cookie");
return false;
} else {
return true;
}
}
private static String errorMessage(Throwable t) {
return t.getCause() != null ? t.getCause().getMessage() : t.getMessage();
}
private CodeAuthenticationStateBean getCodeAuthenticationBean(String[] parsedStateCookieValue,
TenantConfigContext configContext) {
if (parsedStateCookieValue.length == 2) {
CodeAuthenticationStateBean bean = new CodeAuthenticationStateBean();
Authentication authentication = configContext.oidcConfig().authentication();
boolean pkceRequired = authentication.pkceRequired().orElse(false);
if (!pkceRequired && !authentication.nonceRequired()) {
JsonObject json = new JsonObject(OidcCommonUtils.base64UrlDecode(parsedStateCookieValue[1]));
bean.setRestorePath(json.getString(OidcUtils.STATE_COOKIE_RESTORE_PATH));
return bean;
}
JsonObject json = null;
try {
json = OidcUtils.decryptJson(parsedStateCookieValue[1], configContext.getStateCookieEncryptionKey());
} catch (Exception ex) {
LOG.errorf("State cookie value for the %s tenant can not be decrypted: %s",
configContext.oidcConfig().tenantId().get(), ex.getMessage());
throw new AuthenticationCompletionException(ex);
}
bean.setRestorePath(json.getString(OidcUtils.STATE_COOKIE_RESTORE_PATH));
bean.setCodeVerifier(json.getString(OidcConstants.PKCE_CODE_VERIFIER));
bean.setNonce(json.getString(OidcConstants.NONCE));
return bean;
}
return null;
}
private String generateInternalIdToken(TenantConfigContext context, UserInfo userInfo, String currentIdToken,
Long accessTokenExpiresInSecs) {
JwtClaimsBuilder builder = Jwt.claims();
if (currentIdToken != null) {
AbstractJsonObject currentIdTokenJson = new AbstractJsonObject(
OidcUtils.decodeJwtContentAsString(currentIdToken)) {
};
for (String claim : currentIdTokenJson.getPropertyNames()) {
// Ignore "iat"(issued at) and "exp"(expiry) claims, new "iat" and "exp" claims will be generated
if (!claim.equals(Claims.iat.name()) && !claim.equals(Claims.exp.name())) {
builder.claim(claim, currentIdTokenJson.get(claim));
}
}
}
if (userInfo != null) {
builder.claim(OidcUtils.USER_INFO_ATTRIBUTE, userInfo.getJsonObject());
}
if (context.oidcConfig().authentication().internalIdTokenLifespan().isPresent()) {
builder.expiresIn(context.oidcConfig().authentication().internalIdTokenLifespan().get().getSeconds());
} else if (accessTokenExpiresInSecs != null) {
builder.expiresIn(accessTokenExpiresInSecs);
}
builder.audience(context.oidcConfig().clientId().get());
JwtSignatureBuilder sigBuilder = builder.jws().header(INTERNAL_IDTOKEN_HEADER, true);
String clientOrJwtSecret = context.getOidcProviderClient().getClientOrJwtSecret();
if (clientOrJwtSecret != null) {
LOG.debug("Signing internal ID token with a configured client secret");
return sigBuilder.sign(KeyUtils.createSecretKeyFromSecret(clientOrJwtSecret));
} else if (context.provider().client.getClientJwtKey() instanceof PrivateKey) {
LOG.debug("Signing internal ID token with a configured JWT private key");
return sigBuilder
.sign(OidcUtils.createSecretKeyFromDigest(((PrivateKey) context.provider().client.getClientJwtKey())
.getEncoded()));
} else {
LOG.debug("Signing internal ID token with a generated secret key");
return sigBuilder.sign(context.getInternalIdTokenSigningKey());
}
}
private Uni<Void> processSuccessfulAuthentication(RoutingContext context,
TenantConfigContext configContext,
AuthorizationCodeTokens tokens,
String idToken,
SecurityIdentity securityIdentity) {
LOG.debug("ID token has been verified, removing the existing session cookie if any and creating a new one");
return removeSessionCookie(context, configContext.oidcConfig())
.chain(new Function<Void, Uni<? extends Void>>() {
@Override
public Uni<? extends Void> apply(Void t) {
JsonObject idTokenJson = OidcCommonUtils.decodeJwtContent(idToken);
if (!idTokenJson.containsKey("exp") || !idTokenJson.containsKey("iat")) {
final String error = "ID Token is required to contain 'exp' and 'iat' claims";
LOG.error(error);
throw new AuthenticationCompletionException(error);
}
long maxAge = idTokenJson.getLong("exp") - idTokenJson.getLong("iat");
LOG.debugf("ID token is valid for %d seconds", maxAge);
if (configContext.oidcConfig().token().lifespanGrace().isPresent()) {
maxAge += configContext.oidcConfig().token().lifespanGrace().getAsInt();
}
if (configContext.oidcConfig().token().refreshExpired() && tokens.getRefreshToken() != null) {
maxAge += configContext.oidcConfig().authentication().sessionAgeExtension().getSeconds();
}
final long sessionMaxAge = maxAge;
context.put(SESSION_MAX_AGE_PARAM, maxAge);
context.put(TenantConfigContext.class.getName(), configContext);
// Just in case, remove the stale Back-Channel Logout data if the previous session was not terminated correctly
resolver.getBackChannelLogoutTokens().remove(configContext.oidcConfig().tenantId().get());
AuthorizationCodeTokens encryptedTokens = encryptTokens(context, configContext.oidcConfig(), tokens);
return resolver.getTokenStateManager()
.createTokenState(context, configContext.oidcConfig(), encryptedTokens,
createTokenStateRequestContext)
.map(new Function<String, Void>() {
@Override
public Void apply(String cookieValue) {
String sessionName = OidcUtils.getSessionCookieName(configContext.oidcConfig());
LOG.debugf("Session cookie length for the tenant %s is %d bytes.",
configContext.oidcConfig().tenantId().get(), cookieValue.length());
if (cookieValue.length() > OidcUtils.MAX_COOKIE_VALUE_LENGTH) {
LOG.debugf(
"Session cookie length for the tenant %s is greater than %d bytes."
+ " The cookie will be split to chunks to avoid browsers ignoring it."
+ " Alternative recommendations: 1. Set 'quarkus.oidc.token-state-manager.split-tokens=true'"
+ " to have the ID, access and refresh tokens stored in separate cookies."
+ " 2. Set 'quarkus.oidc.token-state-manager.strategy=id-refresh-tokens' if you do not need to use the access token"
+ " as a source of roles or to request UserInfo or propagate it to the downstream services."
+ " 3. Decrease the encrypted session cookie's length by enabling a direct encryption algorithm"
+ " with 'quarkus.oidc.token-state-manager.encryption-algorithm=dir'."
+ " 4. Decrease the session cookie's length by disabling its encryption with 'quarkus.oidc.token-state-manager.encryption-required=false'"
+ " but only if it is considered to be safe in your application's network."
+ " 5. Use the 'quarkus-oidc-db-token-state-manager' extension or the 'quarkus-oidc-redis-token-state-manager' extension"
+ " or register a custom 'quarkus.oidc.TokenStateManager'"
+ " CDI bean with the alternative priority set to 1 and save the tokens on the server.",
configContext.oidcConfig().tenantId().get(),
OidcUtils.MAX_COOKIE_VALUE_LENGTH);
OidcUtils.createChunkedCookie(context, configContext.oidcConfig(), sessionName,
cookieValue, sessionMaxAge);
} else {
OidcUtils.createSessionCookie(context, configContext.oidcConfig(), sessionName,
cookieValue, sessionMaxAge);
}
Set<CacheControl> cacheControl = configContext.oidcConfig().authentication()
.cacheControl()
.orElse(Set.of());
if (!cacheControl.isEmpty()) {
// Only 'no-store' is currently supported
context.response().putHeader(HttpHeaders.CACHE_CONTROL,
cacheControl.iterator().next().directive());
}
fireEvent(SecurityEvent.Type.OIDC_LOGIN, securityIdentity);
return null;
}
});
}
});
}
private AuthorizationCodeTokens encryptTokens(RoutingContext context, OidcTenantConfig oidcConfig,
AuthorizationCodeTokens tokens) {
if (!(resolver.getTokenStateManager() instanceof DefaultTokenStateManager)
&& oidcConfig.tokenStateManager().encryptionRequired()) {
return OidcUtils.encryptTokens(context, oidcConfig, tokens);
}
return tokens;
}
private AuthorizationCodeTokens decryptTokens(RoutingContext context, OidcTenantConfig oidcConfig,
AuthorizationCodeTokens tokens) {
if (!(resolver.getTokenStateManager() instanceof DefaultTokenStateManager)
&& oidcConfig.tokenStateManager().encryptionRequired()) {
return OidcUtils.decryptTokens(context, oidcConfig, tokens);
}
return tokens;
}
private void fireEvent(SecurityEvent.Type eventType, SecurityIdentity securityIdentity) {
if (resolver.isSecurityEventObserved()) {
SecurityEventHelper.fire(resolver.getSecurityEvent(), new SecurityEvent(eventType, securityIdentity));
}
}
private void fireEvent(SecurityEvent.Type eventType, Map<String, Object> properties) {
if (resolver.isSecurityEventObserved()) {
SecurityEventHelper.fire(resolver.getSecurityEvent(), new SecurityEvent(eventType, properties));
}
}
private static String decryptIdToken(TenantConfigContext configContext, String idToken) {
if (configContext.oidcConfig().token().decryptIdToken().isPresent() &&
!configContext.oidcConfig().token().decryptIdToken().get()) {
return idToken;
}
if (configContext.oidcConfig().token().decryptIdToken().orElse(false)
|| configContext.oidcConfig().token().decryptionKeyLocation().isPresent()) {
return OidcUtils.decryptToken(configContext, idToken);
} else {
return idToken;
}
}
private String getRedirectPath(OidcTenantConfig oidcConfig, RoutingContext context) {
Authentication auth = oidcConfig.authentication();
return auth.redirectPath().isPresent() ? auth.redirectPath().get() : context.request().path();
}
private String generateCodeFlowState(RoutingContext context, TenantConfigContext configContext,
String redirectPath, MultiMap requestQueryWithoutForwardedParams, String pkceCodeVerifier, String nonce) {
String uuid = UUID.randomUUID().toString();
String cookieValue = uuid;
Authentication authentication = configContext.oidcConfig().authentication();
boolean restorePath = isRestorePath(authentication);
if (restorePath || pkceCodeVerifier != null || nonce != null) {
CodeAuthenticationStateBean extraStateValue = new CodeAuthenticationStateBean();
if (restorePath) {
String requestQuery = context.request().query();
String requestPath = !redirectPath.equals(context.request().path()) || requestQuery != null
? context.request().path()
: "";
if (requestQuery != null) {
requestPath += "?";
if (requestQueryWithoutForwardedParams == null) {
requestPath += requestQuery;
} else {
StringBuilder sb = new StringBuilder();
for (String requestQueryParam : requestQueryWithoutForwardedParams.names()) {
for (String requestQueryParamValue : requestQueryWithoutForwardedParams.getAll(requestQueryParam)) {
if (sb.length() > 0) {
sb.append(AMP);
}
sb.append(requestQueryParam).append(EQ)
.append(OidcCommonUtils.urlEncode(requestQueryParamValue));
}
}
requestPath += sb.toString();
}
}
if (!requestPath.isEmpty()) {
extraStateValue.setRestorePath(requestPath);
}
}
extraStateValue.setCodeVerifier(pkceCodeVerifier);
extraStateValue.setNonce(nonce);
if (!extraStateValue.isEmpty()) {
cookieValue += (COOKIE_DELIM + encodeExtraStateValue(extraStateValue, configContext));
}
} else if (context.request().query() != null) {
CodeAuthenticationStateBean extraStateValue = new CodeAuthenticationStateBean();
extraStateValue.setRestorePath("?" + context.request().query());
cookieValue += (COOKIE_DELIM + encodeExtraStateValue(extraStateValue, configContext));
}
String stateCookieNameSuffix = configContext.oidcConfig().authentication().allowMultipleCodeFlows() ? "_" + uuid : "";
OidcUtils.createCookie(context, configContext.oidcConfig(),
getStateCookieName(configContext.oidcConfig()) + stateCookieNameSuffix, cookieValue,
configContext.oidcConfig().authentication().stateCookieAge().toSeconds());
return uuid;
}
private boolean isRestorePath(Authentication auth) {
return auth.restorePathAfterRedirect() || !auth.redirectPath().isPresent();
}
private String encodeExtraStateValue(CodeAuthenticationStateBean extraStateValue, TenantConfigContext configContext) {
JsonObject json = new JsonObject();
if (extraStateValue.getCodeVerifier() != null || extraStateValue.getNonce() != null) {
if (extraStateValue.getCodeVerifier() != null) {
json.put(OidcConstants.PKCE_CODE_VERIFIER, extraStateValue.getCodeVerifier());
}
if (extraStateValue.getNonce() != null) {
json.put(OidcConstants.NONCE, extraStateValue.getNonce());
}
if (extraStateValue.getRestorePath() != null) {
json.put(OidcUtils.STATE_COOKIE_RESTORE_PATH, extraStateValue.getRestorePath());
}
try {
return OidcUtils.encryptJson(json, configContext.getStateCookieEncryptionKey());
} catch (Exception ex) {
LOG.errorf("State cookie value for the %s tenant can not be encrypted: %s",
configContext.oidcConfig().tenantId().get(), ex.getMessage());
throw new AuthenticationCompletionException(ex);
}
} else {
json.put(OidcUtils.STATE_COOKIE_RESTORE_PATH, extraStateValue.getRestorePath());
return Base64.getUrlEncoder().withoutPadding().encodeToString(json.encode().getBytes(StandardCharsets.UTF_8));
}
}
private String generatePostLogoutState(RoutingContext context, TenantConfigContext configContext) {
OidcUtils.removeCookie(context, configContext.oidcConfig(), getPostLogoutCookieName(configContext.oidcConfig()));
return OidcUtils.createCookie(context, configContext.oidcConfig(), getPostLogoutCookieName(configContext.oidcConfig()),
UUID.randomUUID().toString(),
60 * 30).getValue();
}
private String buildUri(RoutingContext context, boolean forceHttps, String path) {
if (path.startsWith(HTTP_SCHEME)) {
return path;
}
String authority = URI.create(context.request().absoluteURI()).getAuthority();
return buildUri(context, forceHttps, authority, path);
}
private String buildUri(RoutingContext context, boolean forceHttps, String authority, String path) {
final String scheme = forceHttps ? "https" : context.request().scheme();
String forwardedPrefix = "";
if (resolver.isEnableHttpForwardedPrefix()) {
String forwardedPrefixHeader = context.request().getHeader("X-Forwarded-Prefix");
if (forwardedPrefixHeader != null && !forwardedPrefixHeader.equals("/") && !forwardedPrefixHeader.equals("//")) {
forwardedPrefix = forwardedPrefixHeader;
if (forwardedPrefix.endsWith("/")) {
forwardedPrefix = forwardedPrefix.substring(0, forwardedPrefix.length() - 1);
}
}
}
return new StringBuilder(scheme).append("://")
.append(authority)
.append(forwardedPrefix)
.append(path)
.toString();
}
private boolean isRpInitiatedLogout(RoutingContext context, TenantConfigContext configContext) {
return isEqualToRequestPath(configContext.oidcConfig().logout().path(), context, configContext);
}
private boolean isEqualToRequestPath(Optional<String> path, RoutingContext context, TenantConfigContext configContext) {
if (path.isPresent()) {
return context.request().path().equals(path.get());
}
return false;
}
private Uni<SecurityIdentity> refreshSecurityIdentity(TenantConfigContext configContext, String currentIdToken,
String refreshToken,
RoutingContext context, IdentityProviderManager identityProviderManager, boolean autoRefresh,
SecurityIdentity fallback) {
Uni<AuthorizationCodeTokens> refreshedTokensUni = refreshTokensUni(configContext, currentIdToken, refreshToken,
autoRefresh);
return refreshedTokensUni
.onItemOrFailure()
.transformToUni(new BiFunction<AuthorizationCodeTokens, Throwable, Uni<? extends SecurityIdentity>>() {
@Override
public Uni<SecurityIdentity> apply(final AuthorizationCodeTokens tokens, final Throwable t) {
if (t != null) {
LOG.debugf("ID token refresh has failed: %s", errorMessage(t));
if (autoRefresh) {
// Token refresh was initiated while ID token was still valid
if (fallback != null) {
LOG.debug("Using the current SecurityIdentity since the ID token is still valid");
return Uni.createFrom().item(fallback);
} else {
return Uni.createFrom()
.failure(new AuthenticationFailedException(t, tokenMap(currentIdToken)));
}
} else if (configContext.oidcConfig().authentication().sessionExpiredPath().isPresent()) {
// Token has expired but the refresh does not work, check if the session expired page is available
return redirectToSessionExpiredPage(context, configContext);
}
// Redirect to the OIDC provider to reauthenticate
return Uni.createFrom().failure(new AuthenticationFailedException(t, tokenMap(currentIdToken)));
} else {
context.put(OidcConstants.ACCESS_TOKEN_VALUE, tokens.getAccessToken());
context.put(AuthorizationCodeTokens.class.getName(), tokens);
context.put(REFRESH_TOKEN_GRANT_RESPONSE, Boolean.TRUE);
// Default token state manager may have encrypted the refreshed ID token
final String idToken = decryptIdToken(configContext, tokens.getIdToken());
LOG.debug("Verifying the refreshed ID token");
return authenticate(identityProviderManager, context,
new IdTokenCredential(idToken,
isInternalIdToken(idToken, configContext)))
.call(new Function<SecurityIdentity, Uni<?>>() {
@Override
public Uni<Void> apply(SecurityIdentity identity) {
// after a successful refresh, rebuild the identity and update the cookie
return processSuccessfulAuthentication(context, configContext,
tokens, idToken, identity);
}
})
.map(new Function<SecurityIdentity, SecurityIdentity>() {
@Override
public SecurityIdentity apply(SecurityIdentity identity) {
fireEvent(autoRefresh ? SecurityEvent.Type.OIDC_SESSION_REFRESHED
: SecurityEvent.Type.OIDC_SESSION_EXPIRED_AND_REFRESHED,
identity);
return identity;
}
}).onFailure().transform(new Function<Throwable, Throwable>() {
@Override
public Throwable apply(Throwable tInner) {
LOG.debugf("Verifying the refreshed ID token failed %s", errorMessage(tInner));
return new AuthenticationFailedException(tInner, tokenMap(currentIdToken));
}
});
}
}
});
}
private Uni<AuthorizationCodeTokens> refreshTokensUni(TenantConfigContext configContext,
String currentIdToken, String refreshToken, boolean autoRefresh) {
return configContext.provider().refreshTokens(refreshToken).onItem()
.transform(new Function<AuthorizationCodeTokens, AuthorizationCodeTokens>() {
@Override
public AuthorizationCodeTokens apply(AuthorizationCodeTokens tokens) {
if (tokens.getRefreshToken() == null) {
tokens.setRefreshToken(refreshToken);
}
if (tokens.getIdToken() == null) {
if (autoRefresh) {
// Auto-refresh is triggered while current ID token is still valid, continue using it.
tokens.setIdToken(currentIdToken);
} else if (isIdTokenRequired(configContext)) {
LOG.debugf(
"Required ID token is not returned in the refresh token grant response, re-authentication is required");
throw new AuthenticationFailedException(tokenMap(currentIdToken));
} else {
if (!isInternalIdToken(currentIdToken, configContext)) {
LOG.debugf(
"OIDC provider issued an ID token after the authorization code flow completion but did not refresh it,"
+ " an internal ID token will be generated");
}
tokens.setIdToken(generateInternalIdToken(configContext, null, currentIdToken,
tokens.getAccessTokenExpiresIn()));
}
}
return tokens;
}
});
}
private Uni<AuthorizationCodeTokens> getCodeFlowTokensUni(RoutingContext context, TenantConfigContext configContext,
String code, String codeVerifier) {
// 'redirect_uri': it must match the 'redirect_uri' query parameter which was used during the code request.
Optional<String> configuredRedirectPath = configContext.oidcConfig().authentication().redirectPath();
if (configuredRedirectPath.isPresent()) {
String requestPath = configuredRedirectPath.get().startsWith(HTTP_SCHEME)
? buildUri(context, configContext.oidcConfig().authentication().forceRedirectHttpsScheme().orElse(false),
context.request().path())
: context.request().path();
if (!configuredRedirectPath.get().equals(requestPath)) {
LOG.warnf("Token redirect path %s does not match the current request path", requestPath);
return Uni.createFrom().failure(new AuthenticationFailedException("Wrong redirect path"));
}
}
String redirectPath = getRedirectPath(configContext.oidcConfig(), context);
String redirectUriParam = buildUri(context, isForceHttps(configContext.oidcConfig()), redirectPath);
LOG.debugf("Token request redirect_uri parameter: %s", redirectUriParam);
return configContext.provider().getCodeFlowTokens(code, redirectUriParam, codeVerifier);
}
private String buildLogoutRedirectUri(TenantConfigContext configContext, String idToken, RoutingContext context) {
String logoutPath = configContext.provider().getMetadata().getEndSessionUri();
Map<String, String> extraParams = configContext.oidcConfig().logout().extraParams();
StringBuilder logoutUri = new StringBuilder(logoutPath);
if (idToken != null || configContext.oidcConfig().logout().postLogoutPath().isPresent()
|| (extraParams != null && !extraParams.isEmpty())) {
logoutUri.append("?");
}
if (idToken != null) {
logoutUri.append(OidcConstants.LOGOUT_ID_TOKEN_HINT).append(EQ).append(idToken);
}
if (configContext.oidcConfig().logout().postLogoutPath().isPresent()) {
logoutUri.append(AMP).append(configContext.oidcConfig().logout().postLogoutUriParam()).append(EQ).append(
OidcCommonUtils.urlEncode(buildUri(context, isForceHttps(configContext.oidcConfig()),
configContext.oidcConfig().logout().postLogoutPath().get())));
logoutUri.append(AMP).append(OidcConstants.LOGOUT_STATE).append(EQ)
.append(generatePostLogoutState(context, configContext));
}
addExtraParamsToUri(logoutUri, configContext.oidcConfig().logout().extraParams());
return logoutUri.toString();
}
private static void addExtraParamsToUri(StringBuilder builder, Map<String, String> extraParams) {
if (extraParams != null) {
for (Map.Entry<String, String> entry : extraParams.entrySet()) {
if (entry.getKey().equals(OidcConstants.TOKEN_SCOPE)) {
continue;
}
builder.append(AMP).append(entry.getKey()).append(EQ).append(OidcCommonUtils.urlEncode(entry.getValue()));
}
}
}
private boolean isForceHttps(OidcTenantConfig oidcConfig) {
return oidcConfig.authentication().forceRedirectHttpsScheme().orElse(false);
}
private Uni<Void> buildLogoutRedirectUriUni(RoutingContext context, TenantConfigContext configContext,
String idToken) {
return removeSessionCookie(context, configContext.oidcConfig())
.map(new Function<Void, Void>() {
@Override
public Void apply(Void t) {
if (configContext.oidcConfig().logout().logoutMode() == LogoutMode.QUERY) {
String logoutUri = buildLogoutRedirectUri(configContext, idToken, context);
LOG.debugf("Logout uri: %s", logoutUri);
throw new AuthenticationRedirectException(
filterRedirect(context, configContext, logoutUri, Redirect.Location.OIDC_LOGOUT));
} else {
String postLogoutUrl = null;
String postLogoutState = null;
if (configContext.oidcConfig().logout().postLogoutPath().isPresent()) {
postLogoutUrl = buildUri(context, isForceHttps(configContext.oidcConfig()),
configContext.oidcConfig().logout().postLogoutPath().get());
postLogoutState = generatePostLogoutState(context, configContext);
}
String logoutUrl = filterRedirect(context, configContext,
configContext.provider().getMetadata().getEndSessionUri(), Redirect.Location.OIDC_LOGOUT);
// Target URL is embedded in the form post payload
String formPostLogout = LogoutUtils.createFormPostLogout(configContext.oidcConfig().logout(),
logoutUrl, idToken,
postLogoutUrl, postLogoutState);
LOG.debugf("Initiating form post logout");
throw new AuthenticationRedirectException(200, formPostLogout);
}
}
});
}
private static String getStateCookieName(OidcTenantConfig oidcConfig) {
return OidcUtils.STATE_COOKIE_NAME + OidcUtils.getCookieSuffix(oidcConfig);
}
private static String getPostLogoutCookieName(OidcTenantConfig oidcConfig) {
return OidcUtils.POST_LOGOUT_COOKIE_NAME + OidcUtils.getCookieSuffix(oidcConfig);
}
private Uni<Void> removeSessionCookie(RoutingContext context, OidcTenantConfig oidcConfig) {
return OidcUtils.removeSessionCookie(context, oidcConfig, resolver.getTokenStateManager());
}
private
|
CodeAuthenticationMechanism
|
java
|
quarkusio__quarkus
|
integration-tests/main/src/main/java/io/quarkus/it/rest/PayloadClass.java
|
{
"start": 36,
"end": 239
}
|
class ____ {
private final String message;
public PayloadClass(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
|
PayloadClass
|
java
|
apache__camel
|
components/camel-cxf/camel-cxf-soap/src/test/java/org/apache/camel/component/cxf/jaxws/CxfPayLoadMessageRouterAddressOverrideTest.java
|
{
"start": 1388,
"end": 2834
}
|
class ____ extends CxfPayLoadMessageRouterTest {
private String routerEndpointURI = "cxf://" + getRouterAddress() + "?" + SERVICE_CLASS + "&dataFormat=PAYLOAD";
private String serviceEndpointURI = "cxf://http://localhost:9002/badAddress" + "?" + SERVICE_CLASS + "&dataFormat=PAYLOAD";
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from(routerEndpointURI).process(new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(Exchange.DESTINATION_OVERRIDE_URL, getServiceAddress());
CxfPayload<?> payload = exchange.getIn().getBody(CxfPayload.class);
List<Source> elements = payload.getBodySources();
assertNotNull(elements, "We should get the elements here");
assertEquals(1, elements.size(), "Get the wrong elements size");
Element el = new XmlConverter().toDOMElement(elements.get(0));
assertEquals("http://jaxws.cxf.component.camel.apache.org/", el.getNamespaceURI(),
"Get the wrong namespace URI");
}
})
.to(serviceEndpointURI);
}
};
}
}
|
CxfPayLoadMessageRouterAddressOverrideTest
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/submitted/multipleresultsetswithassociation/OrderDetail.java
|
{
"start": 729,
"end": 1643
}
|
class ____ {
private int orderId;
private int lineNumber;
private int quantity;
private String itemDescription;
private OrderHeader orderHeader;
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public OrderHeader getOrderHeader() {
return orderHeader;
}
public void setOrderHeader(OrderHeader orderHeader) {
this.orderHeader = orderHeader;
}
}
|
OrderDetail
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/protocol/impl/pb/GetDisabledNameservicesResponsePBImpl.java
|
{
"start": 1695,
"end": 3153
}
|
class ____
extends GetDisabledNameservicesResponse implements PBRecord {
private FederationProtocolPBTranslator<GetDisabledNameservicesResponseProto,
Builder, GetDisabledNameservicesResponseProtoOrBuilder> translator =
new FederationProtocolPBTranslator<
GetDisabledNameservicesResponseProto, Builder,
GetDisabledNameservicesResponseProtoOrBuilder>(
GetDisabledNameservicesResponseProto.class);
public GetDisabledNameservicesResponsePBImpl() {
}
public GetDisabledNameservicesResponsePBImpl(
GetDisabledNameservicesResponseProto proto) {
this.translator.setProto(proto);
}
@Override
public GetDisabledNameservicesResponseProto getProto() {
return this.translator.build();
}
@Override
public void setProto(Message proto) {
this.translator.setProto(proto);
}
@Override
public void readInstance(String base64String) throws IOException {
this.translator.readInstance(base64String);
}
@Override
public Set<String> getNameservices() {
List<String> nsIds =
this.translator.getProtoOrBuilder().getNameServiceIdsList();
return new TreeSet<>(nsIds);
}
@Override
public void setNameservices(Set<String> nameservices) {
this.translator.getBuilder().clearNameServiceIds();
for (String nsId : nameservices) {
this.translator.getBuilder().addNameServiceIds(nsId);
}
}
}
|
GetDisabledNameservicesResponsePBImpl
|
java
|
spring-projects__spring-framework
|
spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DataClassRowMapper.java
|
{
"start": 2873,
"end": 3187
}
|
class ____<T> extends BeanPropertyRowMapper<T> {
private final Constructor<T> mappedConstructor;
private final @Nullable String[] constructorParameterNames;
private final TypeDescriptor[] constructorParameterTypes;
/**
* Create a new {@code DataClassRowMapper}.
* @param mappedClass the
|
DataClassRowMapper
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java
|
{
"start": 2066,
"end": 2394
}
|
class ____ {
static final String CONFIGURATION_CLASS_FULL = "full";
static final String CONFIGURATION_CLASS_LITE = "lite";
/**
* When set to {@link Boolean#TRUE}, this attribute signals that the bean class
* for the given {@link BeanDefinition} should be considered as a candidate
* configuration
|
ConfigurationClassUtils
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/atomic/longadder/LongAdderAssert_usingComparator_Test.java
|
{
"start": 948,
"end": 1559
}
|
class ____ extends LongAdderAssertBaseTest {
private final Comparator<LongAdder> comparator = comparingLong(LongAdder::longValue);
@Override
protected LongAdderAssert invoke_api_method() {
// in that, we don't care of the comparator, the point to check is that we switch correctly of comparator
return assertions.usingComparator(comparator);
}
@Override
protected void verify_internal_effects() {
assertThat(getObjects(assertions).getComparator()).isSameAs(comparator);
assertThat(getLongs(assertions).getComparator()).isSameAs(comparator);
}
}
|
LongAdderAssert_usingComparator_Test
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/rm/ContainerAllocatorEvent.java
|
{
"start": 964,
"end": 1314
}
|
class ____ extends
AbstractEvent<ContainerAllocator.EventType> {
private TaskAttemptId attemptID;
public ContainerAllocatorEvent(TaskAttemptId attemptID,
ContainerAllocator.EventType type) {
super(type);
this.attemptID = attemptID;
}
public TaskAttemptId getAttemptID() {
return attemptID;
}
}
|
ContainerAllocatorEvent
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/state/memory/ByteStreamStateHandle.java
|
{
"start": 1198,
"end": 3497
}
|
class ____ implements StreamStateHandle {
private static final long serialVersionUID = -5280226231202517594L;
/** The state data. */
private final byte[] data;
/**
* A unique name of by which this state handle is identified and compared. Like a filename, all
* {@link ByteStreamStateHandle} with the exact same name must also have the exact same content
* in data.
*/
private final String handleName;
/** Creates a new ByteStreamStateHandle containing the given data. */
public ByteStreamStateHandle(String handleName, byte[] data) {
this.handleName = Preconditions.checkNotNull(handleName);
this.data = Preconditions.checkNotNull(data);
}
@Override
public FSDataInputStream openInputStream() throws IOException {
return new ByteStateHandleInputStream(data);
}
@Override
public Optional<byte[]> asBytesIfInMemory() {
return Optional.of(getData());
}
@Override
public PhysicalStateHandleID getStreamStateHandleID() {
return new PhysicalStateHandleID(handleName);
}
public byte[] getData() {
return data;
}
public String getHandleName() {
return handleName;
}
@Override
public void discardState() {}
@Override
public long getStateSize() {
return data.length;
}
@Override
public void collectSizeStats(StateObjectSizeStatsCollector collector) {
collector.add(StateObjectLocation.LOCAL_MEMORY, getStateSize());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ByteStreamStateHandle)) {
return false;
}
ByteStreamStateHandle that = (ByteStreamStateHandle) o;
return handleName.equals(that.handleName);
}
@Override
public int hashCode() {
return 31 * handleName.hashCode();
}
@Override
public String toString() {
return "ByteStreamStateHandle{"
+ "handleName='"
+ handleName
+ '\''
+ ", dataBytes="
+ data.length
+ '}';
}
/** An input stream view on a byte array. */
private static final
|
ByteStreamStateHandle
|
java
|
netty__netty
|
transport-classes-kqueue/src/main/java/io/netty/channel/kqueue/KQueueIoHandle.java
|
{
"start": 806,
"end": 965
}
|
interface ____ extends IoHandle {
/**
* Return the ident of the {@link IoHandle}.
*
* @return ident.
*/
int ident();
}
|
KQueueIoHandle
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/float_/FloatAssert_isGreaterThanOrEqualTo_FloatWrapper_Test.java
|
{
"start": 1104,
"end": 2324
}
|
class ____ extends FloatAssertBaseTest {
private Float other = 1.0f;
@Override
protected FloatAssert invoke_api_method() {
return assertions.isGreaterThanOrEqualTo(other);
}
@Override
protected void verify_internal_effects() {
verify(comparables).assertGreaterThanOrEqualTo(getInfo(assertions), getActual(assertions), other);
verifyNoInteractions(floats);
}
@Test
void should_fail_when_comparing_negative_zero_to_positive_zero() {
// GIVEN
final Float positiveZero = 0.0f;
final float negativeZero = -0.0f;
// THEN
expectAssertionError(() -> assertThat(negativeZero).isGreaterThanOrEqualTo(positiveZero));
verifyNoInteractions(floats);
}
@Test
void should_pass_when_comparing_positive_zero_to_negative_zero() {
// GIVEN
final Float positiveZero = 0.0f;
final Float negativeZero = -0.0f;
// THEN
assertThat(positiveZero).isGreaterThanOrEqualTo(negativeZero);
}
@Test
void should_honor_user_specified_comparator() {
// GIVEN
final Float one = 1.0f;
// THEN
assertThat(-one).usingComparator(ALWAY_EQUAL_FLOAT)
.isGreaterThanOrEqualTo(one);
}
}
|
FloatAssert_isGreaterThanOrEqualTo_FloatWrapper_Test
|
java
|
quarkusio__quarkus
|
extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/sortedset/ZScanCursor.java
|
{
"start": 123,
"end": 477
}
|
interface ____<V> extends Cursor<List<ScoredValue<V>>> {
/**
* Returns an {@code Iterable} providing each member of the sorted set individually.
* Unlike {@link #next()} which provides the members by batch, this method returns them one by one.
*
* @return the iterable
*/
Iterable<ScoredValue<V>> toIterable();
}
|
ZScanCursor
|
java
|
quarkusio__quarkus
|
extensions/elytron-security/runtime/src/main/java/io/quarkus/elytron/security/runtime/ElytronTokenIdentityProvider.java
|
{
"start": 991,
"end": 2869
}
|
class ____ implements IdentityProvider<TokenAuthenticationRequest> {
private static final Logger log = Logger.getLogger(ElytronTokenIdentityProvider.class);
@Inject
SecurityDomain domain;
@Override
public Class<TokenAuthenticationRequest> getRequestType() {
return TokenAuthenticationRequest.class;
}
@Override
public Uni<SecurityIdentity> authenticate(TokenAuthenticationRequest request,
AuthenticationRequestContext context) {
return context.runBlocking(new Supplier<SecurityIdentity>() {
@Override
public SecurityIdentity get() {
org.wildfly.security.auth.server.SecurityIdentity result;
try {
result = domain.authenticate(new BearerTokenEvidence(request.getToken().getToken()));
if (result == null) {
throw new AuthenticationFailedException();
}
QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder();
for (Attributes.Entry entry : result.getAttributes().entries()) {
builder.addAttribute(entry.getKey(), entry);
}
builder.setPrincipal(result.getPrincipal());
for (String i : result.getRoles()) {
builder.addRole(i);
}
builder.addCredential(request.getToken());
return builder.build();
} catch (RealmUnavailableException e) {
throw new RuntimeException(e);
} catch (SecurityException e) {
log.debug("Authentication failed", e);
throw new AuthenticationFailedException(e);
}
}
});
}
}
|
ElytronTokenIdentityProvider
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/results/QuestionAnsweringInferenceResultsTests.java
|
{
"start": 731,
"end": 3568
}
|
class ____ extends InferenceResultsTestCase<QuestionAnsweringInferenceResults> {
public static QuestionAnsweringInferenceResults createRandomResults() {
return new QuestionAnsweringInferenceResults(
randomAlphaOfLength(10),
randomInt(1000),
randomInt(1000),
randomBoolean()
? null
: Stream.generate(TopAnswerEntryTests::createRandomTopAnswerEntry)
.limit(randomIntBetween(0, 10))
.collect(Collectors.toList()),
randomAlphaOfLength(10),
randomDoubleBetween(0.0, 1.0, false),
randomBoolean()
);
}
@SuppressWarnings("unchecked")
public void testWriteResultsWithTopClasses() {
List<QuestionAnsweringInferenceResults.TopAnswerEntry> entries = Arrays.asList(
new QuestionAnsweringInferenceResults.TopAnswerEntry("foo", 0.7, 0, 3),
new QuestionAnsweringInferenceResults.TopAnswerEntry("bar", 0.2, 11, 14),
new QuestionAnsweringInferenceResults.TopAnswerEntry("baz", 0.1, 4, 7)
);
QuestionAnsweringInferenceResults result = new QuestionAnsweringInferenceResults(
"foo",
0,
3,
entries,
"my_results",
0.7,
randomBoolean()
);
IngestDocument document = TestIngestDocument.emptyIngestDocument();
writeResult(result, document, "result_field", "test");
List<?> list = document.getFieldValue("result_field.top_classes", List.class);
assertThat(list.size(), equalTo(3));
for (int i = 0; i < 3; i++) {
Map<String, Object> map = (Map<String, Object>) list.get(i);
assertThat(map, equalTo(entries.get(i).asValueMap()));
}
assertThat(document.getFieldValue("result_field.my_results", String.class), equalTo("foo"));
}
@Override
protected QuestionAnsweringInferenceResults createTestInstance() {
return createRandomResults();
}
@Override
protected QuestionAnsweringInferenceResults mutateInstance(QuestionAnsweringInferenceResults instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected Writeable.Reader<QuestionAnsweringInferenceResults> instanceReader() {
return QuestionAnsweringInferenceResults::new;
}
@Override
void assertFieldValues(
QuestionAnsweringInferenceResults createdInstance,
IngestDocument document,
String parentField,
String resultsField
) {
String path = parentField + resultsField;
assertThat(document.getFieldValue(path, String.class), equalTo(createdInstance.predictedValue()));
}
}
|
QuestionAnsweringInferenceResultsTests
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/ComparisonContractViolatedTest.java
|
{
"start": 1355,
"end": 1481
}
|
class ____ {
static final int POSITIVE_CONSTANT = 50;
static
|
ComparisonContractViolatedPositiveCases
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isBetween_with_String_parameters_Test.java
|
{
"start": 1027,
"end": 2109
}
|
class ____
extends AbstractOffsetDateTimeAssertBaseTest {
@Override
protected OffsetDateTimeAssert invoke_api_method() {
return assertions.isBetween(BEFORE.toString(), AFTER.toString());
}
@Override
protected void verify_internal_effects() {
verify(comparables).assertIsBetween(getInfo(assertions), getActual(assertions), BEFORE, AFTER, true, true);
}
@Test
void should_throw_a_DateTimeParseException_if_start_String_parameter_cant_be_converted() {
// GIVEN
String abc = "abc";
// WHEN
Throwable thrown = catchThrowable(() -> assertions.isBetween(abc, AFTER.toString()));
// THEN
assertThat(thrown).isInstanceOf(DateTimeParseException.class);
}
@Test
void should_throw_a_DateTimeParseException_if_end_String_parameter_cant_be_converted() {
// GIVEN
String abc = "abc";
// WHEN
Throwable thrown = catchThrowable(() -> assertions.isBetween(BEFORE.toString(), abc));
// THEN
assertThat(thrown).isInstanceOf(DateTimeParseException.class);
}
}
|
OffsetDateTimeAssert_isBetween_with_String_parameters_Test
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java
|
{
"start": 57353,
"end": 57523
}
|
class ____ extends MyControllerWithAbstractMethod<String> {
@Override
public String handle(String arg) {
return arg;
}
}
}
|
SubControllerImplementingAbstractMethod
|
java
|
spring-projects__spring-boot
|
module/spring-boot-health/src/main/java/org/springframework/boot/health/contributor/ReactiveHealthIndicatorAdapter.java
|
{
"start": 886,
"end": 1327
}
|
class ____ implements HealthIndicator {
private final ReactiveHealthIndicator delegate;
ReactiveHealthIndicatorAdapter(ReactiveHealthIndicator indicator) {
this.delegate = indicator;
}
@Override
public @Nullable Health health(boolean includeDetails) {
return this.delegate.health(includeDetails).block();
}
@Override
public @Nullable Health health() {
return this.delegate.health().block();
}
}
|
ReactiveHealthIndicatorAdapter
|
java
|
apache__rocketmq
|
client/src/main/java/org/apache/rocketmq/client/impl/MQClientAPIImpl.java
|
{
"start": 17374,
"end": 184438
}
|
class ____ implements NameServerUpdateCallback, StartAndShutdown {
private final static Logger log = LoggerFactory.getLogger(MQClientAPIImpl.class);
private static boolean sendSmartMsg =
Boolean.parseBoolean(System.getProperty("org.apache.rocketmq.client.sendSmartMsg", "true"));
static {
System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION));
}
private final RemotingClient remotingClient;
private final TopAddressing topAddressing;
private final ClientRemotingProcessor clientRemotingProcessor;
private String nameSrvAddr = null;
private ClientConfig clientConfig;
public MQClientAPIImpl(
final NettyClientConfig nettyClientConfig,
final ClientRemotingProcessor clientRemotingProcessor,
final RPCHook rpcHook,
final ClientConfig clientConfig
) {
this(nettyClientConfig, clientRemotingProcessor, rpcHook, clientConfig, null);
}
public MQClientAPIImpl(
final NettyClientConfig nettyClientConfig,
final ClientRemotingProcessor clientRemotingProcessor,
final RPCHook rpcHook,
final ClientConfig clientConfig,
final ChannelEventListener channelEventListener
) {
this(
nettyClientConfig,
clientRemotingProcessor,
rpcHook,
clientConfig,
channelEventListener,
null
);
}
public MQClientAPIImpl(final NettyClientConfig nettyClientConfig,
final ClientRemotingProcessor clientRemotingProcessor,
RPCHook rpcHook, final ClientConfig clientConfig,
final ChannelEventListener channelEventListener,
final ObjectCreator<RemotingClient> remotingClientCreator) {
this.clientConfig = clientConfig;
topAddressing = new DefaultTopAddressing(MixAll.getWSAddr(), clientConfig.getUnitName());
topAddressing.registerChangeCallBack(this);
this.remotingClient = remotingClientCreator != null
? remotingClientCreator.create(nettyClientConfig, channelEventListener)
: new NettyRemotingClient(nettyClientConfig, channelEventListener);
this.clientRemotingProcessor = clientRemotingProcessor;
this.remotingClient.registerRPCHook(new NamespaceRpcHook(clientConfig));
// Inject stream rpc hook first to make reserve field signature
if (clientConfig.isEnableStreamRequestType()) {
this.remotingClient.registerRPCHook(new StreamTypeRPCHook());
}
this.remotingClient.registerRPCHook(rpcHook);
this.remotingClient.registerRPCHook(new DynamicalExtFieldRPCHook());
this.remotingClient.registerProcessor(RequestCode.CHECK_TRANSACTION_STATE, this.clientRemotingProcessor, null);
this.remotingClient.registerProcessor(RequestCode.NOTIFY_CONSUMER_IDS_CHANGED, this.clientRemotingProcessor, null);
this.remotingClient.registerProcessor(RequestCode.RESET_CONSUMER_CLIENT_OFFSET, this.clientRemotingProcessor, null);
this.remotingClient.registerProcessor(RequestCode.GET_CONSUMER_STATUS_FROM_CLIENT, this.clientRemotingProcessor, null);
this.remotingClient.registerProcessor(RequestCode.GET_CONSUMER_RUNNING_INFO, this.clientRemotingProcessor, null);
this.remotingClient.registerProcessor(RequestCode.CONSUME_MESSAGE_DIRECTLY, this.clientRemotingProcessor, null);
this.remotingClient.registerProcessor(RequestCode.PUSH_REPLY_MESSAGE_TO_CLIENT, this.clientRemotingProcessor, null);
}
public List<String> getNameServerAddressList() {
return this.remotingClient.getNameServerAddressList();
}
public RemotingClient getRemotingClient() {
return remotingClient;
}
public String fetchNameServerAddr() {
try {
String addrs = this.topAddressing.fetchNSAddr();
if (!UtilAll.isBlank(addrs)) {
if (!addrs.equals(this.nameSrvAddr)) {
log.info("name server address changed, old=" + this.nameSrvAddr + ", new=" + addrs);
this.updateNameServerAddressList(addrs);
this.nameSrvAddr = addrs;
return nameSrvAddr;
}
}
} catch (Exception e) {
log.error("fetchNameServerAddr Exception", e);
}
return nameSrvAddr;
}
@Override
public String onNameServerAddressChange(String namesrvAddress) {
if (namesrvAddress != null) {
if (!namesrvAddress.equals(this.nameSrvAddr)) {
log.info("name server address changed, old=" + this.nameSrvAddr + ", new=" + namesrvAddress);
this.updateNameServerAddressList(namesrvAddress);
this.nameSrvAddr = namesrvAddress;
return nameSrvAddr;
}
}
return nameSrvAddr;
}
public void updateNameServerAddressList(final String addrs) {
String[] addrArray = addrs.split(";");
List<String> list = Arrays.asList(addrArray);
this.remotingClient.updateNameServerAddressList(list);
}
public void start() {
this.remotingClient.start();
}
public void shutdown() {
this.remotingClient.shutdown();
}
public Set<MessageQueueAssignment> queryAssignment(final String addr, final String topic,
final String consumerGroup, final String clientId, final String strategyName,
final MessageModel messageModel, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
QueryAssignmentRequestBody requestBody = new QueryAssignmentRequestBody();
requestBody.setTopic(topic);
requestBody.setConsumerGroup(consumerGroup);
requestBody.setClientId(clientId);
requestBody.setMessageModel(messageModel);
requestBody.setStrategyName(strategyName);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_ASSIGNMENT, null);
request.setBody(requestBody.encode());
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
QueryAssignmentResponseBody queryAssignmentResponseBody = QueryAssignmentResponseBody.decode(response.getBody(), QueryAssignmentResponseBody.class);
return queryAssignmentResponseBody.getMessageQueueAssignments();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void createSubscriptionGroup(final String addr, final SubscriptionGroupConfig config,
final long timeoutMillis) throws RemotingException, InterruptedException, MQClientException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_SUBSCRIPTIONGROUP, null);
byte[] body = RemotingSerializable.encode(config);
request.setBody(body);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void createSubscriptionGroupList(final String address, final List<SubscriptionGroupConfig> configs,
final long timeoutMillis) throws RemotingException, InterruptedException, MQClientException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_SUBSCRIPTIONGROUP_LIST, null);
SubscriptionGroupList requestBody = new SubscriptionGroupList(configs);
request.setBody(requestBody.encode());
RemotingCommand response = this.remotingClient.invokeSync(
MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), address), request, timeoutMillis);
assert response != null;
if (response.getCode() == ResponseCode.SUCCESS) {
return;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void createTopic(final String addr, final String defaultTopic, final TopicConfig topicConfig,
final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
Validators.checkTopicConfig(topicConfig);
CreateTopicRequestHeader requestHeader = new CreateTopicRequestHeader();
requestHeader.setTopic(topicConfig.getTopicName());
requestHeader.setDefaultTopic(defaultTopic);
requestHeader.setReadQueueNums(topicConfig.getReadQueueNums());
requestHeader.setWriteQueueNums(topicConfig.getWriteQueueNums());
requestHeader.setPerm(topicConfig.getPerm());
requestHeader.setTopicFilterType(topicConfig.getTopicFilterType().name());
requestHeader.setTopicSysFlag(topicConfig.getTopicSysFlag());
requestHeader.setOrder(topicConfig.isOrder());
requestHeader.setAttributes(AttributeParser.parseToString(topicConfig.getAttributes()));
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_TOPIC, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void createTopicList(final String address, final List<TopicConfig> topicConfigList, final long timeoutMillis)
throws InterruptedException, RemotingException, MQClientException {
CreateTopicListRequestHeader requestHeader = new CreateTopicListRequestHeader();
CreateTopicListRequestBody requestBody = new CreateTopicListRequestBody(topicConfigList);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_TOPIC_LIST, requestHeader);
request.setBody(requestBody.encode());
RemotingCommand response = this.remotingClient.invokeSync(
MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), address), request, timeoutMillis);
assert response != null;
if (response.getCode() == ResponseCode.SUCCESS) {
return;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public SendResult sendMessage(
final String addr,
final String brokerName,
final Message msg,
final SendMessageRequestHeader requestHeader,
final long timeoutMillis,
final CommunicationMode communicationMode,
final SendMessageContext context,
final DefaultMQProducerImpl producer
) throws RemotingException, MQBrokerException, InterruptedException {
return sendMessage(addr, brokerName, msg, requestHeader, timeoutMillis, communicationMode, null, null, null, 0, context, producer);
}
public SendResult sendMessage(
final String addr,
final String brokerName,
final Message msg,
final SendMessageRequestHeader requestHeader,
final long timeoutMillis,
final CommunicationMode communicationMode,
final SendCallback sendCallback,
final TopicPublishInfo topicPublishInfo,
final MQClientInstance instance,
final int retryTimesWhenSendFailed,
final SendMessageContext context,
final DefaultMQProducerImpl producer
) throws RemotingException, MQBrokerException, InterruptedException {
long beginStartTime = System.currentTimeMillis();
RemotingCommand request = null;
String msgType = msg.getProperty(MessageConst.PROPERTY_MESSAGE_TYPE);
boolean isReply = msgType != null && msgType.equals(MixAll.REPLY_MESSAGE_FLAG);
if (isReply) {
if (sendSmartMsg) {
SendMessageRequestHeaderV2 requestHeaderV2 = SendMessageRequestHeaderV2.createSendMessageRequestHeaderV2(requestHeader);
request = RemotingCommand.createRequestCommand(RequestCode.SEND_REPLY_MESSAGE_V2, requestHeaderV2);
} else {
request = RemotingCommand.createRequestCommand(RequestCode.SEND_REPLY_MESSAGE, requestHeader);
}
} else {
if (sendSmartMsg || msg instanceof MessageBatch) {
SendMessageRequestHeaderV2 requestHeaderV2 = SendMessageRequestHeaderV2.createSendMessageRequestHeaderV2(requestHeader);
request = RemotingCommand.createRequestCommand(msg instanceof MessageBatch ? RequestCode.SEND_BATCH_MESSAGE : RequestCode.SEND_MESSAGE_V2, requestHeaderV2);
} else {
request = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, requestHeader);
}
}
request.setBody(msg.getBody());
switch (communicationMode) {
case ONEWAY:
this.remotingClient.invokeOneway(addr, request, timeoutMillis);
return null;
case ASYNC:
final AtomicInteger times = new AtomicInteger();
long costTimeAsync = System.currentTimeMillis() - beginStartTime;
if (timeoutMillis < costTimeAsync) {
throw new RemotingTooMuchRequestException("sendMessage call timeout");
}
this.sendMessageAsync(addr, brokerName, msg, timeoutMillis - costTimeAsync, request, sendCallback, topicPublishInfo, instance,
retryTimesWhenSendFailed, times, context, producer);
return null;
case SYNC:
long costTimeSync = System.currentTimeMillis() - beginStartTime;
if (timeoutMillis < costTimeSync) {
throw new RemotingTooMuchRequestException("sendMessage call timeout");
}
return this.sendMessageSync(addr, brokerName, msg, timeoutMillis - costTimeSync, request);
default:
assert false;
break;
}
return null;
}
private SendResult sendMessageSync(
final String addr,
final String brokerName,
final Message msg,
final long timeoutMillis,
final RemotingCommand request
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
return this.processSendResponse(brokerName, msg, response, addr);
}
void execRpcHooksAfterRequest(ResponseFuture responseFuture) {
if (this.remotingClient instanceof NettyRemotingClient) {
NettyRemotingClient remotingClient = (NettyRemotingClient) this.remotingClient;
RemotingCommand response = responseFuture.getResponseCommand();
remotingClient.doAfterRpcHooks(RemotingHelper.parseChannelRemoteAddr(responseFuture.getChannel()), responseFuture.getRequestCommand(), response);
}
}
private void sendMessageAsync(
final String addr,
final String brokerName,
final Message msg,
final long timeoutMillis,
final RemotingCommand request,
final SendCallback sendCallback,
final TopicPublishInfo topicPublishInfo,
final MQClientInstance instance,
final int retryTimesWhenSendFailed,
final AtomicInteger times,
final SendMessageContext context,
final DefaultMQProducerImpl producer
) {
final long beginStartTime = System.currentTimeMillis();
try {
this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
}
@Override
public void operationSucceed(RemotingCommand response) {
long cost = System.currentTimeMillis() - beginStartTime;
if (null == sendCallback) {
try {
SendResult sendResult = MQClientAPIImpl.this.processSendResponse(brokerName, msg, response, addr);
if (context != null && sendResult != null) {
context.setSendResult(sendResult);
context.getProducer().executeSendMessageHookAfter(context);
}
} catch (Throwable e) {
}
producer.updateFaultItem(brokerName, System.currentTimeMillis() - beginStartTime, false, true);
return;
}
try {
SendResult sendResult = MQClientAPIImpl.this.processSendResponse(brokerName, msg, response, addr);
assert sendResult != null;
if (context != null) {
context.setSendResult(sendResult);
context.getProducer().executeSendMessageHookAfter(context);
}
try {
sendCallback.onSuccess(sendResult);
} catch (Throwable e) {
}
producer.updateFaultItem(brokerName, System.currentTimeMillis() - beginStartTime, false, true);
} catch (Exception e) {
producer.updateFaultItem(brokerName, System.currentTimeMillis() - beginStartTime, true, true);
onExceptionImpl(brokerName, msg, timeoutMillis - cost, request, sendCallback, topicPublishInfo, instance,
retryTimesWhenSendFailed, times, e, context, false, producer);
}
}
@Override
public void operationFail(Throwable throwable) {
producer.updateFaultItem(brokerName, System.currentTimeMillis() - beginStartTime, true, true);
long cost = System.currentTimeMillis() - beginStartTime;
if (throwable instanceof RemotingSendRequestException) {
MQClientException ex = new MQClientException("send request failed", throwable);
onExceptionImpl(brokerName, msg, timeoutMillis - cost, request, sendCallback, topicPublishInfo, instance,
retryTimesWhenSendFailed, times, ex, context, true, producer);
} else if (throwable instanceof RemotingTimeoutException) {
MQClientException ex = new MQClientException("wait response timeout, cost=" + cost, throwable);
onExceptionImpl(brokerName, msg, timeoutMillis - cost, request, sendCallback, topicPublishInfo, instance,
retryTimesWhenSendFailed, times, ex, context, true, producer);
} else {
MQClientException ex = new MQClientException("unknown reason", throwable);
boolean needRetry = !(throwable instanceof RemotingTooMuchRequestException);
onExceptionImpl(brokerName, msg, timeoutMillis - cost, request, sendCallback, topicPublishInfo, instance,
retryTimesWhenSendFailed, times, ex, context, needRetry, producer);
}
}
});
} catch (Exception ex) {
long cost = System.currentTimeMillis() - beginStartTime;
producer.updateFaultItem(brokerName, cost, true, false);
onExceptionImpl(brokerName, msg, timeoutMillis - cost, request, sendCallback, topicPublishInfo, instance,
retryTimesWhenSendFailed, times, ex, context, true, producer);
}
}
private void onExceptionImpl(final String brokerName,
final Message msg,
final long timeoutMillis,
final RemotingCommand request,
final SendCallback sendCallback,
final TopicPublishInfo topicPublishInfo,
final MQClientInstance instance,
final int timesTotal,
final AtomicInteger curTimes,
final Exception e,
final SendMessageContext context,
final boolean needRetry,
final DefaultMQProducerImpl producer
) {
int tmp = curTimes.incrementAndGet();
if (needRetry && tmp <= timesTotal && timeoutMillis > 0) {
String retryBrokerName = brokerName;//by default, it will send to the same broker
if (topicPublishInfo != null) { //select one message queue accordingly, in order to determine which broker to send
MessageQueue mqChosen = producer.selectOneMessageQueue(topicPublishInfo, brokerName, false);
retryBrokerName = instance.getBrokerNameFromMessageQueue(mqChosen);
}
String addr = instance.findBrokerAddressInPublish(retryBrokerName);
log.warn("async send msg by retry {} times. topic={}, brokerAddr={}, brokerName={}", tmp, msg.getTopic(), addr,
retryBrokerName, e);
request.setOpaque(RemotingCommand.createNewRequestId());
sendMessageAsync(addr, retryBrokerName, msg, timeoutMillis, request, sendCallback, topicPublishInfo, instance,
timesTotal, curTimes, context, producer);
} else {
if (context != null) {
context.setException(e);
context.getProducer().executeSendMessageHookAfter(context);
}
try {
sendCallback.onException(e);
} catch (Exception ignored) {
}
}
}
protected SendResult processSendResponse(
final String brokerName,
final Message msg,
final RemotingCommand response,
final String addr
) throws MQBrokerException, RemotingCommandException {
SendStatus sendStatus;
switch (response.getCode()) {
case ResponseCode.FLUSH_DISK_TIMEOUT: {
sendStatus = SendStatus.FLUSH_DISK_TIMEOUT;
break;
}
case ResponseCode.FLUSH_SLAVE_TIMEOUT: {
sendStatus = SendStatus.FLUSH_SLAVE_TIMEOUT;
break;
}
case ResponseCode.SLAVE_NOT_AVAILABLE: {
sendStatus = SendStatus.SLAVE_NOT_AVAILABLE;
break;
}
case ResponseCode.SUCCESS: {
sendStatus = SendStatus.SEND_OK;
break;
}
default: {
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
}
SendMessageResponseHeader responseHeader =
(SendMessageResponseHeader) response.decodeCommandCustomHeader(SendMessageResponseHeader.class);
//If namespace not null , reset Topic without namespace.
String topic = msg.getTopic();
if (StringUtils.isNotEmpty(this.clientConfig.getNamespace())) {
topic = NamespaceUtil.withoutNamespace(topic, this.clientConfig.getNamespace());
}
MessageQueue messageQueue = new MessageQueue(topic, brokerName, responseHeader.getQueueId());
String uniqMsgId = MessageClientIDSetter.getUniqID(msg);
if (msg instanceof MessageBatch && responseHeader.getBatchUniqId() == null) {
// This means it is not an inner batch
StringBuilder sb = new StringBuilder();
for (Message message : (MessageBatch) msg) {
sb.append(sb.length() == 0 ? "" : ",").append(MessageClientIDSetter.getUniqID(message));
}
uniqMsgId = sb.toString();
}
SendResult sendResult = new SendResult(sendStatus,
uniqMsgId,
responseHeader.getMsgId(), messageQueue, responseHeader.getQueueOffset());
sendResult.setTransactionId(responseHeader.getTransactionId());
sendResult.setRecallHandle(responseHeader.getRecallHandle());
String regionId = response.getExtFields().get(MessageConst.PROPERTY_MSG_REGION);
if (regionId == null || regionId.isEmpty()) {
regionId = MixAll.DEFAULT_TRACE_REGION_ID;
}
sendResult.setRegionId(regionId);
String traceOn = response.getExtFields().get(MessageConst.PROPERTY_TRACE_SWITCH);
sendResult.setTraceOn(!Boolean.FALSE.toString().equals(traceOn));
return sendResult;
}
public PullResult pullMessage(
final String addr,
final PullMessageRequestHeader requestHeader,
final long timeoutMillis,
final CommunicationMode communicationMode,
final PullCallback pullCallback
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request;
if (PullSysFlag.hasLitePullFlag(requestHeader.getSysFlag())) {
request = RemotingCommand.createRequestCommand(RequestCode.LITE_PULL_MESSAGE, requestHeader);
} else {
request = RemotingCommand.createRequestCommand(RequestCode.PULL_MESSAGE, requestHeader);
}
switch (communicationMode) {
case ONEWAY:
assert false;
return null;
case ASYNC:
this.pullMessageAsync(addr, request, timeoutMillis, pullCallback);
return null;
case SYNC:
return this.pullMessageSync(addr, request, timeoutMillis);
default:
assert false;
break;
}
return null;
}
public void popMessageAsync(
final String brokerName, final String addr, final PopMessageRequestHeader requestHeader,
final long timeoutMillis, final PopCallback popCallback
) throws RemotingException, InterruptedException {
final RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.POP_MESSAGE, requestHeader);
this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
}
@Override
public void operationSucceed(RemotingCommand response) {
try {
PopResult popResult = MQClientAPIImpl.this.processPopResponse(brokerName, response, requestHeader.getTopic(), requestHeader);
popCallback.onSuccess(popResult);
} catch (Exception e) {
popCallback.onException(e);
}
}
@Override
public void operationFail(Throwable throwable) {
popCallback.onException(throwable);
}
});
}
public void ackMessageAsync(
final String addr,
final long timeOut,
final AckCallback ackCallback,
final AckMessageRequestHeader requestHeader
) throws RemotingException, MQBrokerException, InterruptedException {
ackMessageAsync(addr, timeOut, ackCallback, requestHeader, null);
}
public void batchAckMessageAsync(
final String addr,
final long timeOut,
final AckCallback ackCallback,
final String topic,
final String consumerGroup,
final List<String> extraInfoList
) throws RemotingException, MQBrokerException, InterruptedException {
String brokerName = null;
Map<String, BatchAck> batchAckMap = new HashMap<>();
for (String extraInfo : extraInfoList) {
String[] extraInfoData = ExtraInfoUtil.split(extraInfo);
if (brokerName == null) {
brokerName = ExtraInfoUtil.getBrokerName(extraInfoData);
}
String mergeKey = ExtraInfoUtil.getRetry(extraInfoData) + "@" +
ExtraInfoUtil.getQueueId(extraInfoData) + "@" +
ExtraInfoUtil.getCkQueueOffset(extraInfoData) + "@" +
ExtraInfoUtil.getPopTime(extraInfoData);
BatchAck bAck = batchAckMap.computeIfAbsent(mergeKey, k -> {
BatchAck newBatchAck = new BatchAck();
newBatchAck.setConsumerGroup(consumerGroup);
newBatchAck.setTopic(topic);
newBatchAck.setRetry(ExtraInfoUtil.getRetry(extraInfoData));
newBatchAck.setStartOffset(ExtraInfoUtil.getCkQueueOffset(extraInfoData));
newBatchAck.setQueueId(ExtraInfoUtil.getQueueId(extraInfoData));
newBatchAck.setReviveQueueId(ExtraInfoUtil.getReviveQid(extraInfoData));
newBatchAck.setPopTime(ExtraInfoUtil.getPopTime(extraInfoData));
newBatchAck.setInvisibleTime(ExtraInfoUtil.getInvisibleTime(extraInfoData));
newBatchAck.setBitSet(new BitSet());
return newBatchAck;
});
bAck.getBitSet().set((int) (ExtraInfoUtil.getQueueOffset(extraInfoData) - ExtraInfoUtil.getCkQueueOffset(extraInfoData)));
}
BatchAckMessageRequestBody requestBody = new BatchAckMessageRequestBody();
requestBody.setBrokerName(brokerName);
requestBody.setAcks(new ArrayList<>(batchAckMap.values()));
batchAckMessageAsync(addr, timeOut, ackCallback, requestBody);
}
public void batchAckMessageAsync(
final String addr,
final long timeOut,
final AckCallback ackCallback,
final BatchAckMessageRequestBody requestBody
) throws RemotingException, MQBrokerException, InterruptedException {
ackMessageAsync(addr, timeOut, ackCallback, null, requestBody);
}
protected void ackMessageAsync(
final String addr,
final long timeOut,
final AckCallback ackCallback,
final AckMessageRequestHeader requestHeader,
final BatchAckMessageRequestBody requestBody
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request;
if (requestHeader != null) {
request = RemotingCommand.createRequestCommand(RequestCode.ACK_MESSAGE, requestHeader);
} else {
request = RemotingCommand.createRequestCommand(RequestCode.BATCH_ACK_MESSAGE, null);
if (requestBody != null) {
request.setBody(requestBody.encode());
}
}
this.remotingClient.invokeAsync(addr, request, timeOut, new InvokeCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
}
@Override
public void operationSucceed(RemotingCommand response) {
AckResult ackResult = new AckResult();
if (ResponseCode.SUCCESS == response.getCode()) {
ackResult.setStatus(AckStatus.OK);
} else {
ackResult.setStatus(AckStatus.NO_EXIST);
}
ackCallback.onSuccess(ackResult);
}
@Override
public void operationFail(Throwable throwable) {
ackCallback.onException(throwable);
}
});
}
public void changeInvisibleTimeAsync(//
final String brokerName,
final String addr, //
final ChangeInvisibleTimeRequestHeader requestHeader,//
final long timeoutMillis,
final AckCallback ackCallback
) throws RemotingException, MQBrokerException, InterruptedException {
final RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CHANGE_MESSAGE_INVISIBLETIME, requestHeader);
this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
}
@Override
public void operationSucceed(RemotingCommand response) {
try {
ChangeInvisibleTimeResponseHeader responseHeader = (ChangeInvisibleTimeResponseHeader) response.decodeCommandCustomHeader(ChangeInvisibleTimeResponseHeader.class);
AckResult ackResult = new AckResult();
if (ResponseCode.SUCCESS == response.getCode()) {
ackResult.setStatus(AckStatus.OK);
ackResult.setPopTime(responseHeader.getPopTime());
ackResult.setExtraInfo(ExtraInfoUtil
.buildExtraInfo(requestHeader.getOffset(), responseHeader.getPopTime(), responseHeader.getInvisibleTime(),
responseHeader.getReviveQid(), requestHeader.getTopic(), brokerName, requestHeader.getQueueId()) + MessageConst.KEY_SEPARATOR
+ requestHeader.getOffset());
} else {
ackResult.setStatus(AckStatus.NO_EXIST);
}
ackCallback.onSuccess(ackResult);
} catch (Exception e) {
ackCallback.onException(e);
}
}
@Override
public void operationFail(Throwable throwable) {
ackCallback.onException(throwable);
}
});
}
private void pullMessageAsync(
final String addr,
final RemotingCommand request,
final long timeoutMillis,
final PullCallback pullCallback
) throws RemotingException, InterruptedException {
this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
}
@Override
public void operationSucceed(RemotingCommand response) {
try {
PullResult pullResult = MQClientAPIImpl.this.processPullResponse(response, addr);
pullCallback.onSuccess(pullResult);
} catch (Exception e) {
pullCallback.onException(e);
}
}
@Override
public void operationFail(Throwable throwable) {
pullCallback.onException(throwable);
}
});
}
private PullResult pullMessageSync(
final String addr,
final RemotingCommand request,
final long timeoutMillis
) throws RemotingException, InterruptedException, MQBrokerException {
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
return this.processPullResponse(response, addr);
}
private PullResult processPullResponse(
final RemotingCommand response,
final String addr) throws MQBrokerException, RemotingCommandException {
PullStatus pullStatus = PullStatus.NO_NEW_MSG;
switch (response.getCode()) {
case ResponseCode.SUCCESS:
pullStatus = PullStatus.FOUND;
break;
case ResponseCode.PULL_NOT_FOUND:
pullStatus = PullStatus.NO_NEW_MSG;
break;
case ResponseCode.PULL_RETRY_IMMEDIATELY:
pullStatus = PullStatus.NO_MATCHED_MSG;
break;
case ResponseCode.PULL_OFFSET_MOVED:
pullStatus = PullStatus.OFFSET_ILLEGAL;
break;
default:
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
PullMessageResponseHeader responseHeader =
(PullMessageResponseHeader) response.decodeCommandCustomHeader(PullMessageResponseHeader.class);
return new PullResultExt(pullStatus, responseHeader.getNextBeginOffset(), responseHeader.getMinOffset(),
responseHeader.getMaxOffset(), null, responseHeader.getSuggestWhichBrokerId(), response.getBody(), responseHeader.getOffsetDelta());
}
private PopResult processPopResponse(final String brokerName, final RemotingCommand response, String topic,
CommandCustomHeader requestHeader) throws MQBrokerException, RemotingCommandException {
PopStatus popStatus = PopStatus.NO_NEW_MSG;
List<MessageExt> msgFoundList = null;
switch (response.getCode()) {
case ResponseCode.SUCCESS:
popStatus = PopStatus.FOUND;
ByteBuffer byteBuffer = ByteBuffer.wrap(response.getBody());
msgFoundList = MessageDecoder.decodesBatch(
byteBuffer,
clientConfig.isDecodeReadBody(),
clientConfig.isDecodeDecompressBody(),
true);
break;
case ResponseCode.POLLING_FULL:
popStatus = PopStatus.POLLING_FULL;
break;
case ResponseCode.POLLING_TIMEOUT:
popStatus = PopStatus.POLLING_NOT_FOUND;
break;
case ResponseCode.PULL_NOT_FOUND:
popStatus = PopStatus.POLLING_NOT_FOUND;
break;
default:
throw new MQBrokerException(response.getCode(), response.getRemark());
}
PopResult popResult = new PopResult(popStatus, msgFoundList);
PopMessageResponseHeader responseHeader = (PopMessageResponseHeader) response.decodeCommandCustomHeader(PopMessageResponseHeader.class);
popResult.setRestNum(responseHeader.getRestNum());
if (popStatus != PopStatus.FOUND) {
return popResult;
}
// it is a pop command if pop time greater than 0, we should set the check point info to extraInfo field
Map<String, Long> startOffsetInfo = null;
Map<String, List<Long>> msgOffsetInfo = null;
Map<String, Integer> orderCountInfo = null;
if (requestHeader instanceof PopMessageRequestHeader) {
popResult.setInvisibleTime(responseHeader.getInvisibleTime());
popResult.setPopTime(responseHeader.getPopTime());
startOffsetInfo = ExtraInfoUtil.parseStartOffsetInfo(responseHeader.getStartOffsetInfo());
msgOffsetInfo = ExtraInfoUtil.parseMsgOffsetInfo(responseHeader.getMsgOffsetInfo());
orderCountInfo = ExtraInfoUtil.parseOrderCountInfo(responseHeader.getOrderCountInfo());
}
Map<String/*topicMark@queueId*/, List<Long>/*msg queueOffset*/> sortMap
= buildQueueOffsetSortedMap(topic, msgFoundList);
Map<String, String> map = new HashMap<>(5);
for (MessageExt messageExt : msgFoundList) {
if (requestHeader instanceof PopMessageRequestHeader) {
if (startOffsetInfo == null) {
// we should set the check point info to extraInfo field , if the command is popMsg
// find pop ck offset
String key = messageExt.getTopic() + messageExt.getQueueId();
if (!map.containsKey(messageExt.getTopic() + messageExt.getQueueId())) {
map.put(key, ExtraInfoUtil.buildExtraInfo(messageExt.getQueueOffset(), responseHeader.getPopTime(), responseHeader.getInvisibleTime(), responseHeader.getReviveQid(),
messageExt.getTopic(), brokerName, messageExt.getQueueId()));
}
messageExt.getProperties().put(MessageConst.PROPERTY_POP_CK, map.get(key) + MessageConst.KEY_SEPARATOR + messageExt.getQueueOffset());
} else {
if (messageExt.getProperty(MessageConst.PROPERTY_POP_CK) == null) {
final String queueIdKey;
final String queueOffsetKey;
final int index;
final Long msgQueueOffset;
if (MixAll.isLmq(topic) && messageExt.getReconsumeTimes() == 0 && StringUtils.isNotEmpty(
messageExt.getProperty(MessageConst.PROPERTY_INNER_MULTI_DISPATCH))) {
// process LMQ
String[] queues = messageExt.getProperty(MessageConst.PROPERTY_INNER_MULTI_DISPATCH)
.split(MixAll.LMQ_DISPATCH_SEPARATOR);
String[] queueOffsets = messageExt.getProperty(MessageConst.PROPERTY_INNER_MULTI_QUEUE_OFFSET)
.split(MixAll.LMQ_DISPATCH_SEPARATOR);
long offset = Long.parseLong(queueOffsets[ArrayUtils.indexOf(queues, topic)]);
// LMQ topic has only 1 queue, which queue id is 0
queueIdKey = ExtraInfoUtil.getStartOffsetInfoMapKey(topic, MixAll.LMQ_QUEUE_ID);
queueOffsetKey = ExtraInfoUtil.getQueueOffsetMapKey(topic, MixAll.LMQ_QUEUE_ID, offset);
index = sortMap.get(queueIdKey).indexOf(offset);
msgQueueOffset = msgOffsetInfo.get(queueIdKey).get(index);
if (msgQueueOffset != offset) {
log.warn("Queue offset[{}] of msg is strange, not equal to the stored in msg, {}",
msgQueueOffset, messageExt);
}
messageExt.getProperties().put(MessageConst.PROPERTY_POP_CK,
ExtraInfoUtil.buildExtraInfo(startOffsetInfo.get(queueIdKey), responseHeader.getPopTime(), responseHeader.getInvisibleTime(),
responseHeader.getReviveQid(), topic, brokerName, 0, msgQueueOffset)
);
} else {
queueIdKey = ExtraInfoUtil.getStartOffsetInfoMapKey(messageExt.getTopic(), messageExt.getQueueId());
queueOffsetKey = ExtraInfoUtil.getQueueOffsetMapKey(messageExt.getTopic(), messageExt.getQueueId(), messageExt.getQueueOffset());
index = sortMap.get(queueIdKey).indexOf(messageExt.getQueueOffset());
msgQueueOffset = msgOffsetInfo.get(queueIdKey).get(index);
if (msgQueueOffset != messageExt.getQueueOffset()) {
log.warn("Queue offset[{}] of msg is strange, not equal to the stored in msg, {}", msgQueueOffset, messageExt);
}
messageExt.getProperties().put(MessageConst.PROPERTY_POP_CK,
ExtraInfoUtil.buildExtraInfo(startOffsetInfo.get(queueIdKey), responseHeader.getPopTime(), responseHeader.getInvisibleTime(),
responseHeader.getReviveQid(), messageExt.getTopic(), brokerName, messageExt.getQueueId(), msgQueueOffset)
);
}
if (((PopMessageRequestHeader) requestHeader).isOrder() && orderCountInfo != null) {
Integer count = orderCountInfo.get(queueOffsetKey);
if (count == null) {
count = orderCountInfo.get(queueIdKey);
}
if (count != null && count > 0) {
messageExt.setReconsumeTimes(count);
}
}
}
}
messageExt.getProperties().computeIfAbsent(
MessageConst.PROPERTY_FIRST_POP_TIME, k -> String.valueOf(responseHeader.getPopTime()));
}
messageExt.setBrokerName(brokerName);
messageExt.setTopic(NamespaceUtil.withoutNamespace(topic, this.clientConfig.getNamespace()));
}
return popResult;
}
/**
* Build queue offset sorted map
*
* @param topic pop consumer topic
* @param msgFoundList popped message list
* @return sorted map, key is topicMark@queueId, value is sorted msg queueOffset list
*/
private static Map<String, List<Long>> buildQueueOffsetSortedMap(String topic, List<MessageExt> msgFoundList) {
Map<String/*topicMark@queueId*/, List<Long>/*msg queueOffset*/> sortMap = new HashMap<>(16);
for (MessageExt messageExt : msgFoundList) {
final String key;
if (MixAll.isLmq(topic) && messageExt.getReconsumeTimes() == 0
&& StringUtils.isNotEmpty(messageExt.getProperty(MessageConst.PROPERTY_INNER_MULTI_DISPATCH))) {
// process LMQ
String[] queues = messageExt.getProperty(MessageConst.PROPERTY_INNER_MULTI_DISPATCH)
.split(MixAll.LMQ_DISPATCH_SEPARATOR);
String[] queueOffsets = messageExt.getProperty(MessageConst.PROPERTY_INNER_MULTI_QUEUE_OFFSET)
.split(MixAll.LMQ_DISPATCH_SEPARATOR);
// LMQ topic has only 1 queue, which queue id is 0
key = ExtraInfoUtil.getStartOffsetInfoMapKey(topic, MixAll.LMQ_QUEUE_ID);
sortMap.putIfAbsent(key, new ArrayList<>(4));
sortMap.get(key).add(Long.parseLong(queueOffsets[ArrayUtils.indexOf(queues, topic)]));
continue;
}
// Value of POP_CK is used to determine whether it is a pop retry,
// cause topic could be rewritten by broker.
key = ExtraInfoUtil.getStartOffsetInfoMapKey(messageExt.getTopic(),
messageExt.getProperty(MessageConst.PROPERTY_POP_CK), messageExt.getQueueId());
if (!sortMap.containsKey(key)) {
sortMap.put(key, new ArrayList<>(4));
}
sortMap.get(key).add(messageExt.getQueueOffset());
}
return sortMap;
}
public MessageExt viewMessage(final String addr, final String topic, final long phyoffset, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
ViewMessageRequestHeader requestHeader = new ViewMessageRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setOffset(phyoffset);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.VIEW_MESSAGE_BY_ID, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
ByteBuffer byteBuffer = ByteBuffer.wrap(response.getBody());
MessageExt messageExt = MessageDecoder.clientDecode(byteBuffer, true);
//If namespace not null , reset Topic without namespace.
if (StringUtils.isNotEmpty(this.clientConfig.getNamespace())) {
messageExt.setTopic(NamespaceUtil.withoutNamespace(messageExt.getTopic(), this.clientConfig.getNamespace()));
}
return messageExt;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
@Deprecated
public long searchOffset(final String addr, final String topic, final int queueId, final long timestamp,
final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
SearchOffsetRequestHeader requestHeader = new SearchOffsetRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setQueueId(queueId);
requestHeader.setTimestamp(timestamp);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.SEARCH_OFFSET_BY_TIMESTAMP, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
SearchOffsetResponseHeader responseHeader =
(SearchOffsetResponseHeader) response.decodeCommandCustomHeader(SearchOffsetResponseHeader.class);
return responseHeader.getOffset();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public long searchOffset(final String addr, final MessageQueue messageQueue, final long timestamp,
final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
// default return lower boundary offset when there are more than one offsets.
return searchOffset(addr, messageQueue, timestamp, BoundaryType.LOWER, timeoutMillis);
}
public long searchOffset(final String addr, final MessageQueue messageQueue, final long timestamp,
final BoundaryType boundaryType, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
SearchOffsetRequestHeader requestHeader = new SearchOffsetRequestHeader();
requestHeader.setTopic(messageQueue.getTopic());
requestHeader.setQueueId(messageQueue.getQueueId());
requestHeader.setBrokerName(messageQueue.getBrokerName());
requestHeader.setTimestamp(timestamp);
requestHeader.setBoundaryType(boundaryType);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.SEARCH_OFFSET_BY_TIMESTAMP, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
SearchOffsetResponseHeader responseHeader =
(SearchOffsetResponseHeader) response.decodeCommandCustomHeader(SearchOffsetResponseHeader.class);
return responseHeader.getOffset();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public long getMaxOffset(final String addr, final MessageQueue messageQueue, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
GetMaxOffsetRequestHeader requestHeader = new GetMaxOffsetRequestHeader();
requestHeader.setTopic(messageQueue.getTopic());
requestHeader.setQueueId(messageQueue.getQueueId());
requestHeader.setBrokerName(messageQueue.getBrokerName());
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_MAX_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
GetMaxOffsetResponseHeader responseHeader =
(GetMaxOffsetResponseHeader) response.decodeCommandCustomHeader(GetMaxOffsetResponseHeader.class);
return responseHeader.getOffset();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public List<String> getConsumerIdListByGroup(
final String addr,
final String consumerGroup,
final long timeoutMillis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException,
MQBrokerException, InterruptedException {
GetConsumerListByGroupRequestHeader requestHeader = new GetConsumerListByGroupRequestHeader();
requestHeader.setConsumerGroup(consumerGroup);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUMER_LIST_BY_GROUP, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (response.getBody() != null) {
GetConsumerListByGroupResponseBody body =
GetConsumerListByGroupResponseBody.decode(response.getBody(), GetConsumerListByGroupResponseBody.class);
return body.getConsumerIdList();
}
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public long getMinOffset(final String addr, final MessageQueue messageQueue, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
GetMinOffsetRequestHeader requestHeader = new GetMinOffsetRequestHeader();
requestHeader.setTopic(messageQueue.getTopic());
requestHeader.setQueueId(messageQueue.getQueueId());
requestHeader.setBrokerName(messageQueue.getBrokerName());
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_MIN_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
GetMinOffsetResponseHeader responseHeader =
(GetMinOffsetResponseHeader) response.decodeCommandCustomHeader(GetMinOffsetResponseHeader.class);
return responseHeader.getOffset();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public long getEarliestMsgStoretime(final String addr, final MessageQueue mq, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
GetEarliestMsgStoretimeRequestHeader requestHeader = new GetEarliestMsgStoretimeRequestHeader();
requestHeader.setTopic(mq.getTopic());
requestHeader.setQueueId(mq.getQueueId());
requestHeader.setBrokerName(mq.getBrokerName());
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_EARLIEST_MSG_STORETIME, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
GetEarliestMsgStoretimeResponseHeader responseHeader =
(GetEarliestMsgStoretimeResponseHeader) response.decodeCommandCustomHeader(GetEarliestMsgStoretimeResponseHeader.class);
return responseHeader.getTimestamp();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public long queryConsumerOffset(
final String addr,
final QueryConsumerOffsetRequestHeader requestHeader,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_CONSUMER_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
QueryConsumerOffsetResponseHeader responseHeader =
(QueryConsumerOffsetResponseHeader) response.decodeCommandCustomHeader(QueryConsumerOffsetResponseHeader.class);
return responseHeader.getOffset();
}
case ResponseCode.QUERY_NOT_FOUND: {
throw new OffsetNotFoundException(response.getCode(), response.getRemark(), addr);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public void updateConsumerOffset(
final String addr,
final UpdateConsumerOffsetRequestHeader requestHeader,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_CONSUMER_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public void updateConsumerOffsetOneway(
final String addr,
final UpdateConsumerOffsetRequestHeader requestHeader,
final long timeoutMillis
) throws RemotingConnectException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException,
InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_CONSUMER_OFFSET, requestHeader);
this.remotingClient.invokeOneway(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
}
public int sendHeartbeat(
final String addr,
final HeartbeatData heartbeatData,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.HEART_BEAT, new HeartbeatRequestHeader());
request.setLanguage(clientConfig.getLanguage());
request.setBody(heartbeatData.encode());
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return response.getVersion();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public HeartbeatV2Result sendHeartbeatV2(
final String addr,
final HeartbeatData heartbeatData,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.HEART_BEAT, new HeartbeatRequestHeader());
request.setLanguage(clientConfig.getLanguage());
request.setBody(heartbeatData.encode());
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (response.getExtFields() != null) {
return new HeartbeatV2Result(response.getVersion(), Boolean.parseBoolean(response.getExtFields().get(MixAll.IS_SUB_CHANGE)), Boolean.parseBoolean(response.getExtFields().get(MixAll.IS_SUPPORT_HEART_BEAT_V2)));
}
return new HeartbeatV2Result(response.getVersion(), false, false);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void unregisterClient(
final String addr,
final String clientID,
final String producerGroup,
final String consumerGroup,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
final UnregisterClientRequestHeader requestHeader = new UnregisterClientRequestHeader();
requestHeader.setClientID(clientID);
requestHeader.setProducerGroup(producerGroup);
requestHeader.setConsumerGroup(consumerGroup);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UNREGISTER_CLIENT, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public void endTransactionOneway(
final String addr,
final EndTransactionRequestHeader requestHeader,
final String remark,
final long timeoutMillis
) throws RemotingException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.END_TRANSACTION, requestHeader);
request.setRemark(remark);
this.remotingClient.invokeOneway(addr, request, timeoutMillis);
}
public void queryMessage(
final String addr,
final QueryMessageRequestHeader requestHeader,
final long timeoutMillis,
final InvokeCallback invokeCallback,
final Boolean isUniqueKey
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_MESSAGE, requestHeader);
request.addExtField(MixAll.UNIQUE_MSG_QUERY_FLAG, isUniqueKey.toString());
this.remotingClient.invokeAsync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis,
invokeCallback);
}
public boolean registerClient(final String addr, final HeartbeatData heartbeat, final long timeoutMillis)
throws RemotingException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.HEART_BEAT, new HeartbeatRequestHeader());
request.setBody(heartbeat.encode());
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
return response.getCode() == ResponseCode.SUCCESS;
}
public void consumerSendMessageBack(
final String addr,
final String brokerName,
final MessageExt msg,
final String consumerGroup,
final int delayLevel,
final long timeoutMillis,
final int maxConsumeRetryTimes
) throws RemotingException, MQBrokerException, InterruptedException {
ConsumerSendMsgBackRequestHeader requestHeader = new ConsumerSendMsgBackRequestHeader();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CONSUMER_SEND_MSG_BACK, requestHeader);
requestHeader.setGroup(consumerGroup);
requestHeader.setOriginTopic(msg.getTopic());
requestHeader.setOffset(msg.getCommitLogOffset());
requestHeader.setDelayLevel(delayLevel);
requestHeader.setOriginMsgId(msg.getMsgId());
requestHeader.setMaxReconsumeTimes(maxConsumeRetryTimes);
requestHeader.setBrokerName(brokerName);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public Set<MessageQueue> lockBatchMQ(
final String addr,
final LockBatchRequestBody requestBody,
final long timeoutMillis) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.LOCK_BATCH_MQ, new LockBatchMqRequestHeader());
request.setBody(requestBody.encode());
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
LockBatchResponseBody responseBody = LockBatchResponseBody.decode(response.getBody(), LockBatchResponseBody.class);
Set<MessageQueue> messageQueues = responseBody.getLockOKMQSet();
return messageQueues;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public void unlockBatchMQ(
final String addr,
final UnlockBatchRequestBody requestBody,
final long timeoutMillis,
final boolean oneway
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UNLOCK_BATCH_MQ, new UnlockBatchMqRequestHeader());
request.setBody(requestBody.encode());
if (oneway) {
this.remotingClient.invokeOneway(addr, request, timeoutMillis);
} else {
RemotingCommand response = this.remotingClient
.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
}
public TopicStatsTable getTopicStatsInfo(final String addr, final String topic,
final long timeoutMillis) throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
GetTopicStatsInfoRequestHeader requestHeader = new GetTopicStatsInfoRequestHeader();
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_TOPIC_STATS_INFO, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
TopicStatsTable topicStatsTable = TopicStatsTable.decode(response.getBody(), TopicStatsTable.class);
return topicStatsTable;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public ConsumeStats getConsumeStats(final String addr, final String consumerGroup, final long timeoutMillis)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException,
MQBrokerException {
return getConsumeStats(addr, consumerGroup, null, null, timeoutMillis);
}
public ConsumeStats getConsumeStats(final String addr, final String consumerGroup, final List<String> topicList,
final long timeoutMillis) throws RemotingSendRequestException, RemotingConnectException, RemotingTimeoutException, MQBrokerException, InterruptedException {
return getConsumeStats(addr, consumerGroup, null, topicList, timeoutMillis);
}
public ConsumeStats getConsumeStats(final String addr, final String consumerGroup, final String topic,
final long timeoutMillis) throws RemotingSendRequestException, RemotingConnectException, RemotingTimeoutException, MQBrokerException, InterruptedException {
return getConsumeStats(addr, consumerGroup, topic, null, timeoutMillis);
}
public ConsumeStats getConsumeStats(final String addr, final String consumerGroup, final String topic,
final List<String> topicList, final long timeoutMillis)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException,
MQBrokerException {
GetConsumeStatsRequestHeader requestHeader = new GetConsumeStatsRequestHeader();
requestHeader.setConsumerGroup(consumerGroup);
requestHeader.setTopic(topic);
requestHeader.updateTopicList(topicList);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUME_STATS, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
ConsumeStats consumeStats = ConsumeStats.decode(response.getBody(), ConsumeStats.class);
return consumeStats;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public ProducerConnection getProducerConnectionList(final String addr, final String producerGroup,
final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
GetProducerConnectionListRequestHeader requestHeader = new GetProducerConnectionListRequestHeader();
requestHeader.setProducerGroup(producerGroup);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_PRODUCER_CONNECTION_LIST, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return ProducerConnection.decode(response.getBody(), ProducerConnection.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public ProducerTableInfo getAllProducerInfo(final String addr, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
GetAllProducerInfoRequestHeader requestHeader = new GetAllProducerInfoRequestHeader();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_PRODUCER_INFO, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return ProducerTableInfo.decode(response.getBody(), ProducerTableInfo.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public ConsumerConnection getConsumerConnectionList(final String addr, final String consumerGroup,
final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
GetConsumerConnectionListRequestHeader requestHeader = new GetConsumerConnectionListRequestHeader();
requestHeader.setConsumerGroup(consumerGroup);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUMER_CONNECTION_LIST, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return ConsumerConnection.decode(response.getBody(), ConsumerConnection.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public KVTable getBrokerRuntimeInfo(final String addr, final long timeoutMillis) throws RemotingConnectException,
RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_RUNTIME_INFO, null);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return KVTable.decode(response.getBody(), KVTable.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public void addBroker(final String addr, final String brokerConfigPath, final long timeoutMillis)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
AddBrokerRequestHeader requestHeader = new AddBrokerRequestHeader();
requestHeader.setConfigPath(brokerConfigPath);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.ADD_BROKER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS:
return;
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void removeBroker(final String addr, String clusterName, String brokerName, long brokerId,
final long timeoutMillis)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
RemoveBrokerRequestHeader requestHeader = new RemoveBrokerRequestHeader();
requestHeader.setBrokerClusterName(clusterName);
requestHeader.setBrokerName(brokerName);
requestHeader.setBrokerId(brokerId);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.REMOVE_BROKER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS:
return;
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void updateBrokerConfig(final String addr, final Properties properties, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException, MQClientException, UnsupportedEncodingException {
Validators.checkBrokerConfig(properties);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_BROKER_CONFIG, null);
String str = MixAll.properties2String(properties);
if (str != null && str.length() > 0) {
request.setBody(str.getBytes(MixAll.DEFAULT_CHARSET));
RemotingCommand response = this.remotingClient
.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
}
public Properties getBrokerConfig(final String addr, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException, UnsupportedEncodingException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_CONFIG, null);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return MixAll.string2Properties(new String(response.getBody(), MixAll.DEFAULT_CHARSET));
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public void updateColdDataFlowCtrGroupConfig(final String addr, final Properties properties, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException, UnsupportedEncodingException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_COLD_DATA_FLOW_CTR_CONFIG, null);
String str = MixAll.properties2String(properties);
if (str != null && str.length() > 0) {
request.setBody(str.getBytes(MixAll.DEFAULT_CHARSET));
RemotingCommand response = this.remotingClient.invokeSync(
MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
}
public void removeColdDataFlowCtrGroupConfig(final String addr, final String consumerGroup, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException, UnsupportedEncodingException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.REMOVE_COLD_DATA_FLOW_CTR_CONFIG, null);
if (consumerGroup != null && consumerGroup.length() > 0) {
request.setBody(consumerGroup.getBytes(MixAll.DEFAULT_CHARSET));
RemotingCommand response = this.remotingClient.invokeSync(
MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
}
public String getColdDataFlowCtrInfo(final String addr, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException, UnsupportedEncodingException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_COLD_DATA_FLOW_CTR_INFO, null);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (null != response.getBody() && response.getBody().length > 0) {
return new String(response.getBody(), MixAll.DEFAULT_CHARSET);
}
return null;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public String setCommitLogReadAheadMode(final String addr, final String mode, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.SET_COMMITLOG_READ_MODE, null);
HashMap<String, String> extFields = new HashMap<>();
extFields.put(FIleReadaheadMode.READ_AHEAD_MODE, mode);
request.setExtFields(extFields);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (null != response.getRemark() && response.getRemark().length() > 0) {
return response.getRemark();
}
return null;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public ClusterInfo getBrokerClusterInfo(
final long timeoutMillis) throws InterruptedException, RemotingTimeoutException,
RemotingSendRequestException, RemotingConnectException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_CLUSTER_INFO, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return ClusterInfo.decode(response.getBody(), ClusterInfo.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public TopicRouteData getDefaultTopicRouteInfoFromNameServer(final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
return getTopicRouteInfoFromNameServer(TopicValidator.AUTO_CREATE_TOPIC_KEY_TOPIC, timeoutMillis, false);
}
public TopicRouteData getTopicRouteInfoFromNameServer(final String topic, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
return getTopicRouteInfoFromNameServer(topic, timeoutMillis, true);
}
public TopicRouteData getTopicRouteInfoFromNameServer(final String topic, final long timeoutMillis,
boolean allowTopicNotExist) throws MQClientException, InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException {
GetRouteInfoRequestHeader requestHeader = new GetRouteInfoRequestHeader();
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ROUTEINFO_BY_TOPIC, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.TOPIC_NOT_EXIST: {
if (allowTopicNotExist) {
log.warn("get Topic [{}] RouteInfoFromNameServer is not exist value", topic);
}
break;
}
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
return TopicRouteData.decode(body, TopicRouteData.class);
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public TopicList getTopicListFromNameServer(final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_TOPIC_LIST_FROM_NAMESERVER, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
return TopicList.decode(body, TopicList.class);
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public int wipeWritePermOfBroker(final String namesrvAddr, String brokerName,
final long timeoutMillis) throws RemotingCommandException,
RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQClientException {
WipeWritePermOfBrokerRequestHeader requestHeader = new WipeWritePermOfBrokerRequestHeader();
requestHeader.setBrokerName(brokerName);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.WIPE_WRITE_PERM_OF_BROKER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(namesrvAddr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
WipeWritePermOfBrokerResponseHeader responseHeader =
(WipeWritePermOfBrokerResponseHeader) response.decodeCommandCustomHeader(WipeWritePermOfBrokerResponseHeader.class);
return responseHeader.getWipeTopicCount();
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public int addWritePermOfBroker(final String nameSrvAddr, String brokerName, final long timeoutMillis)
throws RemotingCommandException,
RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQClientException {
AddWritePermOfBrokerRequestHeader requestHeader = new AddWritePermOfBrokerRequestHeader();
requestHeader.setBrokerName(brokerName);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.ADD_WRITE_PERM_OF_BROKER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(nameSrvAddr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
AddWritePermOfBrokerResponseHeader responseHeader =
(AddWritePermOfBrokerResponseHeader) response.decodeCommandCustomHeader(AddWritePermOfBrokerResponseHeader.class);
return responseHeader.getAddTopicCount();
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void deleteTopicInBroker(final String addr, final String topic, final long timeoutMillis)
throws RemotingException, InterruptedException, MQClientException {
DeleteTopicRequestHeader requestHeader = new DeleteTopicRequestHeader();
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_TOPIC_IN_BROKER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void deleteTopicInNameServer(final String addr, final String topic, final long timeoutMillis)
throws RemotingException, InterruptedException, MQClientException {
DeleteTopicFromNamesrvRequestHeader requestHeader = new DeleteTopicFromNamesrvRequestHeader();
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_TOPIC_IN_NAMESRV, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void deleteTopicInNameServer(final String addr, final String clusterName, final String topic,
final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
DeleteTopicFromNamesrvRequestHeader requestHeader = new DeleteTopicFromNamesrvRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setClusterName(clusterName);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_TOPIC_IN_NAMESRV, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void deleteSubscriptionGroup(final String addr, final String groupName, final boolean removeOffset,
final long timeoutMillis)
throws RemotingException, InterruptedException, MQClientException {
DeleteSubscriptionGroupRequestHeader requestHeader = new DeleteSubscriptionGroupRequestHeader();
requestHeader.setGroupName(groupName);
requestHeader.setCleanOffset(removeOffset);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_SUBSCRIPTIONGROUP, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public String getKVConfigValue(final String namespace, final String key, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
GetKVConfigRequestHeader requestHeader = new GetKVConfigRequestHeader();
requestHeader.setNamespace(namespace);
requestHeader.setKey(key);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_KV_CONFIG, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
GetKVConfigResponseHeader responseHeader =
(GetKVConfigResponseHeader) response.decodeCommandCustomHeader(GetKVConfigResponseHeader.class);
return responseHeader.getValue();
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void putKVConfigValue(final String namespace, final String key, final String value, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
PutKVConfigRequestHeader requestHeader = new PutKVConfigRequestHeader();
requestHeader.setNamespace(namespace);
requestHeader.setKey(key);
requestHeader.setValue(value);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.PUT_KV_CONFIG, requestHeader);
List<String> nameServerAddressList = this.remotingClient.getNameServerAddressList();
if (nameServerAddressList != null) {
RemotingCommand errResponse = null;
for (String namesrvAddr : nameServerAddressList) {
RemotingCommand response = this.remotingClient.invokeSync(namesrvAddr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
break;
}
default:
errResponse = response;
}
}
if (errResponse != null) {
throw new MQClientException(errResponse.getCode(), errResponse.getRemark());
}
}
}
public void deleteKVConfigValue(final String namespace, final String key, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
DeleteKVConfigRequestHeader requestHeader = new DeleteKVConfigRequestHeader();
requestHeader.setNamespace(namespace);
requestHeader.setKey(key);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_KV_CONFIG, requestHeader);
List<String> nameServerAddressList = this.remotingClient.getNameServerAddressList();
if (nameServerAddressList != null) {
RemotingCommand errResponse = null;
for (String namesrvAddr : nameServerAddressList) {
RemotingCommand response = this.remotingClient.invokeSync(namesrvAddr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
break;
}
default:
errResponse = response;
}
}
if (errResponse != null) {
throw new MQClientException(errResponse.getCode(), errResponse.getRemark());
}
}
}
public KVTable getKVListByNamespace(final String namespace, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
GetKVListByNamespaceRequestHeader requestHeader = new GetKVListByNamespaceRequestHeader();
requestHeader.setNamespace(namespace);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_KVLIST_BY_NAMESPACE, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return KVTable.decode(response.getBody(), KVTable.class);
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public Map<MessageQueue, Long> invokeBrokerToResetOffset(final String addr, final String topic, final String group,
final long timestamp, final boolean isForce, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
return invokeBrokerToResetOffset(addr, topic, group, timestamp, isForce, timeoutMillis, false);
}
public Map<MessageQueue, Long> invokeBrokerToResetOffset(final String addr, final String topic, final String group,
final long timestamp, int queueId, Long offset, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
ResetOffsetRequestHeader requestHeader = new ResetOffsetRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setGroup(group);
requestHeader.setQueueId(queueId);
requestHeader.setTimestamp(timestamp);
requestHeader.setOffset(offset);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.INVOKE_BROKER_TO_RESET_OFFSET,
requestHeader);
RemotingCommand response = remotingClient.invokeSync(
MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (null != response.getBody()) {
return ResetOffsetBody.decode(response.getBody(), ResetOffsetBody.class).getOffsetTable();
}
break;
}
case ResponseCode.TOPIC_NOT_EXIST:
case ResponseCode.SUBSCRIPTION_NOT_EXIST:
case ResponseCode.SYSTEM_ERROR:
log.warn("Invoke broker to reset offset error code={}, remark={}",
response.getCode(), response.getRemark());
break;
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public Map<MessageQueue, Long> invokeBrokerToResetOffset(final String addr, final String topic, final String group,
final long timestamp, final boolean isForce, final long timeoutMillis, boolean isC)
throws RemotingException, MQClientException, InterruptedException {
ResetOffsetRequestHeader requestHeader = new ResetOffsetRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setGroup(group);
requestHeader.setTimestamp(timestamp);
requestHeader.setForce(isForce);
// offset is -1 means offset is null
requestHeader.setOffset(-1L);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.INVOKE_BROKER_TO_RESET_OFFSET, requestHeader);
if (isC) {
request.setLanguage(LanguageCode.CPP);
}
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (response.getBody() != null) {
ResetOffsetBody body = ResetOffsetBody.decode(response.getBody(), ResetOffsetBody.class);
return body.getOffsetTable();
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public Map<String, Map<MessageQueue, Long>> invokeBrokerToGetConsumerStatus(final String addr, final String topic,
final String group,
final String clientAddr,
final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException {
GetConsumerStatusRequestHeader requestHeader = new GetConsumerStatusRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setGroup(group);
requestHeader.setClientAddr(clientAddr);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.INVOKE_BROKER_TO_GET_CONSUMER_STATUS, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (response.getBody() != null) {
GetConsumerStatusBody body = GetConsumerStatusBody.decode(response.getBody(), GetConsumerStatusBody.class);
return body.getConsumerTable();
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public GroupList queryTopicConsumeByWho(final String addr, final String topic, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
QueryTopicConsumeByWhoRequestHeader requestHeader = new QueryTopicConsumeByWhoRequestHeader();
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_TOPIC_CONSUME_BY_WHO, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
GroupList groupList = GroupList.decode(response.getBody(), GroupList.class);
return groupList;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public TopicList queryTopicsByConsumer(final String addr, final String group, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
QueryTopicsByConsumerRequestHeader requestHeader = new QueryTopicsByConsumerRequestHeader();
requestHeader.setGroup(group);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_TOPICS_BY_CONSUMER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
TopicList topicList = TopicList.decode(response.getBody(), TopicList.class);
return topicList;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public SubscriptionData querySubscriptionByConsumer(final String addr, final String group, final String topic,
final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
QuerySubscriptionByConsumerRequestHeader requestHeader = new QuerySubscriptionByConsumerRequestHeader();
requestHeader.setGroup(group);
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_SUBSCRIPTION_BY_CONSUMER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
QuerySubscriptionResponseBody subscriptionResponseBody =
QuerySubscriptionResponseBody.decode(response.getBody(), QuerySubscriptionResponseBody.class);
return subscriptionResponseBody.getSubscriptionData();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public List<QueueTimeSpan> queryConsumeTimeSpan(final String addr, final String topic, final String group,
final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
QueryConsumeTimeSpanRequestHeader requestHeader = new QueryConsumeTimeSpanRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setGroup(group);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_CONSUME_TIME_SPAN, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
QueryConsumeTimeSpanBody consumeTimeSpanBody = GroupList.decode(response.getBody(), QueryConsumeTimeSpanBody.class);
return consumeTimeSpanBody.getConsumeTimeSpanSet();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public TopicList getTopicsByCluster(final String cluster, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
GetTopicsByClusterRequestHeader requestHeader = new GetTopicsByClusterRequestHeader();
requestHeader.setCluster(cluster);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_TOPICS_BY_CLUSTER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(body, TopicList.class);
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public TopicList getSystemTopicList(
final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_SYSTEM_TOPIC_LIST_FROM_NS, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(response.getBody(), TopicList.class);
if (topicList.getTopicList() != null && !topicList.getTopicList().isEmpty()
&& !UtilAll.isBlank(topicList.getBrokerAddr())) {
TopicList tmp = getSystemTopicListFromBroker(topicList.getBrokerAddr(), timeoutMillis);
if (tmp.getTopicList() != null && !tmp.getTopicList().isEmpty()) {
topicList.getTopicList().addAll(tmp.getTopicList());
}
}
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public TopicList getSystemTopicListFromBroker(final String addr, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_SYSTEM_TOPIC_LIST_FROM_BROKER, null);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(body, TopicList.class);
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public boolean cleanExpiredConsumeQueue(final String addr,
long timeoutMillis) throws MQClientException, RemotingConnectException,
RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLEAN_EXPIRED_CONSUMEQUEUE, null);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return true;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public boolean deleteExpiredCommitLog(final String addr, long timeoutMillis) throws MQClientException,
RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_EXPIRED_COMMITLOG, null);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return true;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public boolean cleanUnusedTopicByAddr(final String addr,
long timeoutMillis) throws MQClientException, RemotingConnectException,
RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLEAN_UNUSED_TOPIC, null);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return true;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public ConsumerRunningInfo getConsumerRunningInfo(final String addr, String consumerGroup, String clientId,
boolean jstack,
final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException {
GetConsumerRunningInfoRequestHeader requestHeader = new GetConsumerRunningInfoRequestHeader();
requestHeader.setConsumerGroup(consumerGroup);
requestHeader.setClientId(clientId);
requestHeader.setJstackEnable(jstack);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUMER_RUNNING_INFO, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
ConsumerRunningInfo info = ConsumerRunningInfo.decode(body, ConsumerRunningInfo.class);
return info;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public ConsumeMessageDirectlyResult consumeMessageDirectly(final String addr,
String consumerGroup,
String clientId,
String topic,
String msgId,
final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException {
ConsumeMessageDirectlyResultRequestHeader requestHeader = new ConsumeMessageDirectlyResultRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setConsumerGroup(consumerGroup);
requestHeader.setClientId(clientId);
requestHeader.setMsgId(msgId);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CONSUME_MESSAGE_DIRECTLY, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
ConsumeMessageDirectlyResult info = ConsumeMessageDirectlyResult.decode(body, ConsumeMessageDirectlyResult.class);
return info;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public Map<Integer, Long> queryCorrectionOffset(final String addr, final String topic, final String group,
Set<String> filterGroup,
long timeoutMillis) throws MQClientException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException,
InterruptedException {
QueryCorrectionOffsetHeader requestHeader = new QueryCorrectionOffsetHeader();
requestHeader.setCompareGroup(group);
requestHeader.setTopic(topic);
if (filterGroup != null) {
StringBuilder sb = new StringBuilder();
String splitor = "";
for (String s : filterGroup) {
sb.append(splitor).append(s);
splitor = ",";
}
requestHeader.setFilterGroups(sb.toString());
}
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_CORRECTION_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (response.getBody() != null) {
QueryCorrectionOffsetBody body = QueryCorrectionOffsetBody.decode(response.getBody(), QueryCorrectionOffsetBody.class);
return body.getCorrectionOffsets();
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public TopicList getUnitTopicList(final boolean containRetry, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_UNIT_TOPIC_LIST, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(response.getBody(), TopicList.class);
if (!containRetry) {
Iterator<String> it = topicList.getTopicList().iterator();
while (it.hasNext()) {
String topic = it.next();
if (topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
it.remove();
}
}
}
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public TopicList getHasUnitSubTopicList(final boolean containRetry, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_HAS_UNIT_SUB_TOPIC_LIST, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(response.getBody(), TopicList.class);
if (!containRetry) {
Iterator<String> it = topicList.getTopicList().iterator();
while (it.hasNext()) {
String topic = it.next();
if (topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
it.remove();
}
}
}
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public TopicList getHasUnitSubUnUnitTopicList(final boolean containRetry, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_HAS_UNIT_SUB_UNUNIT_TOPIC_LIST, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(response.getBody(), TopicList.class);
if (!containRetry) {
Iterator<String> it = topicList.getTopicList().iterator();
while (it.hasNext()) {
String topic = it.next();
if (topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
it.remove();
}
}
}
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void cloneGroupOffset(final String addr, final String srcGroup, final String destGroup, final String topic,
final boolean isOffline,
final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException {
CloneGroupOffsetRequestHeader requestHeader = new CloneGroupOffsetRequestHeader();
requestHeader.setSrcGroup(srcGroup);
requestHeader.setDestGroup(destGroup);
requestHeader.setTopic(topic);
requestHeader.setOffline(isOffline);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLONE_GROUP_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public BrokerStatsData viewBrokerStatsData(String brokerAddr, String statsName, String statsKey, long timeoutMillis)
throws MQClientException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException,
InterruptedException {
ViewBrokerStatsDataRequestHeader requestHeader = new ViewBrokerStatsDataRequestHeader();
requestHeader.setStatsName(statsName);
requestHeader.setStatsKey(statsKey);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.VIEW_BROKER_STATS_DATA, requestHeader);
RemotingCommand response = this.remotingClient
.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
return BrokerStatsData.decode(body, BrokerStatsData.class);
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public Set<String> getClusterList(String topic,
long timeoutMillis) {
return Collections.EMPTY_SET;
}
public ConsumeStatsList fetchConsumeStatsInBroker(String brokerAddr, boolean isOrder,
long timeoutMillis) throws MQClientException,
RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
GetConsumeStatsInBrokerHeader requestHeader = new GetConsumeStatsInBrokerHeader();
requestHeader.setIsOrder(isOrder);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_CONSUME_STATS, requestHeader);
RemotingCommand response = this.remotingClient
.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
return ConsumeStatsList.decode(body, ConsumeStatsList.class);
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public SubscriptionGroupWrapper getAllSubscriptionGroup(final String brokerAddr, long timeoutMillis)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException,
RemotingConnectException, MQBrokerException, RemotingCommandException {
DataVersion currentDataVersion = null;
int groupSeq = 0;
ConcurrentMap<String, SubscriptionGroupConfig> subscriptionGroupTable = new ConcurrentHashMap<>();
ConcurrentMap<String, ConcurrentMap<String, Integer>> forbiddenTable = new ConcurrentHashMap<>();
long beginTime = System.nanoTime();
while (true) {
long leftTime = timeoutMillis - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - beginTime);
if (leftTime < 0) {
throw new RemotingTimeoutException("invokeSync call timeout");
}
GetAllSubscriptionGroupRequestHeader requestHeader = new GetAllSubscriptionGroupRequestHeader();
requestHeader.setGroupSeq(groupSeq);
requestHeader.setMaxGroupNum(clientConfig.getMaxPageSizeInGetMetadata());
requestHeader.setDataVersion(Optional.ofNullable(currentDataVersion)
.map(DataVersion::toJson).orElse(StringUtils.EMPTY));
log.info("getAllSubscriptionGroup from seq {}, max {}, dataVersion {}",
groupSeq, requestHeader.getMaxGroupNum(), requestHeader.getDataVersion());
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_SUBSCRIPTIONGROUP_CONFIG, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(
MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, leftTime);
assert response != null;
if (response.getCode() == SUCCESS) {
SubscriptionGroupWrapper subscriptionGroupWrapper =
SubscriptionGroupWrapper.decode(response.getBody(), SubscriptionGroupWrapper.class);
subscriptionGroupTable.putAll(subscriptionGroupWrapper.getSubscriptionGroupTable());
forbiddenTable.putAll(subscriptionGroupWrapper.getForbiddenTable());
DataVersion newDataVersion = subscriptionGroupWrapper.getDataVersion();
if (currentDataVersion == null) {
// fill dataVersion before break the loop to compatible with old version server
currentDataVersion = newDataVersion;
}
groupSeq += subscriptionGroupWrapper.getSubscriptionGroupTable().size();
GetAllSubscriptionGroupResponseHeader responseHeader =
response.decodeCommandCustomHeader(GetAllSubscriptionGroupResponseHeader.class);
Integer totalGroupNum = Optional.ofNullable(responseHeader)
.map(GetAllSubscriptionGroupResponseHeader::getTotalGroupNum).orElse(null);
if (Objects.isNull(totalGroupNum)) {
// the server side don't support totalGroupNum, all data is returned
break;
}
if (!Objects.equals(currentDataVersion, newDataVersion)) {
log.error("dataVersion changed, currentDataVersion: {}, newDataVersion: {}",
currentDataVersion, newDataVersion);
currentDataVersion = newDataVersion;
groupSeq = 0;
subscriptionGroupTable.clear();
forbiddenTable.clear();
continue;
}
if (groupSeq >= totalGroupNum - 1) {
log.info("get all subscription group config, totalGroupNum: {}", totalGroupNum);
break;
}
} else {
throw new MQBrokerException(response.getCode(), response.getRemark(), brokerAddr);
}
}
SubscriptionGroupWrapper allSubscriptionGroup = new SubscriptionGroupWrapper();
allSubscriptionGroup.setSubscriptionGroupTable(subscriptionGroupTable);
allSubscriptionGroup.setForbiddenTable(forbiddenTable);
allSubscriptionGroup.setDataVersion(currentDataVersion);
return allSubscriptionGroup;
}
public SubscriptionGroupConfig getSubscriptionGroupConfig(final String brokerAddr, String group,
long timeoutMillis) throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
GetSubscriptionGroupConfigRequestHeader header = new GetSubscriptionGroupConfigRequestHeader();
header.setGroup(group);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_SUBSCRIPTIONGROUP_CONFIG, header);
RemotingCommand response = this.remotingClient
.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return RemotingSerializable.decode(response.getBody(), SubscriptionGroupConfig.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), brokerAddr);
}
public TopicConfigSerializeWrapper getAllTopicConfig(final String addr, long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException,
InterruptedException, MQBrokerException, RemotingCommandException {
DataVersion currentDataVersion = null;
int topicSeq = 0;
ConcurrentMap<String, TopicConfig> topicConfigTable = new ConcurrentHashMap<>();
long beginTime = System.nanoTime();
while (true) {
long leftTime = timeoutMillis - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - beginTime);
if (leftTime <= 0) {
throw new RemotingTimeoutException("invokeSync call timeout");
}
GetAllTopicConfigRequestHeader requestHeader = new GetAllTopicConfigRequestHeader();
requestHeader.setTopicSeq(topicSeq);
requestHeader.setMaxTopicNum(clientConfig.getMaxPageSizeInGetMetadata());
requestHeader.setDataVersion(Optional.ofNullable(currentDataVersion).
map(DataVersion::toJson).orElse(StringUtils.EMPTY));
log.info("getAllTopicConfig from seq {}, max {}, dataVersion {}",
topicSeq, requestHeader.getMaxTopicNum(), requestHeader.getDataVersion());
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_TOPIC_CONFIG, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(
MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, leftTime);
assert response != null;
if (response.getCode() == SUCCESS) {
TopicConfigSerializeWrapper topicConfigSerializeWrapper =
TopicConfigSerializeWrapper.decode(response.getBody(), TopicConfigSerializeWrapper.class);
topicConfigTable.putAll(topicConfigSerializeWrapper.getTopicConfigTable());
topicSeq += topicConfigSerializeWrapper.getTopicConfigTable().size();
DataVersion newDataVersion = topicConfigSerializeWrapper.getDataVersion();
if (currentDataVersion == null) {
// fill dataVersion before break the loop to compatible with old version server
currentDataVersion = newDataVersion;
}
GetAllTopicConfigResponseHeader responseHeader =
response.decodeCommandCustomHeader(GetAllTopicConfigResponseHeader.class);
Integer totalTopicNum = Optional.ofNullable(responseHeader)
.map(GetAllTopicConfigResponseHeader::getTotalTopicNum).orElse(null);
if (Objects.isNull(totalTopicNum)) { // compatible with old version server
// the server side don't support totalTopicNum, all data is returned
break;
}
if (!Objects.equals(currentDataVersion, newDataVersion)) {
log.error("dataVersion changed, currentDataVersion: {}, newDataVersion: {}", currentDataVersion, newDataVersion);
currentDataVersion = newDataVersion;
topicSeq = 0;
topicConfigTable.clear();
continue;
}
if (topicSeq >= totalTopicNum - 1) {
log.info("get all topic config, totalTopicNum: {}", totalTopicNum);
break;
}
} else {
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
}
TopicConfigSerializeWrapper topicConfigSerializeWrapper = new TopicConfigSerializeWrapper();
topicConfigSerializeWrapper.setDataVersion(currentDataVersion);
topicConfigSerializeWrapper.setTopicConfigTable(topicConfigTable);
return topicConfigSerializeWrapper;
}
public void updateNameServerConfig(final Properties properties, final List<String> nameServers, long timeoutMillis)
throws UnsupportedEncodingException, InterruptedException, RemotingTimeoutException, RemotingSendRequestException,
RemotingConnectException, MQClientException {
String str = MixAll.properties2String(properties);
if (str == null || str.length() < 1) {
return;
}
List<String> invokeNameServers = (nameServers == null || nameServers.isEmpty()) ?
this.remotingClient.getNameServerAddressList() : nameServers;
if (invokeNameServers == null || invokeNameServers.isEmpty()) {
return;
}
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_NAMESRV_CONFIG, null);
request.setBody(str.getBytes(MixAll.DEFAULT_CHARSET));
RemotingCommand errResponse = null;
for (String nameServer : invokeNameServers) {
RemotingCommand response = this.remotingClient.invokeSync(nameServer, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
break;
}
default:
errResponse = response;
}
}
if (errResponse != null) {
throw new MQClientException(errResponse.getCode(), errResponse.getRemark());
}
}
public Map<String, Properties> getNameServerConfig(final List<String> nameServers, long timeoutMillis)
throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException,
MQClientException, UnsupportedEncodingException {
List<String> invokeNameServers = (nameServers == null || nameServers.isEmpty()) ?
this.remotingClient.getNameServerAddressList() : nameServers;
if (invokeNameServers == null || invokeNameServers.isEmpty()) {
return null;
}
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_NAMESRV_CONFIG, null);
Map<String, Properties> configMap = new HashMap<>(4);
for (String nameServer : invokeNameServers) {
RemotingCommand response = this.remotingClient.invokeSync(nameServer, request, timeoutMillis);
assert response != null;
if (ResponseCode.SUCCESS == response.getCode()) {
configMap.put(nameServer, MixAll.string2Properties(new String(response.getBody(), MixAll.DEFAULT_CHARSET)));
} else {
throw new MQClientException(response.getCode(), response.getRemark());
}
}
return configMap;
}
public QueryConsumeQueueResponseBody queryConsumeQueue(final String brokerAddr, final String topic,
final int queueId,
final long index, final int count, final String consumerGroup,
final long timeoutMillis) throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQClientException {
QueryConsumeQueueRequestHeader requestHeader = new QueryConsumeQueueRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setQueueId(queueId);
requestHeader.setIndex(index);
requestHeader.setCount(count);
requestHeader.setConsumerGroup(consumerGroup);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_CONSUME_QUEUE, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
if (ResponseCode.SUCCESS == response.getCode()) {
return QueryConsumeQueueResponseBody.decode(response.getBody(), QueryConsumeQueueResponseBody.class);
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public CheckRocksdbCqWriteResult checkRocksdbCqWriteProgress(final String brokerAddr, final String topic, final long checkStoreTime, final long timeoutMillis) throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQClientException {
CheckRocksdbCqWriteProgressRequestHeader header = new CheckRocksdbCqWriteProgressRequestHeader();
header.setTopic(topic);
header.setCheckStoreTime(checkStoreTime);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CHECK_ROCKSDB_CQ_WRITE_PROGRESS, header);
RemotingCommand response = this.remotingClient.invokeSync(brokerAddr, request, timeoutMillis);
assert response != null;
if (ResponseCode.SUCCESS == response.getCode()) {
return JSON.parseObject(response.getBody(), CheckRocksdbCqWriteResult.class);
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void exportRocksDBConfigToJson(final String brokerAddr,
final List<ExportRocksDBConfigToJsonRequestHeader.ConfigType> configType,
final long timeoutMillis) throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQClientException {
ExportRocksDBConfigToJsonRequestHeader header = new ExportRocksDBConfigToJsonRequestHeader();
header.updateConfigType(configType);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.EXPORT_ROCKSDB_CONFIG_TO_JSON, header);
RemotingCommand response = this.remotingClient.invokeSync(brokerAddr, request, timeoutMillis);
assert response != null;
if (ResponseCode.SUCCESS != response.getCode()) {
throw new MQClientException(response.getCode(), response.getRemark());
}
}
public void checkClientInBroker(final String brokerAddr, final String consumerGroup,
final String clientId, final SubscriptionData subscriptionData,
final long timeoutMillis)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException,
RemotingConnectException, MQClientException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CHECK_CLIENT_CONFIG, null);
CheckClientRequestBody requestBody = new CheckClientRequestBody();
requestBody.setClientId(clientId);
requestBody.setGroup(consumerGroup);
requestBody.setSubscriptionData(subscriptionData);
request.setBody(requestBody.encode());
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
if (ResponseCode.SUCCESS != response.getCode()) {
throw new MQClientException(response.getCode(), response.getRemark());
}
}
public boolean resumeCheckHalfMessage(final String addr, String topic, String msgId,
final long timeoutMillis) throws RemotingException, InterruptedException {
ResumeCheckHalfMessageRequestHeader requestHeader = new ResumeCheckHalfMessageRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setMsgId(msgId);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.RESUME_CHECK_HALF_MESSAGE, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return true;
}
default:
log.error("Failed to resume half message check logic. Remark={}", response.getRemark());
return false;
}
}
public void setMessageRequestMode(final String brokerAddr, final String topic, final String consumerGroup,
final MessageRequestMode mode, final int popShareQueueNum, final long timeoutMillis)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException,
RemotingConnectException, MQClientException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.SET_MESSAGE_REQUEST_MODE, null);
SetMessageRequestModeRequestBody requestBody = new SetMessageRequestModeRequestBody();
requestBody.setTopic(topic);
requestBody.setConsumerGroup(consumerGroup);
requestBody.setMode(mode);
requestBody.setPopShareQueueNum(popShareQueueNum);
request.setBody(requestBody.encode());
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
if (ResponseCode.SUCCESS != response.getCode()) {
throw new MQClientException(response.getCode(), response.getRemark());
}
}
public TopicConfigAndQueueMapping getTopicConfig(final String brokerAddr, String topic,
long timeoutMillis) throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
GetTopicConfigRequestHeader header = new GetTopicConfigRequestHeader();
header.setTopic(topic);
header.setLo(true);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_TOPIC_CONFIG, header);
RemotingCommand response = this.remotingClient
.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return RemotingSerializable.decode(response.getBody(), TopicConfigAndQueueMapping.class);
}
//should check the exist
case ResponseCode.TOPIC_NOT_EXIST: {
//should return null?
break;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void createStaticTopic(final String addr, final String defaultTopic, final TopicConfig topicConfig,
final TopicQueueMappingDetail topicQueueMappingDetail, boolean force,
final long timeoutMillis) throws RemotingException, InterruptedException, MQBrokerException {
CreateTopicRequestHeader requestHeader = new CreateTopicRequestHeader();
requestHeader.setTopic(topicConfig.getTopicName());
requestHeader.setDefaultTopic(defaultTopic);
requestHeader.setReadQueueNums(topicConfig.getReadQueueNums());
requestHeader.setWriteQueueNums(topicConfig.getWriteQueueNums());
requestHeader.setPerm(topicConfig.getPerm());
requestHeader.setTopicFilterType(topicConfig.getTopicFilterType().name());
requestHeader.setTopicSysFlag(topicConfig.getTopicSysFlag());
requestHeader.setOrder(topicConfig.isOrder());
requestHeader.setForce(force);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_STATIC_TOPIC, requestHeader);
request.setBody(topicQueueMappingDetail.encode());
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
/**
* @param addr
* @param requestHeader
* @param timeoutMillis
* @throws InterruptedException
* @throws RemotingTimeoutException
* @throws RemotingSendRequestException
* @throws RemotingConnectException
* @throws MQBrokerException
*/
public GroupForbidden updateAndGetGroupForbidden(String addr, UpdateGroupForbiddenRequestHeader requestHeader,
long timeoutMillis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_GET_GROUP_FORBIDDEN, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return RemotingSerializable.decode(response.getBody(), GroupForbidden.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public void resetMasterFlushOffset(final String brokerAddr, final long masterFlushOffset)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
ResetMasterFlushOffsetHeader requestHeader = new ResetMasterFlushOffsetHeader();
requestHeader.setMasterFlushOffset(masterFlushOffset);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.RESET_MASTER_FLUSH_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(brokerAddr, request, 3000);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), brokerAddr);
}
public HARuntimeInfo getBrokerHAStatus(final String brokerAddr, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException,
InterruptedException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_HA_STATUS, null);
RemotingCommand response = this.remotingClient.invokeSync(brokerAddr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return HARuntimeInfo.decode(response.getBody(), HARuntimeInfo.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public GetMetaDataResponseHeader getControllerMetaData(
final String controllerAddress) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, RemotingCommandException, MQBrokerException {
final RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CONTROLLER_GET_METADATA_INFO, null);
final RemotingCommand response = this.remotingClient.invokeSync(controllerAddress, request, 3000);
assert response != null;
if (response.getCode() == SUCCESS) {
return (GetMetaDataResponseHeader) response.decodeCommandCustomHeader(GetMetaDataResponseHeader.class);
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public BrokerReplicasInfo getInSyncStateData(final String controllerAddress,
final List<String> brokers) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException, RemotingCommandException {
// Get controller leader address.
final GetMetaDataResponseHeader controllerMetaData = getControllerMetaData(controllerAddress);
assert controllerMetaData != null;
assert controllerMetaData.getControllerLeaderAddress() != null;
final String leaderAddress = controllerMetaData.getControllerLeaderAddress();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CONTROLLER_GET_SYNC_STATE_DATA, null);
final byte[] body = RemotingSerializable.encode(brokers);
request.setBody(body);
RemotingCommand response = this.remotingClient.invokeSync(leaderAddress, request, 3000);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return RemotingSerializable.decode(response.getBody(), BrokerReplicasInfo.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public EpochEntryCache getBrokerEpochCache(
String brokerAddr) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_EPOCH_CACHE, null);
final RemotingCommand response = this.remotingClient.invokeSync(brokerAddr, request, 3000);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return RemotingSerializable.decode(response.getBody(), EpochEntryCache.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public Map<String, Properties> getControllerConfig(final List<String> controllerServers,
final long timeoutMillis) throws InterruptedException, RemotingTimeoutException,
RemotingSendRequestException, RemotingConnectException, MQClientException, UnsupportedEncodingException {
List<String> invokeControllerServers = (controllerServers == null || controllerServers.isEmpty()) ?
this.remotingClient.getNameServerAddressList() : controllerServers;
if (invokeControllerServers == null || invokeControllerServers.isEmpty()) {
return null;
}
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONTROLLER_CONFIG, null);
Map<String, Properties> configMap = new HashMap<>(4);
for (String controller : invokeControllerServers) {
RemotingCommand response = this.remotingClient.invokeSync(controller, request, timeoutMillis);
assert response != null;
if (ResponseCode.SUCCESS == response.getCode()) {
configMap.put(controller, MixAll.string2Properties(new String(response.getBody(), MixAll.DEFAULT_CHARSET)));
} else {
throw new MQClientException(response.getCode(), response.getRemark());
}
}
return configMap;
}
public void updateControllerConfig(final Properties properties, final List<String> controllers,
final long timeoutMillis) throws InterruptedException, RemotingConnectException, UnsupportedEncodingException,
RemotingSendRequestException, RemotingTimeoutException, MQClientException {
String str = MixAll.properties2String(properties);
if (str.length() < 1 || controllers == null || controllers.isEmpty()) {
return;
}
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_CONTROLLER_CONFIG, null);
request.setBody(str.getBytes(MixAll.DEFAULT_CHARSET));
RemotingCommand errResponse = null;
for (String controller : controllers) {
RemotingCommand response = this.remotingClient.invokeSync(controller, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
break;
}
default:
errResponse = response;
}
}
if (errResponse != null) {
throw new MQClientException(errResponse.getCode(), errResponse.getRemark());
}
}
public Pair<ElectMasterResponseHeader, BrokerMemberGroup> electMaster(String controllerAddr, String clusterName,
String brokerName,
Long brokerId) throws MQBrokerException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, RemotingCommandException {
//get controller leader address
final GetMetaDataResponseHeader controllerMetaData = this.getControllerMetaData(controllerAddr);
assert controllerMetaData != null;
assert controllerMetaData.getControllerLeaderAddress() != null;
final String leaderAddress = controllerMetaData.getControllerLeaderAddress();
ElectMasterRequestHeader electRequestHeader = ElectMasterRequestHeader.ofAdminTrigger(clusterName, brokerName, brokerId);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CONTROLLER_ELECT_MASTER, electRequestHeader);
final RemotingCommand response = this.remotingClient.invokeSync(leaderAddress, request, 3000);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
BrokerMemberGroup brokerMemberGroup = RemotingSerializable.decode(response.getBody(), BrokerMemberGroup.class);
ElectMasterResponseHeader responseHeader = (ElectMasterResponseHeader) response.decodeCommandCustomHeader(ElectMasterResponseHeader.class);
return new Pair<>(responseHeader, brokerMemberGroup);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void cleanControllerBrokerData(String controllerAddr, String clusterName,
String brokerName, String brokerControllerIdsToClean, boolean isCleanLivingBroker)
throws RemotingException, InterruptedException, MQBrokerException {
//get controller leader address
final GetMetaDataResponseHeader controllerMetaData = this.getControllerMetaData(controllerAddr);
assert controllerMetaData != null;
assert controllerMetaData.getControllerLeaderAddress() != null;
final String leaderAddress = controllerMetaData.getControllerLeaderAddress();
CleanControllerBrokerDataRequestHeader cleanHeader = new CleanControllerBrokerDataRequestHeader(clusterName, brokerName, brokerControllerIdsToClean, isCleanLivingBroker);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLEAN_BROKER_DATA, cleanHeader);
final RemotingCommand response = this.remotingClient.invokeSync(leaderAddress, request, 3000);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void createUser(String addr, UserInfo userInfo, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
CreateUserRequestHeader requestHeader = new CreateUserRequestHeader(userInfo.getUsername());
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.AUTH_CREATE_USER, requestHeader);
request.setBody(RemotingSerializable.encode(userInfo));
RemotingCommand response = this.remotingClient.invokeSync(addr, request, millis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void updateUser(String addr, UserInfo userInfo, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
UpdateUserRequestHeader requestHeader = new UpdateUserRequestHeader(userInfo.getUsername());
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.AUTH_UPDATE_USER, requestHeader);
request.setBody(RemotingSerializable.encode(userInfo));
RemotingCommand response = this.remotingClient.invokeSync(addr, request, millis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void deleteUser(String addr, String username, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
DeleteUserRequestHeader requestHeader = new DeleteUserRequestHeader(username);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.AUTH_DELETE_USER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, millis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public UserInfo getUser(String addr, String username, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
GetUserRequestHeader requestHeader = new GetUserRequestHeader(username);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.AUTH_GET_USER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, millis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return RemotingSerializable.decode(response.getBody(), UserInfo.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public List<UserInfo> listUser(String addr, String filter, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
ListUsersRequestHeader requestHeader = new ListUsersRequestHeader(filter);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.AUTH_LIST_USER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, millis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return RemotingSerializable.decodeList(response.getBody(), UserInfo.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void createAcl(String addr, AclInfo aclInfo, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
CreateAclRequestHeader requestHeader = new CreateAclRequestHeader(aclInfo.getSubject());
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.AUTH_CREATE_ACL, requestHeader);
request.setBody(RemotingSerializable.encode(aclInfo));
RemotingCommand response = this.remotingClient.invokeSync(addr, request, millis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void updateAcl(String addr, AclInfo aclInfo, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
UpdateAclRequestHeader requestHeader = new UpdateAclRequestHeader(aclInfo.getSubject());
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.AUTH_UPDATE_ACL, requestHeader);
request.setBody(RemotingSerializable.encode(aclInfo));
RemotingCommand response = this.remotingClient.invokeSync(addr, request, millis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void deleteAcl(String addr, String subject, String resource, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
DeleteAclRequestHeader requestHeader = new DeleteAclRequestHeader(subject, resource);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.AUTH_DELETE_ACL, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, millis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public AclInfo getAcl(String addr, String subject, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
GetAclRequestHeader requestHeader = new GetAclRequestHeader(subject);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.AUTH_GET_ACL, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, millis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return RemotingSerializable.decode(response.getBody(), AclInfo.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public List<AclInfo> listAcl(String addr, String subjectFilter, String resourceFilter, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
ListAclsRequestHeader requestHeader = new ListAclsRequestHeader(subjectFilter, resourceFilter);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.AUTH_LIST_ACL, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, millis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return RemotingSerializable.decodeList(response.getBody(), AclInfo.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public String recallMessage(
final String addr,
RecallMessageRequestHeader requestHeader,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.RECALL_MESSAGE, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
RecallMessageResponseHeader responseHeader =
response.decodeCommandCustomHeader(RecallMessageResponseHeader.class);
return responseHeader.getMsgId();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
}
public void recallMessageAsync(
final String addr,
final RecallMessageRequestHeader requestHeader,
final long timeoutMillis,
final InvokeCallback invokeCallback
) throws RemotingException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.RECALL_MESSAGE, requestHeader);
this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
}
@Override
public void operationSucceed(RemotingCommand response) {
invokeCallback.operationSucceed(response);
}
@Override
public void operationFail(Throwable throwable) {
invokeCallback.operationFail(throwable);
}
});
}
public void exportPopRecord(String brokerAddr, long timeout) throws RemotingConnectException,
RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(
RequestCode.POP_ROLLBACK, null);
RemotingCommand response = this.remotingClient.invokeSync(brokerAddr, request, timeout);
assert response != null;
if (response.getCode() == SUCCESS) {
return;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
}
|
MQClientAPIImpl
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/junit4/HardCodedProfileValueSourceSpringRunnerTests.java
|
{
"start": 1976,
"end": 2149
}
|
class ____ implements ProfileValueSource {
@Override
public String get(final String key) {
return (key.equals(NAME) ? VALUE : null);
}
}
}
|
HardCodedProfileValueSource
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/KeywordValidatorTest.java
|
{
"start": 864,
"end": 1219
}
|
class ____ {
@Test
public void javaKeywordAsComponentCreatorMethodName_failsWithExpectedError() {
Source componentSrc =
CompilerTests.kotlinSource(
"test/TestComponent.kt",
"package test",
"",
"import dagger.Component",
"",
"@Component",
"
|
KeywordValidatorTest
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java
|
{
"start": 84601,
"end": 85224
}
|
class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((requests) -> requests
.anyRequest().authenticated())
.oauth2ResourceServer((server) -> server
.jwt(Customizer.withDefaults()));
return http.build();
// @formatter:on
}
@Bean
BearerTokenResolver allowQueryParameter() {
DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver();
resolver.setAllowUriQueryParameter(true);
return resolver;
}
}
@Configuration
@EnableWebSecurity
static
|
AllowBearerTokenAsQueryParameterConfig
|
java
|
elastic__elasticsearch
|
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/snyk/GenerateSnykDependencyGraph.java
|
{
"start": 1212,
"end": 5263
}
|
class ____ extends DefaultTask {
private static final Map<String, Object> FIXED_META_DATA = Map.of(
"method",
"custom gradle",
"id",
"gradle",
"node",
"v16.15.1",
"name",
"gradle",
"plugin",
"extern:gradle",
"pluginRuntime",
"unknown",
"monitorGraph",
true
);
private final Property<Configuration> configuration;
private final Property<String> gradleVersion;
private final RegularFileProperty outputFile;
private final Property<String> projectName;
private final Property<String> projectPath;
private final Property<String> targetReference;
private final Property<String> version;
private final Property<String> remoteUrl;
@Inject
public GenerateSnykDependencyGraph(ObjectFactory objectFactory) {
configuration = objectFactory.property(Configuration.class);
gradleVersion = objectFactory.property(String.class);
outputFile = objectFactory.fileProperty();
projectName = objectFactory.property(String.class);
projectPath = objectFactory.property(String.class);
version = objectFactory.property(String.class);
remoteUrl = objectFactory.property(String.class);
targetReference = objectFactory.property(String.class);
}
@TaskAction
void resolveGraph() {
Map<String, Object> payload = generateGradleGraphPayload();
String jsonOutput = JsonOutput.prettyPrint(JsonOutput.toJson(payload));
try {
Files.writeString(
getOutputFile().getAsFile().get().toPath(),
jsonOutput,
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING
);
} catch (IOException e) {
throw new GradleException("Cannot generate dependencies json file", e);
}
}
private Map<String, Object> generateGradleGraphPayload() {
Set<ResolvedDependency> firstLevelModuleDependencies = configuration.get()
.getResolvedConfiguration()
.getFirstLevelModuleDependencies();
SnykDependencyGraphBuilder builder = new SnykDependencyGraphBuilder(gradleVersion.get());
String effectiveProjectPath = projectPath.get();
builder.walkGraph(
(effectiveProjectPath.equals(":") ? projectName.get() : effectiveProjectPath),
version.get(),
firstLevelModuleDependencies
);
return Map.of(
"meta",
FIXED_META_DATA,
"depGraphJSON",
builder.build(),
"target",
buildTargetData(),
"targetReference",
targetReference.get(),
"projectAttributes",
projectAttributesData()
);
}
private Map<String, List<String>> projectAttributesData() {
return Map.of("lifecycle", List.of(version.map(v -> v.endsWith("SNAPSHOT") ? "development" : "production").get()));
}
private Object buildTargetData() {
return Map.of("remoteUrl", remoteUrl.get(), "branch", getGitRevision().get());
}
@InputFiles
public Property<Configuration> getConfiguration() {
return configuration;
}
@OutputFile
public RegularFileProperty getOutputFile() {
return outputFile;
}
@Input
public Property<String> getProjectPath() {
return projectPath;
}
@Input
public Property<String> getVersion() {
return version;
}
@Input
public Property<String> getProjectName() {
return projectName;
}
@Input
public Property<String> getGradleVersion() {
return gradleVersion;
}
@Input
public Property<String> getRemoteUrl() {
return remoteUrl;
}
@Input
public Property<String> getTargetReference() {
return targetReference;
}
@Input
public Property<String> getGitRevision() {
return targetReference;
}
}
|
GenerateSnykDependencyGraph
|
java
|
elastic__elasticsearch
|
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/service/RestClearServiceAccountTokenStoreCacheAction.java
|
{
"start": 1179,
"end": 2985
}
|
class ____ extends SecurityBaseRestHandler {
public RestClearServiceAccountTokenStoreCacheAction(Settings settings, XPackLicenseState licenseState) {
super(settings, licenseState);
}
@Override
public List<Route> routes() {
return List.of(new Route(POST, "/_security/service/{namespace}/{service}/credential/token/{name}/_clear_cache"));
}
@Override
public String getName() {
return "xpack_security_clear_service_account_token_store_cache";
}
@Override
protected RestChannelConsumer innerPrepareRequest(RestRequest request, NodeClient client) throws IOException {
final String namespace = request.param("namespace");
final String service = request.param("service");
String[] tokenNames = request.paramAsStringArrayOrEmptyIfAll("name");
ClearSecurityCacheRequest req = new ClearSecurityCacheRequest().cacheName("service");
if (tokenNames.length == 0) {
// This is the wildcard case for tokenNames
req.keys(namespace + "/" + service + "/");
} else {
final Set<String> qualifiedTokenNames = Sets.newHashSetWithExpectedSize(tokenNames.length);
for (String name : tokenNames) {
if (false == Validation.isValidServiceAccountTokenName(name)) {
throw new IllegalArgumentException(Validation.formatInvalidServiceTokenNameErrorMessage(name));
}
qualifiedTokenNames.add(namespace + "/" + service + "/" + name);
}
req.keys(qualifiedTokenNames.toArray(String[]::new));
}
return channel -> client.execute(ClearSecurityCacheAction.INSTANCE, req, new RestActions.NodesResponseRestListener<>(channel));
}
}
|
RestClearServiceAccountTokenStoreCacheAction
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/time/JodaPlusMinusLongTest.java
|
{
"start": 4638,
"end": 5120
}
|
class ____ {
private static final Duration PLUS = Duration.ZERO.plus(42L);
private static final Duration MINUS = Duration.ZERO.minus(42L);
}
""")
.doTest();
}
// DateTime
@Test
public void dateTimePlusMinusDuration() {
helper
.addSourceLines(
"TestClass.java",
"""
import org.joda.time.DateTime;
import org.joda.time.Duration;
public
|
TestClass
|
java
|
spring-projects__spring-framework
|
spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java
|
{
"start": 27019,
"end": 27807
}
|
class ____ implements SmartFactoryBean<TestBean> {
private final TestBean testBean = new TestBean("enigma", 42);
private final boolean singleton;
private final boolean prototype;
TestBeanSmartFactoryBean(boolean singleton, boolean prototype) {
this.singleton = singleton;
this.prototype = prototype;
}
@Override
public TestBean getObject() {
// We don't really care if the actual instance is a singleton or prototype
// for the tests that use this factory.
return this.testBean;
}
@Override
public Class<TestBean> getObjectType() {
return TestBean.class;
}
@Override
public boolean isSingleton() {
return this.singleton;
}
@Override
public boolean isPrototype() {
return this.prototype;
}
}
static
|
TestBeanSmartFactoryBean
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/BuilderReturnThisTest.java
|
{
"start": 1194,
"end": 2293
}
|
class ____ {
static TestBuilder builder() {
return new TestBuilder();
}
Test build() {
return new Test();
}
TestBuilder setFoo(String foo) {
return this;
}
TestBuilder setBar(String bar) {
return this;
}
TestBuilder setBaz(String baz) {
return setFoo(baz).setBar(baz);
}
TestBuilder setTernary(String baz) {
return true ? setFoo(baz) : this;
}
TestBuilder setCast(String baz) {
return (TestBuilder) this;
}
TestBuilder setParens(String bar) {
return (this);
}
}
}
""")
.expectUnchanged()
.doTest();
}
@Test
public void positive() {
testHelper
.addInputLines(
"Test.java",
"""
|
TestBuilder
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/aot/hint/ReflectionTypeReference.java
|
{
"start": 889,
"end": 1896
}
|
class ____ extends AbstractTypeReference {
private final Class<?> type;
private ReflectionTypeReference(Class<?> type) {
super(type.getPackageName(), type.getSimpleName(), getEnclosingClass(type));
this.type = type;
}
private static @Nullable TypeReference getEnclosingClass(Class<?> type) {
Class<?> candidate = (type.isArray() ? type.componentType().getEnclosingClass() :
type.getEnclosingClass());
return (candidate != null ? new ReflectionTypeReference(candidate) : null);
}
static ReflectionTypeReference of(Class<?> type) {
Assert.notNull(type, "'type' must not be null");
Assert.notNull(type.getCanonicalName(), "'type.getCanonicalName()' must not be null");
return new ReflectionTypeReference(type);
}
@Override
public String getCanonicalName() {
return this.type.getCanonicalName();
}
@Override
protected boolean isPrimitive() {
return this.type.isPrimitive() ||
(this.type.isArray() && this.type.componentType().isPrimitive());
}
}
|
ReflectionTypeReference
|
java
|
quarkusio__quarkus
|
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/args/OnCloseInvalidArgumentTest.java
|
{
"start": 820,
"end": 922
}
|
class ____ {
@OnClose
void close(List<String> unsupported) {
}
}
}
|
Endpoint
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/HasChangedMergeTest.java
|
{
"start": 1236,
"end": 4642
}
|
class ____ extends AbstractModifiedFlagsEntityTest {
private Integer parent1Id = null;
private Integer child1Id = null;
private Integer parent2Id = null;
private Integer child2Id = null;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) {
// Revision 1 - data preparation
scope.inEntityManager( em -> {
em.getTransaction().begin();
ListRefEdEntity parent1 = new ListRefEdEntity( 1, "initial data" );
parent1.setReffering( new ArrayList<>() ); // Empty collection is not the same as null reference.
ListRefEdEntity parent2 = new ListRefEdEntity( 2, "initial data" );
parent2.setReffering( new ArrayList<>() );
em.persist( parent1 );
em.persist( parent2 );
parent1Id = parent1.getId();
parent2Id = parent2.getId();
em.getTransaction().commit();
} );
// Revision 2 - inserting new child entity and updating parent
scope.inEntityManager( em -> {
em.getTransaction().begin();
ListRefEdEntity parent1 = em.find( ListRefEdEntity.class, parent1Id );
ListRefIngEntity child1 = new ListRefIngEntity( 1, "initial data", parent1 );
em.persist( child1 );
parent1.setData( "updated data" );
em.merge( parent1 );
child1Id = child1.getId();
em.getTransaction().commit();
} );
// Revision 3 - updating parent, flushing and adding new child
scope.inEntityManager( em -> {
em.getTransaction().begin();
ListRefEdEntity parent2 = em.find( ListRefEdEntity.class, parent2Id );
parent2.setData( "updated data" );
em.merge( parent2 );
em.flush();
ListRefIngEntity child2 = new ListRefIngEntity( 2, "initial data", parent2 );
em.persist( child2 );
child2Id = child2.getId();
em.getTransaction().commit();
} );
}
@Test
@JiraKey(value = "HHH-7948")
public void testOneToManyInsertChildUpdateParent(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
List list = queryForPropertyHasChanged( auditReader, ListRefEdEntity.class, parent1Id, "data" );
assertEquals( 2, list.size() );
assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) );
list = queryForPropertyHasChanged( auditReader, ListRefEdEntity.class, parent1Id, "reffering" );
assertEquals( 2, list.size() );
assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) );
list = queryForPropertyHasChanged( auditReader, ListRefIngEntity.class, child1Id, "reference" );
assertEquals( 1, list.size() );
assertEquals( makeList( 2 ), extractRevisionNumbers( list ) );
} );
}
@Test
@JiraKey(value = "HHH-7948")
public void testOneToManyUpdateParentInsertChild(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
List list = queryForPropertyHasChanged( auditReader, ListRefEdEntity.class, parent2Id, "data" );
assertEquals( 2, list.size() );
assertEquals( makeList( 1, 3 ), extractRevisionNumbers( list ) );
list = queryForPropertyHasChanged( auditReader, ListRefEdEntity.class, parent2Id, "reffering" );
assertEquals( 2, list.size() );
assertEquals( makeList( 1, 3 ), extractRevisionNumbers( list ) );
list = queryForPropertyHasChanged( auditReader, ListRefIngEntity.class, child2Id, "reference" );
assertEquals( 1, list.size() );
assertEquals( makeList( 3 ), extractRevisionNumbers( list ) );
} );
}
}
|
HasChangedMergeTest
|
java
|
spring-projects__spring-security
|
oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2TokenIntrospectionHttpMessageConverterTests.java
|
{
"start": 1735,
"end": 7818
}
|
class ____ {
private final OAuth2TokenIntrospectionHttpMessageConverter messageConverter = new OAuth2TokenIntrospectionHttpMessageConverter();
@Test
public void supportsWhenOAuth2TokenIntrospectionThenTrue() {
assertThat(this.messageConverter.supports(OAuth2TokenIntrospection.class)).isTrue();
}
@Test
public void setTokenIntrospectionParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.messageConverter.setTokenIntrospectionParametersConverter(null));
}
@Test
public void setTokenIntrospectionConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.messageConverter.setTokenIntrospectionConverter(null));
}
@Test
public void readInternalWhenValidParametersThenSuccess() throws Exception {
// @formatter:off
String tokenIntrospectionResponseBody = "{\n"
+ " \"active\": true,\n"
+ " \"client_id\": \"clientId1\",\n"
+ " \"username\": \"username1\",\n"
+ " \"iat\": 1607633867,\n"
+ " \"exp\": 1607637467,\n"
+ " \"scope\": \"scope1 scope2\",\n"
+ " \"token_type\": \"Bearer\",\n"
+ " \"nbf\": 1607633867,\n"
+ " \"sub\": \"subject1\",\n"
+ " \"aud\": [\"audience1\", \"audience2\"],\n"
+ " \"iss\": \"https://example.com/issuer1\",\n"
+ " \"jti\": \"jwtId1\"\n"
+ "}\n";
// @formatter:on
MockClientHttpResponse response = new MockClientHttpResponse(tokenIntrospectionResponseBody.getBytes(),
HttpStatus.OK);
OAuth2TokenIntrospection tokenIntrospectionResponse = this.messageConverter
.readInternal(OAuth2TokenIntrospection.class, response);
assertThat(tokenIntrospectionResponse.isActive()).isTrue();
assertThat(tokenIntrospectionResponse.getClientId()).isEqualTo("clientId1");
assertThat(tokenIntrospectionResponse.getUsername()).isEqualTo("username1");
assertThat(tokenIntrospectionResponse.getIssuedAt()).isEqualTo(Instant.ofEpochSecond(1607633867L));
assertThat(tokenIntrospectionResponse.getExpiresAt()).isEqualTo(Instant.ofEpochSecond(1607637467L));
assertThat(tokenIntrospectionResponse.getScopes())
.containsExactlyInAnyOrderElementsOf(Arrays.asList("scope1", "scope2"));
assertThat(tokenIntrospectionResponse.getTokenType()).isEqualTo("Bearer");
assertThat(tokenIntrospectionResponse.getNotBefore()).isEqualTo(Instant.ofEpochSecond(1607633867L));
assertThat(tokenIntrospectionResponse.getSubject()).isEqualTo("subject1");
assertThat(tokenIntrospectionResponse.getAudience())
.containsExactlyInAnyOrderElementsOf(Arrays.asList("audience1", "audience2"));
assertThat(tokenIntrospectionResponse.getIssuer()).isEqualTo(new URL("https://example.com/issuer1"));
assertThat(tokenIntrospectionResponse.getId()).isEqualTo("jwtId1");
}
@Test
public void readInternalWhenFailingConverterThenThrowException() {
String errorMessage = "this is not a valid converter";
this.messageConverter.setTokenIntrospectionConverter((source) -> {
throw new RuntimeException(errorMessage);
});
MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK);
assertThatExceptionOfType(HttpMessageNotReadableException.class)
.isThrownBy(() -> this.messageConverter.readInternal(OAuth2TokenIntrospection.class, response))
.withMessageContaining("An error occurred reading the Token Introspection Response")
.withMessageContaining(errorMessage);
}
@Test
public void writeInternalWhenTokenIntrospectionThenSuccess() {
// @formatter:off
OAuth2TokenIntrospection tokenClaims = OAuth2TokenIntrospection.builder(true)
.clientId("clientId1")
.username("username1")
.issuedAt(Instant.ofEpochSecond(1607633867))
.expiresAt(Instant.ofEpochSecond(1607637467))
.scope("scope1 scope2")
.tokenType(TokenType.BEARER.getValue())
.notBefore(Instant.ofEpochSecond(1607633867))
.subject("subject1")
.audience("audience1")
.audience("audience2")
.issuer("https://example.com/issuer1")
.id("jwtId1")
.build();
// @formatter:on
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
this.messageConverter.writeInternal(tokenClaims, outputMessage);
String tokenIntrospectionResponse = outputMessage.getBodyAsString();
assertThat(tokenIntrospectionResponse).contains("\"active\":true");
assertThat(tokenIntrospectionResponse).contains("\"client_id\":\"clientId1\"");
assertThat(tokenIntrospectionResponse).contains("\"username\":\"username1\"");
assertThat(tokenIntrospectionResponse).contains("\"iat\":1607633867");
assertThat(tokenIntrospectionResponse).contains("\"exp\":1607637467");
assertThat(tokenIntrospectionResponse).contains("\"scope\":\"scope1 scope2\"");
assertThat(tokenIntrospectionResponse).contains("\"token_type\":\"Bearer\"");
assertThat(tokenIntrospectionResponse).contains("\"nbf\":1607633867");
assertThat(tokenIntrospectionResponse).contains("\"sub\":\"subject1\"");
assertThat(tokenIntrospectionResponse).contains("\"aud\":[\"audience1\",\"audience2\"]");
assertThat(tokenIntrospectionResponse).contains("\"iss\":\"https://example.com/issuer1\"");
assertThat(tokenIntrospectionResponse).contains("\"jti\":\"jwtId1\"");
}
@Test
public void writeInternalWhenWriteFailsThenThrowsException() {
String errorMessage = "this is not a valid converter";
Converter<OAuth2TokenIntrospection, Map<String, Object>> failingConverter = (source) -> {
throw new RuntimeException(errorMessage);
};
this.messageConverter.setTokenIntrospectionParametersConverter(failingConverter);
OAuth2TokenIntrospection tokenClaims = OAuth2TokenIntrospection.builder().build();
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
assertThatExceptionOfType(HttpMessageNotWritableException.class)
.isThrownBy(() -> this.messageConverter.writeInternal(tokenClaims, outputMessage))
.withMessageContaining("An error occurred writing the Token Introspection Response")
.withMessageContaining(errorMessage);
}
}
|
OAuth2TokenIntrospectionHttpMessageConverterTests
|
java
|
google__gson
|
gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java
|
{
"start": 1352,
"end": 5418
}
|
class ____ extends TypeAdapter<Object> {
/** Gson default factory using {@link ToNumberPolicy#DOUBLE}. */
private static final TypeAdapterFactory DOUBLE_FACTORY = newFactory(ToNumberPolicy.DOUBLE);
private final Gson gson;
private final ToNumberStrategy toNumberStrategy;
private ObjectTypeAdapter(Gson gson, ToNumberStrategy toNumberStrategy) {
this.gson = gson;
this.toNumberStrategy = toNumberStrategy;
}
private static TypeAdapterFactory newFactory(ToNumberStrategy toNumberStrategy) {
return new TypeAdapterFactory() {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (type.getRawType() == Object.class) {
return (TypeAdapter<T>) new ObjectTypeAdapter(gson, toNumberStrategy);
}
return null;
}
};
}
public static TypeAdapterFactory getFactory(ToNumberStrategy toNumberStrategy) {
if (toNumberStrategy == ToNumberPolicy.DOUBLE) {
return DOUBLE_FACTORY;
} else {
return newFactory(toNumberStrategy);
}
}
/**
* Tries to begin reading a JSON array or JSON object, returning {@code null} if the next element
* is neither of those.
*/
private Object tryBeginNesting(JsonReader in, JsonToken peeked) throws IOException {
switch (peeked) {
case BEGIN_ARRAY:
in.beginArray();
return new ArrayList<>();
case BEGIN_OBJECT:
in.beginObject();
return new LinkedTreeMap<>();
default:
return null;
}
}
/** Reads an {@code Object} which cannot have any nested elements */
private Object readTerminal(JsonReader in, JsonToken peeked) throws IOException {
switch (peeked) {
case STRING:
return in.nextString();
case NUMBER:
return toNumberStrategy.readNumber(in);
case BOOLEAN:
return in.nextBoolean();
case NULL:
in.nextNull();
return null;
default:
// When read(JsonReader) is called with JsonReader in invalid state
throw new IllegalStateException("Unexpected token: " + peeked);
}
}
@Override
public Object read(JsonReader in) throws IOException {
// Either List or Map
Object current;
JsonToken peeked = in.peek();
current = tryBeginNesting(in, peeked);
if (current == null) {
return readTerminal(in, peeked);
}
Deque<Object> stack = new ArrayDeque<>();
while (true) {
while (in.hasNext()) {
String name = null;
// Name is only used for JSON object members
if (current instanceof Map) {
name = in.nextName();
}
peeked = in.peek();
Object value = tryBeginNesting(in, peeked);
boolean isNesting = value != null;
if (value == null) {
value = readTerminal(in, peeked);
}
if (current instanceof List) {
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) current;
list.add(value);
} else {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) current;
map.put(name, value);
}
if (isNesting) {
stack.addLast(current);
current = value;
}
}
// End current element
if (current instanceof List) {
in.endArray();
} else {
in.endObject();
}
if (stack.isEmpty()) {
return current;
} else {
// Continue with enclosing element
current = stack.removeLast();
}
}
}
@Override
public void write(JsonWriter out, Object value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
@SuppressWarnings("unchecked")
TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) gson.getAdapter(value.getClass());
if (typeAdapter instanceof ObjectTypeAdapter) {
out.beginObject();
out.endObject();
return;
}
typeAdapter.write(out, value);
}
}
|
ObjectTypeAdapter
|
java
|
mybatis__mybatis-3
|
src/main/java/org/apache/ibatis/scripting/xmltags/XMLScriptBuilder.java
|
{
"start": 4398,
"end": 4515
}
|
interface ____ {
void handleNode(XNode nodeToHandle, List<SqlNode> targetContents);
}
private static
|
NodeHandler
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/collection/defaultimplementation/jdk21/SequencedCollectionsDefaultImplementationTest.java
|
{
"start": 1065,
"end": 2558
}
|
class ____ {
@ProcessorTest
public void shouldUseDefaultImplementationForSequencedMap() {
SequencedMap<String, TargetFoo> target =
SequencedCollectionsMapper.INSTANCE.sourceFooMapToTargetFooSequencedMap( createSourceFooMap() );
assertResultMap( target );
}
@ProcessorTest
public void shouldUseDefaultImplementationForSequencedSet() {
SequencedSet<TargetFoo> target =
SequencedCollectionsMapper.INSTANCE.sourceFoosToTargetFooSequencedSet( createSourceFooList() );
assertResultList( target );
}
private void assertResultList(Iterable<TargetFoo> fooIterable) {
assertThat( fooIterable ).isNotNull();
assertThat( fooIterable ).containsOnly( new TargetFoo( "Bob" ), new TargetFoo( "Alice" ) );
}
private void assertResultMap(Map<String, TargetFoo> result) {
assertThat( result ).isNotNull();
assertThat( result ).hasSize( 2 );
assertThat( result ).contains( entry( "1", new TargetFoo( "Bob" ) ), entry( "2", new TargetFoo( "Alice" ) ) );
}
private Map<Long, SourceFoo> createSourceFooMap() {
Map<Long, SourceFoo> map = new HashMap<>();
map.put( 1L, new SourceFoo( "Bob" ) );
map.put( 2L, new SourceFoo( "Alice" ) );
return map;
}
private List<SourceFoo> createSourceFooList() {
return Arrays.asList( new SourceFoo( "Bob" ), new SourceFoo( "Alice" ) );
}
}
|
SequencedCollectionsDefaultImplementationTest
|
java
|
spring-projects__spring-framework
|
spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/JCacheOperationSourcePointcut.java
|
{
"start": 2450,
"end": 3346
}
|
class ____ implements ClassFilter {
@Override
public boolean matches(Class<?> clazz) {
if (CacheManager.class.isAssignableFrom(clazz)) {
return false;
}
return (cacheOperationSource == null || cacheOperationSource.isCandidateClass(clazz));
}
private @Nullable JCacheOperationSource getCacheOperationSource() {
return cacheOperationSource;
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof JCacheOperationSourceClassFilter that &&
ObjectUtils.nullSafeEquals(getCacheOperationSource(), that.getCacheOperationSource())));
}
@Override
public int hashCode() {
return JCacheOperationSourceClassFilter.class.hashCode();
}
@Override
public String toString() {
return JCacheOperationSourceClassFilter.class.getName() + ": " + getCacheOperationSource();
}
}
}
|
JCacheOperationSourceClassFilter
|
java
|
quarkusio__quarkus
|
independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/classloading/ClassLoaderLimiter.java
|
{
"start": 6609,
"end": 6995
}
|
class ____
* @return this, for method chaining.
*/
public Builder neverLoadedClassName(String vetoedClassName) {
Objects.requireNonNull(vetoedClassName);
final boolean add = vetoedClasses.add(vetoedClassName);
if (!add)
throw new ClassLoaderLimiterConsistencyException(
"never loaded
|
name
|
java
|
micronaut-projects__micronaut-core
|
core-processor/src/main/java/io/micronaut/inject/ast/ElementFactory.java
|
{
"start": 1609,
"end": 1860
}
|
class ____ for the given type.
*
* @param type The type
* @param annotationMetadataFactory The element annotation metadata factory
* @param typeArguments The resolved generics
* @return The
|
element
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java
|
{
"start": 3571,
"end": 31432
}
|
class ____ implements RequestManager, MemberStateListener {
private final Time time;
private final SubscriptionState subscriptions;
private final ConsumerMetadata metadata;
private final LogContext logContext;
private final Logger log;
private final Optional<AutoCommitState> autoCommitState;
private final CoordinatorRequestManager coordinatorRequestManager;
private final OffsetCommitCallbackInvoker offsetCommitCallbackInvoker;
private final OffsetCommitMetricsManager metricsManager;
private final long retryBackoffMs;
private final String groupId;
private final Optional<String> groupInstanceId;
private final long retryBackoffMaxMs;
// For testing only
private final OptionalDouble jitter;
private final boolean throwOnFetchStableOffsetUnsupported;
final PendingRequests pendingRequests;
private boolean closing = false;
/**
* Last member epoch sent in a commit request. Empty if no epoch was included in the last
* request. Used for logging.
*/
private Optional<Integer> lastEpochSentOnCommit;
/**
* The member ID and latest member epoch received via the {@link MemberStateListener#onMemberEpochUpdated(Optional, String)},
* to be included in the OffsetFetch and OffsetCommit requests. This will have
* the latest memberEpoch received from the broker.
*/
private final MemberInfo memberInfo;
public CommitRequestManager(
final Time time,
final LogContext logContext,
final SubscriptionState subscriptions,
final ConsumerConfig config,
final CoordinatorRequestManager coordinatorRequestManager,
final OffsetCommitCallbackInvoker offsetCommitCallbackInvoker,
final String groupId,
final Optional<String> groupInstanceId,
final Metrics metrics,
final ConsumerMetadata metadata) {
this(time,
logContext,
subscriptions,
config,
coordinatorRequestManager,
offsetCommitCallbackInvoker,
groupId,
groupInstanceId,
config.getLong(ConsumerConfig.RETRY_BACKOFF_MS_CONFIG),
config.getLong(ConsumerConfig.RETRY_BACKOFF_MAX_MS_CONFIG),
OptionalDouble.empty(),
metrics,
metadata);
}
// Visible for testing
CommitRequestManager(
final Time time,
final LogContext logContext,
final SubscriptionState subscriptions,
final ConsumerConfig config,
final CoordinatorRequestManager coordinatorRequestManager,
final OffsetCommitCallbackInvoker offsetCommitCallbackInvoker,
final String groupId,
final Optional<String> groupInstanceId,
final long retryBackoffMs,
final long retryBackoffMaxMs,
final OptionalDouble jitter,
final Metrics metrics,
final ConsumerMetadata metadata) {
Objects.requireNonNull(coordinatorRequestManager, "Coordinator is needed upon committing offsets");
this.time = time;
this.logContext = logContext;
this.log = logContext.logger(getClass());
this.pendingRequests = new PendingRequests();
if (config.getBoolean(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)) {
final long autoCommitInterval =
Integer.toUnsignedLong(config.getInt(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG));
this.autoCommitState = Optional.of(new AutoCommitState(time, autoCommitInterval, logContext));
} else {
this.autoCommitState = Optional.empty();
}
this.coordinatorRequestManager = coordinatorRequestManager;
this.groupId = groupId;
this.groupInstanceId = groupInstanceId;
this.subscriptions = subscriptions;
this.metadata = metadata;
this.retryBackoffMs = retryBackoffMs;
this.retryBackoffMaxMs = retryBackoffMaxMs;
this.jitter = jitter;
this.throwOnFetchStableOffsetUnsupported = config.getBoolean(THROW_ON_FETCH_STABLE_OFFSET_UNSUPPORTED);
this.memberInfo = new MemberInfo();
this.metricsManager = new OffsetCommitMetricsManager(metrics);
this.offsetCommitCallbackInvoker = offsetCommitCallbackInvoker;
this.lastEpochSentOnCommit = Optional.empty();
}
/**
* Poll for the {@link OffsetFetchRequest} and {@link OffsetCommitRequest} request if there's any.
*/
@Override
public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
// poll when the coordinator node is known and fatal error is not present
if (coordinatorRequestManager.coordinator().isEmpty()) {
pendingRequests.maybeFailOnCoordinatorFatalError();
if (closing && pendingRequests.hasUnsentRequests()) {
CommitFailedException exception = new CommitFailedException(
"Failed to commit offsets: Coordinator unknown and consumer is closing");
pendingRequests.drainPendingCommits()
.forEach(request -> request.future().completeExceptionally(exception));
}
return EMPTY;
}
if (closing) {
return drainPendingOffsetCommitRequests();
}
if (!pendingRequests.hasUnsentRequests())
return EMPTY;
List<NetworkClientDelegate.UnsentRequest> requests = pendingRequests.drain(currentTimeMs);
// min of the remainingBackoffMs of all the request that are still backing off
final long timeUntilNextPoll = Math.min(
findMinTime(unsentOffsetCommitRequests(), currentTimeMs),
findMinTime(unsentOffsetFetchRequests(), currentTimeMs));
return new NetworkClientDelegate.PollResult(timeUntilNextPoll, requests);
}
@Override
public void signalClose() {
closing = true;
}
/**
* Returns the delay for which the application thread can safely wait before it should be responsive
* to results from the request managers. For example, the subscription state can change when heartbeats
* are sent, so blocking for longer than the heartbeat interval might mean the application thread is not
* responsive to changes.
*/
@Override
public long maximumTimeToWait(long currentTimeMs) {
return autoCommitState.map(ac -> ac.remainingMs(currentTimeMs)).orElse(Long.MAX_VALUE);
}
private static long findMinTime(final Collection<? extends RequestState> requests, final long currentTimeMs) {
return requests.stream()
.mapToLong(request -> request.remainingBackoffMs(currentTimeMs))
.min()
.orElse(Long.MAX_VALUE);
}
private KafkaException maybeWrapAsTimeoutException(Throwable t) {
if (t instanceof TimeoutException)
return (TimeoutException) t;
else
return new TimeoutException(t);
}
/**
* Generate a request to commit consumed offsets. Add the request to the queue of pending
* requests to be sent out on the next call to {@link #poll(long)}. If there are empty
* offsets to commit, no request will be generated and a completed future will be returned.
*
* @param requestState Commit request
* @return Future containing the offsets that were committed, or an error if the request
* failed.
*/
private CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> requestAutoCommit(final OffsetCommitRequestState requestState) {
AutoCommitState autocommit = autoCommitState.get();
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result;
if (requestState.offsets.isEmpty()) {
result = CompletableFuture.completedFuture(Collections.emptyMap());
} else {
autocommit.setInflightCommitStatus(true);
OffsetCommitRequestState request = pendingRequests.addOffsetCommitRequest(requestState);
result = request.future;
result.whenComplete(autoCommitCallback(request.offsets));
}
return result;
}
/**
* If auto-commit is enabled, and the auto-commit interval has expired, this will generate and
* enqueue a request to commit all consumed offsets, and will reset the auto-commit timer to the
* interval. The request will be sent on the next call to {@link #poll(long)}.
* <p/>
* If the request completes with a retriable error, this will reset the auto-commit timer with
* the exponential backoff. If it fails with a non-retriable error, no action is taken, so
* the next commit will be generated when the interval expires.
* <p/>
* This will not generate a new commit request if a previous one hasn't received a response.
* In that case, the next auto-commit request will be sent on the next call to poll, after a
* response for the in-flight is received.
*/
private void maybeAutoCommitAsync() {
if (autoCommitEnabled() && autoCommitState.get().shouldAutoCommit()) {
OffsetCommitRequestState requestState = createOffsetCommitRequest(
subscriptions.allConsumed(),
Long.MAX_VALUE);
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result = requestAutoCommit(requestState);
// Reset timer to the interval (even if no request was generated), but ensure that if
// the request completes with a retriable error, the timer is reset to send the next
// auto-commit after the backoff expires.
resetAutoCommitTimer();
maybeResetTimerWithBackoff(result);
}
}
/**
* Reset auto-commit timer to retry with backoff if the future failed with a RetriableCommitFailedException.
*/
private void maybeResetTimerWithBackoff(final CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result) {
result.whenComplete((offsets, error) -> {
if (error != null) {
if (error instanceof RetriableCommitFailedException) {
log.debug("Asynchronous auto-commit of offsets {} failed due to retriable error.", offsets, error);
resetAutoCommitTimer(retryBackoffMs);
} else {
log.debug("Asynchronous auto-commit of offsets {} failed: {}", offsets, error.getMessage());
}
} else {
log.debug("Completed asynchronous auto-commit of offsets {}", offsets);
}
});
}
/**
* Commit consumed offsets if auto-commit is enabled, regardless of the auto-commit interval.
* This is used for committing offsets before rebalance. This will retry committing
* the latest offsets until the request succeeds, fails with a fatal error, or the timeout
* expires. Note that:
* <ul>
* <li>Considers {@link Errors#STALE_MEMBER_EPOCH} as a retriable error, and will retry it
* including the member ID and latest member epoch received from the broker.</li>
* <li>Considers {@link Errors#UNKNOWN_TOPIC_OR_PARTITION} as a fatal error, and will not
* retry it although the error extends RetriableException. The reason is that if a topic
* or partition is deleted, rebalance would not finish in time since the auto commit would keep retrying.</li>
* </ul>
*
* Also note that this will generate a commit request even if there is another one in-flight,
* generated by the auto-commit on the interval logic, to ensure that the latest offsets are
* committed before rebalance.
*
* @return Future that will complete when the offsets are successfully committed. It will
* complete exceptionally if the commit fails with a non-retriable error, or if the retry
* timeout expires.
*/
public CompletableFuture<Void> maybeAutoCommitSyncBeforeRebalance(final long deadlineMs) {
if (!autoCommitEnabled()) {
return CompletableFuture.completedFuture(null);
}
CompletableFuture<Void> result = new CompletableFuture<>();
OffsetCommitRequestState requestState =
createOffsetCommitRequest(subscriptions.allConsumed(), deadlineMs);
autoCommitSyncBeforeRebalanceWithRetries(requestState, result);
return result;
}
private void autoCommitSyncBeforeRebalanceWithRetries(OffsetCommitRequestState requestAttempt,
CompletableFuture<Void> result) {
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> commitAttempt = requestAutoCommit(requestAttempt);
commitAttempt.whenComplete((committedOffsets, error) -> {
if (error == null) {
result.complete(null);
} else {
if (error instanceof RetriableException || isStaleEpochErrorAndValidEpochAvailable(error)) {
if (requestAttempt.isExpired()) {
log.debug("Auto-commit sync before rebalance timed out and won't be retried anymore");
result.completeExceptionally(maybeWrapAsTimeoutException(error));
} else if (error instanceof UnknownTopicOrPartitionException) {
log.debug("Auto-commit sync before rebalance failed because topic or partition were deleted");
result.completeExceptionally(error);
} else {
// Make sure the auto-commit is retried with the latest offsets
log.debug("Member {} will retry auto-commit of latest offsets after receiving retriable error {}",
memberInfo.memberId,
error.getMessage());
requestAttempt.offsets = subscriptions.allConsumed();
requestAttempt.resetFuture();
autoCommitSyncBeforeRebalanceWithRetries(requestAttempt, result);
}
} else {
log.debug("Auto-commit sync before rebalance failed with non-retriable error", error);
result.completeExceptionally(error);
}
}
});
}
/**
* Clear the inflight auto-commit flag and log auto-commit completion status.
*/
private BiConsumer<? super Map<TopicPartition, OffsetAndMetadata>, ? super Throwable> autoCommitCallback(final Map<TopicPartition, OffsetAndMetadata> allConsumedOffsets) {
return (response, throwable) -> {
autoCommitState.ifPresent(autoCommitState -> autoCommitState.setInflightCommitStatus(false));
if (throwable == null) {
offsetCommitCallbackInvoker.enqueueInterceptorInvocation(allConsumedOffsets);
log.debug("Completed auto-commit of offsets {}", allConsumedOffsets);
} else if (throwable instanceof RetriableCommitFailedException) {
log.debug("Auto-commit of offsets {} failed due to retriable error: {}",
allConsumedOffsets, throwable.getMessage());
} else {
log.warn("Auto-commit of offsets {} failed", allConsumedOffsets, throwable);
}
};
}
/**
* Generate a request to commit offsets without retrying, even if it fails with a retriable
* error. The generated request will be added to the queue to be sent on the next call to
* {@link #poll(long)}.
*
* @param offsets Offsets to commit per partition.
* @return Future that will complete when a response is received, successfully or
* exceptionally depending on the response. If the request fails with a retriable error, the
* future will be completed with a {@link RetriableCommitFailedException}.
*/
public CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets) {
if (offsets.isEmpty()) {
log.debug("Skipping commit of empty offsets");
return CompletableFuture.completedFuture(Map.of());
}
maybeUpdateLastSeenEpochIfNewer(offsets);
OffsetCommitRequestState commitRequest = createOffsetCommitRequest(offsets, Long.MAX_VALUE);
pendingRequests.addOffsetCommitRequest(commitRequest);
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> asyncCommitResult = new CompletableFuture<>();
commitRequest.future.whenComplete((committedOffsets, error) -> {
if (error != null) {
asyncCommitResult.completeExceptionally(commitAsyncExceptionForError(error));
} else {
asyncCommitResult.complete(offsets);
}
});
return asyncCommitResult;
}
/**
* Commit offsets, retrying on expected retriable errors while the retry timeout hasn't expired.
*
* @param offsets Offsets to commit
* @param deadlineMs Time until which the request will be retried if it fails with
* an expected retriable error.
* @return Future that will complete when a successful response
*/
public CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> commitSync(final Map<TopicPartition, OffsetAndMetadata> offsets,
final long deadlineMs) {
if (offsets.isEmpty()) {
return CompletableFuture.completedFuture(Map.of());
}
maybeUpdateLastSeenEpochIfNewer(offsets);
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result = new CompletableFuture<>();
OffsetCommitRequestState requestState = createOffsetCommitRequest(offsets, deadlineMs);
commitSyncWithRetries(requestState, result);
return result;
}
private OffsetCommitRequestState createOffsetCommitRequest(final Map<TopicPartition, OffsetAndMetadata> offsets,
final long deadlineMs) {
return jitter.isPresent() ?
new OffsetCommitRequestState(
offsets,
groupId,
groupInstanceId,
deadlineMs,
retryBackoffMs,
retryBackoffMaxMs,
jitter.getAsDouble(),
memberInfo) :
new OffsetCommitRequestState(
offsets,
groupId,
groupInstanceId,
deadlineMs,
retryBackoffMs,
retryBackoffMaxMs,
memberInfo);
}
private void commitSyncWithRetries(OffsetCommitRequestState requestAttempt,
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result) {
pendingRequests.addOffsetCommitRequest(requestAttempt);
// Retry the same commit request while it fails with RetriableException and the retry
// timeout hasn't expired.
requestAttempt.future.whenComplete((res, error) -> {
if (error == null) {
result.complete(requestAttempt.offsets);
} else {
if (error instanceof RetriableException) {
if (requestAttempt.isExpired()) {
log.info("OffsetCommit timeout expired so it won't be retried anymore");
result.completeExceptionally(maybeWrapAsTimeoutException(error));
} else {
requestAttempt.resetFuture();
commitSyncWithRetries(requestAttempt, result);
}
} else {
result.completeExceptionally(commitSyncExceptionForError(error));
}
}
});
}
private Throwable commitSyncExceptionForError(Throwable error) {
if (error instanceof StaleMemberEpochException) {
return new CommitFailedException("OffsetCommit failed with stale member epoch. "
+ Errors.STALE_MEMBER_EPOCH.message());
}
return error;
}
private Throwable commitAsyncExceptionForError(Throwable error) {
if (error instanceof RetriableException) {
return new RetriableCommitFailedException(error);
}
return error;
}
/**
* Enqueue a request to fetch committed offsets, that will be sent on the next call to {@link #poll(long)}.
*
* @param partitions Partitions to fetch offsets for.
* @param deadlineMs Time until which the request should be retried if it fails
* with expected retriable errors.
* @return Future that will complete when a successful response is received, or the request
* fails and cannot be retried. Note that the request is retried whenever it fails with
* retriable expected error and the retry time hasn't expired.
*/
public CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> fetchOffsets(
final Set<TopicPartition> partitions,
final long deadlineMs) {
if (partitions.isEmpty()) {
return CompletableFuture.completedFuture(Collections.emptyMap());
}
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result = new CompletableFuture<>();
OffsetFetchRequestState request = createOffsetFetchRequest(partitions, deadlineMs);
fetchOffsetsWithRetries(request, result);
return result;
}
// Visible for testing
OffsetFetchRequestState createOffsetFetchRequest(final Set<TopicPartition> partitions,
final long deadlineMs) {
return jitter.isPresent() ?
new OffsetFetchRequestState(
partitions,
retryBackoffMs,
retryBackoffMaxMs,
deadlineMs,
jitter.getAsDouble(),
memberInfo) :
new OffsetFetchRequestState(
partitions,
retryBackoffMs,
retryBackoffMaxMs,
deadlineMs,
memberInfo);
}
private void fetchOffsetsWithRetries(final OffsetFetchRequestState fetchRequest,
final CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result) {
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> currentResult = pendingRequests.addOffsetFetchRequest(fetchRequest);
// Retry the same fetch request while it fails with RetriableException and the retry timeout hasn't expired.
currentResult.whenComplete((res, error) -> {
boolean inflightRemoved = pendingRequests.inflightOffsetFetches.remove(fetchRequest);
if (!inflightRemoved) {
log.warn("A duplicated, inflight, request was identified, but unable to find it in the " +
"outbound buffer: {}", fetchRequest);
}
if (error == null) {
maybeUpdateLastSeenEpochIfNewer(res);
result.complete(res);
} else {
if (error instanceof RetriableException || isStaleEpochErrorAndValidEpochAvailable(error)) {
if (fetchRequest.isExpired()) {
log.debug("OffsetFetch request for {} timed out and won't be retried anymore", fetchRequest.requestedPartitions);
result.completeExceptionally(maybeWrapAsTimeoutException(error));
} else {
fetchRequest.resetFuture();
fetchOffsetsWithRetries(fetchRequest, result);
}
} else
result.completeExceptionally(error);
}
});
}
private boolean isStaleEpochErrorAndValidEpochAvailable(Throwable error) {
return error instanceof StaleMemberEpochException && memberInfo.memberEpoch.isPresent();
}
private void updateAutoCommitTimer(final long currentTimeMs) {
this.autoCommitState.ifPresent(t -> t.updateTimer(currentTimeMs));
}
// Visible for testing
Queue<OffsetCommitRequestState> unsentOffsetCommitRequests() {
return pendingRequests.unsentOffsetCommits;
}
private List<OffsetFetchRequestState> unsentOffsetFetchRequests() {
return pendingRequests.unsentOffsetFetches;
}
/**
* Update latest member epoch used by the member.
*
* @param memberEpoch New member epoch received. To be included in the new request.
* @param memberId Current member ID. To be included in the new request.
*/
@Override
public void onMemberEpochUpdated(Optional<Integer> memberEpoch, String memberId) {
if (memberEpoch.isEmpty() && memberInfo.memberEpoch.isPresent()) {
log.info("Member {} won't include epoch in following offset " +
"commit/fetch requests because it has left the group.", memberInfo.memberId);
} else if (memberEpoch.isPresent()) {
log.debug("Member {} will include new member epoch {} in following offset commit/fetch requests.", memberId, memberEpoch);
}
memberInfo.memberId = memberId;
memberInfo.memberEpoch = memberEpoch;
}
/**
* @return True if auto-commit is enabled as defined in the config {@link ConsumerConfig#ENABLE_AUTO_COMMIT_CONFIG}
*/
public boolean autoCommitEnabled() {
return autoCommitState.isPresent();
}
/**
* Reset the auto-commit timer to the auto-commit interval, so that the next auto-commit is
* sent out on the interval starting from now. If auto-commit is not enabled this will
* perform no action.
*/
public void resetAutoCommitTimer() {
autoCommitState.ifPresent(AutoCommitState::resetTimer);
}
/**
* Reset the auto-commit timer to the provided time (backoff), so that the next auto-commit is
* sent out then. If auto-commit is not enabled this will perform no action.
*/
public void resetAutoCommitTimer(long retryBackoffMs) {
autoCommitState.ifPresent(s -> s.resetTimer(retryBackoffMs));
}
/**
* Drains the inflight offsetCommits during shutdown because we want to make sure all pending commits are sent
* before closing.
*/
public NetworkClientDelegate.PollResult drainPendingOffsetCommitRequests() {
if (pendingRequests.unsentOffsetCommits.isEmpty())
return EMPTY;
List<NetworkClientDelegate.UnsentRequest> requests = pendingRequests.drainPendingCommits();
return new NetworkClientDelegate.PollResult(Long.MAX_VALUE, requests);
}
private void maybeUpdateLastSeenEpochIfNewer(final Map<TopicPartition, OffsetAndMetadata> offsets) {
offsets.forEach((topicPartition, offsetAndMetadata) -> {
if (offsetAndMetadata != null)
offsetAndMetadata.leaderEpoch().ifPresent(epoch -> metadata.updateLastSeenEpochIfNewer(topicPartition, epoch));
});
}
/**
* This is a non-blocking method to update timer and trigger async auto-commit.
* <p>
* This method performs two main tasks:
* <ol>
* <li>Updates the internal timer with the current time.</li>
* <li>Initiate an asynchronous auto-commit operation for all consumed positions if needed.</li>
* </ol>
*
* @param currentTimeMs the current timestamp in millisecond
* @see CommitRequestManager#updateAutoCommitTimer(long)
* @see CommitRequestManager#maybeAutoCommitAsync()
*/
public void updateTimerAndMaybeCommit(final long currentTimeMs) {
updateAutoCommitTimer(currentTimeMs);
maybeAutoCommitAsync();
}
|
CommitRequestManager
|
java
|
apache__camel
|
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpProducerFileFastExistFailIT.java
|
{
"start": 871,
"end": 1162
}
|
class ____ extends FtpProducerFileExistFailIT {
@Override
protected String getFtpUrl() {
return "ftp://admin@localhost:{{ftp.server.port}}"
+ "/exist?fastExistsCheck=true&password=admin&delay=2000&noop=true&fileExist=Fail";
}
}
|
FtpProducerFileFastExistFailIT
|
java
|
apache__spark
|
common/variant/src/main/java/org/apache/spark/types/variant/VariantSchema.java
|
{
"start": 2232,
"end": 2296
}
|
class ____ extends ScalarType {
}
public static final
|
FloatType
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/query/hql/internal/BasicDotIdentifierConsumer.java
|
{
"start": 1647,
"end": 1752
}
|
class ____ (entity or otherwise)
* <li>static field references, e.g. {@code MyClass.SOME_FIELD}
* <li>
|
names
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
|
{
"start": 63814,
"end": 64271
}
|
interface ____");
});
}
@Test
public void
injectParameterDoesNotSuppressWildcardGeneration_conflictsWithNonWildcardTypeBinding() {
Source component =
CompilerTests.javaSource(
"test.MyComponent",
"package test;",
"",
"import dagger.Component;",
"import java.util.Set;",
"",
"@Component(modules = TestModule.class)",
"
|
MyComponent
|
java
|
apache__camel
|
components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpOnExceptionHandledTest.java
|
{
"start": 1098,
"end": 2656
}
|
class ____ extends BaseNettyTest {
@Test
public void testOnExceptionHandled() {
Exchange reply = template.request("netty-http:http://localhost:{{port}}/myserver?throwExceptionOnFailure=false", null);
assertNotNull(reply);
assertEquals("Dude something went wrong", reply.getMessage().getBody(String.class));
assertEquals(500, reply.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE));
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
// START SNIPPET: e1
from("netty-http:http://localhost:{{port}}/myserver")
// use onException to catch all exceptions and return a custom reply message
.onException(Exception.class)
.handled(true)
// create a custom failure response
.transform(constant("Dude something went wrong"))
// we must remember to set error code 500 as handled(true)
// otherwise would let Camel thing its a OK response (200)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(500))
.end()
// now just force an exception immediately
.throwException(new IllegalArgumentException("I cannot do this"));
// END SNIPPET: e1
}
};
}
}
|
NettyHttpOnExceptionHandledTest
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/scheduling/support/BitsCronField.java
|
{
"start": 1105,
"end": 7531
}
|
class ____ extends CronField {
public static final BitsCronField ZERO_NANOS = forZeroNanos();
private static final long MASK = 0xFFFFFFFFFFFFFFFFL;
// we store at most 60 bits, for seconds and minutes, so a 64-bit long suffices
private long bits;
private BitsCronField(Type type) {
super(type);
}
/**
* Return a {@code BitsCronField} enabled for 0 nanoseconds.
*/
private static BitsCronField forZeroNanos() {
BitsCronField field = new BitsCronField(Type.NANO);
field.setBit(0);
return field;
}
/**
* Parse the given value into a seconds {@code BitsCronField}, the first entry of a cron expression.
*/
public static BitsCronField parseSeconds(String value) {
return parseField(value, Type.SECOND);
}
/**
* Parse the given value into a minutes {@code BitsCronField}, the second entry of a cron expression.
*/
public static BitsCronField parseMinutes(String value) {
return BitsCronField.parseField(value, Type.MINUTE);
}
/**
* Parse the given value into an hours {@code BitsCronField}, the third entry of a cron expression.
*/
public static BitsCronField parseHours(String value) {
return BitsCronField.parseField(value, Type.HOUR);
}
/**
* Parse the given value into a days of months {@code BitsCronField}, the fourth entry of a cron expression.
*/
public static BitsCronField parseDaysOfMonth(String value) {
return parseDate(value, Type.DAY_OF_MONTH);
}
/**
* Parse the given value into a month {@code BitsCronField}, the fifth entry of a cron expression.
*/
public static BitsCronField parseMonth(String value) {
return BitsCronField.parseField(value, Type.MONTH);
}
/**
* Parse the given value into a days of week {@code BitsCronField}, the sixth entry of a cron expression.
*/
public static BitsCronField parseDaysOfWeek(String value) {
BitsCronField result = parseDate(value, Type.DAY_OF_WEEK);
if (result.getBit(0)) {
// cron supports 0 for Sunday; we use 7 like java.time
result.setBit(7);
result.clearBit(0);
}
return result;
}
private static BitsCronField parseDate(String value, BitsCronField.Type type) {
if (value.equals("?")) {
value = "*";
}
return BitsCronField.parseField(value, type);
}
private static BitsCronField parseField(String value, Type type) {
Assert.hasLength(value, "Value must not be empty");
Assert.notNull(type, "Type must not be null");
try {
BitsCronField result = new BitsCronField(type);
String[] fields = StringUtils.delimitedListToStringArray(value, ",");
for (String field : fields) {
int slashPos = field.indexOf('/');
if (slashPos == -1) {
ValueRange range = parseRange(field, type);
result.setBits(range);
}
else {
String rangeStr = field.substring(0, slashPos);
String deltaStr = field.substring(slashPos + 1);
ValueRange range = parseRange(rangeStr, type);
if (rangeStr.indexOf('-') == -1) {
range = ValueRange.of(range.getMinimum(), type.range().getMaximum());
}
int delta = Integer.parseInt(deltaStr);
if (delta <= 0) {
throw new IllegalArgumentException("Incrementer delta must be 1 or higher");
}
result.setBits(range, delta);
}
}
return result;
}
catch (DateTimeException | IllegalArgumentException ex) {
String msg = ex.getMessage() + " '" + value + "'";
throw new IllegalArgumentException(msg, ex);
}
}
private static ValueRange parseRange(String value, Type type) {
if (value.equals("*")) {
return type.range();
}
else {
int hyphenPos = value.indexOf('-');
if (hyphenPos == -1) {
int result = type.checkValidValue(Integer.parseInt(value));
return ValueRange.of(result, result);
}
else {
int min = Integer.parseInt(value, 0, hyphenPos, 10);
int max = Integer.parseInt(value, hyphenPos + 1, value.length(), 10);
min = type.checkValidValue(min);
max = type.checkValidValue(max);
if (type == Type.DAY_OF_WEEK && min == 7) {
// If used as a minimum in a range, Sunday means 0 (not 7)
min = 0;
}
return ValueRange.of(min, max);
}
}
}
@Override
public <T extends Temporal & Comparable<? super T>> @Nullable T nextOrSame(T temporal) {
int current = type().get(temporal);
int next = nextSetBit(current);
if (next == -1) {
temporal = type().rollForward(temporal);
next = nextSetBit(0);
}
if (next == current) {
return temporal;
}
else {
int count = 0;
current = type().get(temporal);
while (current != next && count++ < CronExpression.MAX_ATTEMPTS) {
temporal = type().elapseUntil(temporal, next);
current = type().get(temporal);
next = nextSetBit(current);
if (next == -1) {
temporal = type().rollForward(temporal);
next = nextSetBit(0);
}
}
if (count >= CronExpression.MAX_ATTEMPTS) {
return null;
}
return type().reset(temporal);
}
}
boolean getBit(int index) {
return (this.bits & (1L << index)) != 0;
}
private int nextSetBit(int fromIndex) {
long result = this.bits & (MASK << fromIndex);
if (result != 0) {
return Long.numberOfTrailingZeros(result);
}
else {
return -1;
}
}
private void setBits(ValueRange range) {
if (range.getMinimum() == range.getMaximum()) {
setBit((int) range.getMinimum());
}
else {
long minMask = MASK << range.getMinimum();
long maxMask = MASK >>> - (range.getMaximum() + 1);
this.bits |= (minMask & maxMask);
}
}
private void setBits(ValueRange range, int delta) {
if (delta == 1) {
setBits(range);
}
else {
for (int i = (int) range.getMinimum(); i <= range.getMaximum(); i += delta) {
setBit(i);
}
}
}
private void setBit(int index) {
this.bits |= (1L << index);
}
private void clearBit(int index) {
this.bits &= ~(1L << index);
}
@Override
public boolean equals(Object other) {
return (this == other || (other instanceof BitsCronField that &&
type() == that.type() && this.bits == that.bits));
}
@Override
public int hashCode() {
return Long.hashCode(this.bits);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(type().toString());
builder.append(" {");
int i = nextSetBit(0);
if (i != -1) {
builder.append(i);
i = nextSetBit(i+1);
while (i != -1) {
builder.append(", ");
builder.append(i);
i = nextSetBit(i+1);
}
}
builder.append('}');
return builder.toString();
}
}
|
BitsCronField
|
java
|
apache__camel
|
components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/spring/tx/error/TransactionErrorHandlerCustomerSpringParserIT.java
|
{
"start": 1344,
"end": 2173
}
|
class ____ extends AbstractSpringJMSITSupport {
@Override
protected ClassPathXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext(
"/org/apache/camel/component/jms/integration/spring/tx/error/TransactionErrorHandlerCustomerSpringParserIT.xml");
}
@Test
public void testTransactionSuccess() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.expectedBodiesReceived("Bye World");
// success at 3rd attempt
mock.message(0).header("count").isEqualTo(3);
template.sendBody("activemq:queue:okay.TransactionErrorHandlerCustomerSpringParserTest", "Hello World");
mock.assertIsSatisfied();
}
}
|
TransactionErrorHandlerCustomerSpringParserIT
|
java
|
apache__flink
|
flink-metrics/flink-metrics-datadog/src/test/java/org/apache/flink/metrics/datadog/DatadogHttpClientTest.java
|
{
"start": 1690,
"end": 7869
}
|
class ____ {
private static final List<String> tags = Arrays.asList("tag1", "tag2");
private static final String TAGS_AS_JSON =
tags.stream().collect(Collectors.joining("\",\"", "[\"", "\"]"));
private static final String HOST = "localhost";
private static final String METRIC = "testMetric";
private static final ObjectMapper MAPPER;
static {
MAPPER = new ObjectMapper();
MAPPER.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
}
private static final long MOCKED_SYSTEM_MILLIS = 123L;
@Test
void testClientWithEmptyKey() {
assertThatThrownBy(() -> new DatadogHttpClient("", null, 123, DataCenter.US, false))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void testClientWithNullKey() {
assertThatThrownBy(() -> new DatadogHttpClient(null, null, 123, DataCenter.US, false))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void testGetProxyWithNullProxyHost() {
DatadogHttpClient client =
new DatadogHttpClient("anApiKey", null, 123, DataCenter.US, false);
assert (client.getProxy() == Proxy.NO_PROXY);
}
@Test
void testGetProxy() {
DatadogHttpClient client =
new DatadogHttpClient("anApiKey", "localhost", 123, DataCenter.US, false);
assertThat(client.getProxy().address()).isInstanceOf(InetSocketAddress.class);
InetSocketAddress proxyAddress = (InetSocketAddress) client.getProxy().address();
assertThat(proxyAddress.getPort()).isEqualTo(123);
assertThat(proxyAddress.getHostString()).isEqualTo("localhost");
}
@Test
void serializeGauge() throws JsonProcessingException {
DSeries series = new DSeries();
series.add(new DGauge(() -> 1, METRIC, HOST, tags, () -> MOCKED_SYSTEM_MILLIS));
assertSerialization(
DatadogHttpClient.serialize(series),
new MetricAssertion(MetricType.gauge, true, "1"));
}
@Test
void serializeGaugeWithoutHost() throws JsonProcessingException {
DSeries series = new DSeries();
series.add(new DGauge(() -> 1, METRIC, null, tags, () -> MOCKED_SYSTEM_MILLIS));
assertSerialization(
DatadogHttpClient.serialize(series),
new MetricAssertion(MetricType.gauge, false, "1"));
}
@Test
void serializeCounter() throws JsonProcessingException {
DSeries series = new DSeries();
series.add(
new DCounter(new TestCounter(1), METRIC, HOST, tags, () -> MOCKED_SYSTEM_MILLIS));
assertSerialization(
DatadogHttpClient.serialize(series),
new MetricAssertion(MetricType.count, true, "1"));
}
@Test
void serializeCounterWithoutHost() throws JsonProcessingException {
DSeries series = new DSeries();
series.add(
new DCounter(new TestCounter(1), METRIC, null, tags, () -> MOCKED_SYSTEM_MILLIS));
assertSerialization(
DatadogHttpClient.serialize(series),
new MetricAssertion(MetricType.count, false, "1"));
}
@Test
void serializeMeter() throws JsonProcessingException {
DSeries series = new DSeries();
series.add(new DMeter(new TestMeter(0, 1), METRIC, HOST, tags, () -> MOCKED_SYSTEM_MILLIS));
assertSerialization(
DatadogHttpClient.serialize(series),
new MetricAssertion(MetricType.gauge, true, "1.0"));
}
@Test
void serializeMeterWithoutHost() throws JsonProcessingException {
DSeries series = new DSeries();
series.add(new DMeter(new TestMeter(0, 1), METRIC, null, tags, () -> MOCKED_SYSTEM_MILLIS));
assertSerialization(
DatadogHttpClient.serialize(series),
new MetricAssertion(MetricType.gauge, false, "1.0"));
}
@Test
void serializeHistogram() throws JsonProcessingException {
DHistogram h =
new DHistogram(new TestHistogram(), METRIC, HOST, tags, () -> MOCKED_SYSTEM_MILLIS);
DSeries series = new DSeries();
h.addTo(series);
assertSerialization(
DatadogHttpClient.serialize(series),
new MetricAssertion(MetricType.gauge, true, "4.0", DHistogram.SUFFIX_AVG),
new MetricAssertion(MetricType.gauge, true, "1", DHistogram.SUFFIX_COUNT),
new MetricAssertion(MetricType.gauge, true, "0.5", DHistogram.SUFFIX_MEDIAN),
new MetricAssertion(
MetricType.gauge, true, "0.95", DHistogram.SUFFIX_95_PERCENTILE),
new MetricAssertion(MetricType.gauge, true, "7", DHistogram.SUFFIX_MIN),
new MetricAssertion(MetricType.gauge, true, "6", DHistogram.SUFFIX_MAX));
}
private static void assertSerialization(String json, MetricAssertion... metricAssertions)
throws JsonProcessingException {
final JsonNode series = MAPPER.readTree(json).get(DSeries.FIELD_NAME_SERIES);
for (int i = 0; i < metricAssertions.length; i++) {
final JsonNode parsedJson = series.get(i);
final MetricAssertion metricAssertion = metricAssertions[i];
if (metricAssertion.expectHost) {
assertThat(parsedJson.get(DMetric.FIELD_NAME_HOST).asText()).isEqualTo(HOST);
} else {
assertThat(parsedJson.get(DMetric.FIELD_NAME_HOST)).isNull();
}
assertThat(parsedJson.get(DMetric.FIELD_NAME_METRIC).asText())
.isEqualTo(METRIC + metricAssertion.metricNameSuffix);
assertThat(parsedJson.get(DMetric.FIELD_NAME_TYPE).asText())
.isEqualTo(metricAssertion.expectedType.name());
assertThat(parsedJson.get(DMetric.FIELD_NAME_POINTS).toString())
.isEqualTo(String.format("[[123,%s]]", metricAssertion.expectedValue));
assertThat(parsedJson.get(DMetric.FIELD_NAME_TAGS).toString()).isEqualTo(TAGS_AS_JSON);
}
}
private static final
|
DatadogHttpClientTest
|
java
|
spring-projects__spring-security
|
webauthn/src/main/java/org/springframework/security/web/webauthn/jackson/AuthenticatorTransportDeserializer.java
|
{
"start": 1133,
"end": 1692
}
|
class ____ extends StdDeserializer<AuthenticatorTransport> {
AuthenticatorTransportDeserializer() {
super(AuthenticatorTransport.class);
}
@Override
public @Nullable AuthenticatorTransport deserialize(JsonParser parser, DeserializationContext ctxt)
throws JacksonException {
String transportValue = parser.readValueAs(String.class);
for (AuthenticatorTransport transport : AuthenticatorTransport.values()) {
if (transport.getValue().equals(transportValue)) {
return transport;
}
}
return null;
}
}
|
AuthenticatorTransportDeserializer
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/CommitOnCloseEvent.java
|
{
"start": 867,
"end": 999
}
|
class ____ extends ApplicationEvent {
public CommitOnCloseEvent() {
super(Type.COMMIT_ON_CLOSE);
}
}
|
CommitOnCloseEvent
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/model/process/internal/NamedBasicTypeResolution.java
|
{
"start": 552,
"end": 1950
}
|
class ____<J> implements BasicValue.Resolution<J> {
private final JavaType<J> domainJtd;
private final BasicType<J> basicType;
private final BasicValueConverter<J,?> valueConverter;
private final MutabilityPlan<J> mutabilityPlan;
public NamedBasicTypeResolution(
JavaType<J> domainJtd,
BasicType<J> basicType,
BasicValueConverter<J,?> valueConverter,
MutabilityPlan<J> explicitPlan) {
this.domainJtd = domainJtd;
this.basicType = basicType;
// todo (6.0) : does it even make sense to allow a combo of explicit Type and a converter?
this.valueConverter = valueConverter;
this.mutabilityPlan = explicitPlan != null ? explicitPlan : domainJtd.getMutabilityPlan();
}
@Override
public JdbcMapping getJdbcMapping() {
return basicType;
}
@Override
public BasicType<J> getLegacyResolvedBasicType() {
return basicType;
}
@Override
public JavaType<J> getDomainJavaType() {
return domainJtd;
}
@Override
public JavaType<?> getRelationalJavaType() {
return valueConverter == null
? basicType.getJavaTypeDescriptor()
: valueConverter.getRelationalJavaType();
}
@Override
public JdbcType getJdbcType() {
return basicType.getJdbcType();
}
@Override
public BasicValueConverter<J,?> getValueConverter() {
return valueConverter;
}
@Override
public MutabilityPlan<J> getMutabilityPlan() {
return mutabilityPlan;
}
}
|
NamedBasicTypeResolution
|
java
|
apache__dubbo
|
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ProxyDescriberRegistrar.java
|
{
"start": 920,
"end": 1011
}
|
interface ____ {
List<JdkProxyDescriber> getJdkProxyDescribers();
}
|
ProxyDescriberRegistrar
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/impl/LifecycleStrategyFailOnStartupTest.java
|
{
"start": 1710,
"end": 1927
}
|
class ____ extends DummyLifecycleStrategy {
@Override
public void onContextStarting(CamelContext context) {
throw new IllegalArgumentException("Forced");
}
}
}
|
MyLifecycleStrategy
|
java
|
bumptech__glide
|
annotation/compiler/test/src/test/java/com/bumptech/glide/annotation/compiler/InvalidGlideTypeExtensionTest.java
|
{
"start": 1862,
"end": 3263
}
|
class ____ {",
" private Extension() {}",
" @NonNull",
" @GlideType(Number.class)",
" public RequestBuilder<Number> doSomething(",
" RequestBuilder<Number> builder) {",
" return builder;",
" }",
"}"));
}
});
}
@Test
public void compilation_withAnnotatedStaticMethod_withoutRequestBuilderArg_fails() {
assertThrows(
"@GlideType methods must take a RequestBuilder object as their first and only"
+ " parameter, but given multiple for:"
+ " com.bumptech.glide.test.Extension#doSomething()",
RuntimeException.class,
new ThrowingRunnable() {
@Override
public void run() {
javac()
.withProcessors(new GlideAnnotationProcessor())
.compile(
emptyAppModule(),
JavaFileObjects.forSourceLines(
"Extension",
"package com.bumptech.glide.test;",
"import com.bumptech.glide.annotation.GlideExtension;",
"import com.bumptech.glide.annotation.GlideType;",
"@GlideExtension",
"public
|
Extension
|
java
|
quarkusio__quarkus
|
extensions/liquibase/liquibase/deployment/src/test/java/io/quarkus/liquibase/test/LiquibaseExtensionMigrateAtStartNamedDataSourceTest.java
|
{
"start": 580,
"end": 1665
}
|
class ____ {
@Inject
@LiquibaseDataSource("users")
LiquibaseFactory liquibaseFactory;
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addAsResource("db/changeLog.xml", "db/changeLog.xml")
.addAsResource("migrate-at-start-config-named-datasource.properties", "application.properties"));
@Test
@DisplayName("Migrates at start for datasource named 'users' correctly")
public void testLiquibaseConfigInjection() throws Exception {
try (Liquibase liquibase = liquibaseFactory.createLiquibase()) {
List<ChangeSetStatus> status = liquibase.getChangeSetStatuses(liquibaseFactory.createContexts(),
liquibaseFactory.createLabels());
assertNotNull(status);
assertEquals(1, status.size());
assertEquals("id-1", status.get(0).getChangeSet().getId());
assertFalse(status.get(0).getWillRun());
}
}
}
|
LiquibaseExtensionMigrateAtStartNamedDataSourceTest
|
java
|
apache__camel
|
components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/annotation/AdviceRouteTest.java
|
{
"start": 2810,
"end": 3002
}
|
class ____ extends AdviceWithRouteBuilder {
@Override
public void configure() throws Exception {
replaceFromWith("direct:foo");
}
}
static
|
TestBuilder
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/test/java/org/apache/hadoop/mapreduce/v2/hs/webapp/TestHsWebServicesJobs.java
|
{
"start": 3307,
"end": 3940
}
|
class ____ extends JerseyTestBase {
private static Configuration conf = new Configuration();
private static MockHistoryContext appContext;
private static HsWebApp webApp;
private static ApplicationClientProtocol acp = mock(ApplicationClientProtocol.class);
@Override
protected Application configure() {
ResourceConfig config = new ResourceConfig();
config.register(new JerseyBinder());
config.register(HsWebServices.class);
config.register(GenericExceptionHandler.class);
config.register(new JettisonFeature()).register(JAXBContextResolver.class);
return config;
}
private
|
TestHsWebServicesJobs
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableAll.java
|
{
"start": 1376,
"end": 3170
}
|
class ____<T> extends DeferredScalarSubscription<Boolean> implements FlowableSubscriber<T> {
private static final long serialVersionUID = -3521127104134758517L;
final Predicate<? super T> predicate;
Subscription upstream;
boolean done;
AllSubscriber(Subscriber<? super Boolean> actual, Predicate<? super T> predicate) {
super(actual);
this.predicate = predicate;
}
@Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.validate(this.upstream, s)) {
this.upstream = s;
downstream.onSubscribe(this);
s.request(Long.MAX_VALUE);
}
}
@Override
public void onNext(T t) {
if (done) {
return;
}
boolean b;
try {
b = predicate.test(t);
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
upstream.cancel();
onError(e);
return;
}
if (!b) {
done = true;
upstream.cancel();
complete(false);
}
}
@Override
public void onError(Throwable t) {
if (done) {
RxJavaPlugins.onError(t);
return;
}
done = true;
downstream.onError(t);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
complete(true);
}
@Override
public void cancel() {
super.cancel();
upstream.cancel();
}
}
}
|
AllSubscriber
|
java
|
redisson__redisson
|
redisson-spring-data/redisson-spring-data-24/src/test/java/org/redisson/spring/data/connection/RedissonSubscribeTest.java
|
{
"start": 926,
"end": 4547
}
|
class ____ extends BaseConnectionTest {
@Test
public void testPatterTopic() throws IOException, InterruptedException {
RedisRunner.RedisProcess instance = new RedisRunner()
.nosave()
.randomPort()
.randomDir()
.notifyKeyspaceEvents(
RedisRunner.KEYSPACE_EVENTS_OPTIONS.K,
RedisRunner.KEYSPACE_EVENTS_OPTIONS.g,
RedisRunner.KEYSPACE_EVENTS_OPTIONS.E,
RedisRunner.KEYSPACE_EVENTS_OPTIONS.$)
.run();
Config config = new Config();
config.useSingleServer().setAddress(instance.getRedisServerAddressAndPort()).setPingConnectionInterval(0);
RedissonClient redisson = Redisson.create(config);
RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson);
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(factory);
AtomicInteger counterTest = new AtomicInteger();
container.addMessageListener(new MessageListener() {
@Override
public void onMessage(Message message, byte[] pattern) {
counterTest.incrementAndGet();
}
}, new PatternTopic("__keyspace@0__:mykey"));
container.addMessageListener(new MessageListener() {
@Override
public void onMessage(Message message, byte[] pattern) {
counterTest.incrementAndGet();
}
}, new PatternTopic("__keyevent@0__:del"));
container.afterPropertiesSet();
container.start();
Assertions.assertThat(container.isRunning()).isTrue();
RedisConnection c = factory.getConnection();
c.set("mykey".getBytes(), "2".getBytes());
c.del("mykey".getBytes());
Awaitility.await().atMost(Durations.FIVE_SECONDS).until(() -> {
return counterTest.get() == 3;
});
container.stop();
redisson.shutdown();
}
@Test
public void testSubscribe() {
RedissonConnection connection = new RedissonConnection(redisson);
AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
connection.subscribe(new MessageListener() {
@Override
public void onMessage(Message message, byte[] pattern) {
msg.set(message.getBody());
}
}, "test".getBytes());
connection.publish("test".getBytes(), "msg".getBytes());
Awaitility.await().atMost(Durations.ONE_SECOND)
.until(() -> Arrays.equals("msg".getBytes(), msg.get()));
connection.getSubscription().unsubscribe();
connection.publish("test".getBytes(), "msg".getBytes());
}
@Test
public void testUnSubscribe() {
RedissonConnection connection = new RedissonConnection(redisson);
AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
connection.subscribe(new MessageListener() {
@Override
public void onMessage(Message message, byte[] pattern) {
msg.set(message.getBody());
}
}, "test".getBytes());
connection.publish("test".getBytes(), "msg".getBytes());
Awaitility.await().atMost(Durations.ONE_SECOND)
.until(() -> Arrays.equals("msg".getBytes(), msg.get()));
connection.getSubscription().unsubscribe();
}
}
|
RedissonSubscribeTest
|
java
|
apache__flink
|
flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/StateChangeIteratorImpl.java
|
{
"start": 1182,
"end": 1802
}
|
class ____
implements StateChangelogHandleStreamHandleReader.StateChangeIterator {
private final ChangelogStreamHandleReader changelogStreamHandleReader;
public StateChangeIteratorImpl(ChangelogStreamHandleReader changelogStreamHandleReader) {
this.changelogStreamHandleReader = changelogStreamHandleReader;
}
@Override
public CloseableIterator<StateChange> read(StreamStateHandle handle, long offset)
throws IOException {
return new StateChangeFormat()
.read(changelogStreamHandleReader.openAndSeek(handle, offset));
}
}
|
StateChangeIteratorImpl
|
java
|
apache__kafka
|
server-common/src/main/java/org/apache/kafka/logger/StateChangeLogger.java
|
{
"start": 905,
"end": 1083
}
|
class ____ sets logIdent appropriately depending on whether the state change logger is being used in the
* context of the broker (e.g. ReplicaManager and Partition).
*/
public
|
that
|
java
|
apache__flink
|
flink-filesystems/flink-hadoop-fs/src/main/java/org/apache/flink/runtime/fs/hdfs/HadoopFsRecoverable.java
|
{
"start": 1340,
"end": 2469
}
|
class ____ implements CommitRecoverable, ResumeRecoverable {
/** The file path for the final result file. */
private final Path targetFile;
/** The file path of the staging file. */
private final Path tempFile;
/** The position to resume from. */
private final long offset;
/**
* Creates a resumable for the given file at the given position.
*
* @param targetFile The file to resume.
* @param offset The position to resume from.
*/
public HadoopFsRecoverable(Path targetFile, Path tempFile, long offset) {
checkArgument(offset >= 0, "offset must be >= 0");
this.targetFile = checkNotNull(targetFile, "targetFile");
this.tempFile = checkNotNull(tempFile, "tempFile");
this.offset = offset;
}
public Path targetFile() {
return targetFile;
}
public Path tempFile() {
return tempFile;
}
public long offset() {
return offset;
}
@Override
public String toString() {
return "HadoopFsRecoverable " + tempFile + " @ " + offset + " -> " + targetFile;
}
}
|
HadoopFsRecoverable
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/bytecode/internal/bytebuddy/ByteBuddyState.java
|
{
"start": 13811,
"end": 13896
}
|
class ____ be opened and exported to Hibernate ORM)", e );
}
}
private static
|
should
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/benckmark/sql/MySqlInsertBenchmark_2.java
|
{
"start": 453,
"end": 3385
}
|
class ____ extends TestCase {
static String sql = "INSERT INTO test_table VALUES (1, '1', '2017-10-10', true, false, '2017-10-10 10:10:10', '10:10:10', 1.111, NULL), (2, '2', '2017-10-10', true, false, '2017-10-10 10:10:10', '10:10:10', 2.222, NULL)" +
", (2, '2', '2017-09-09', true, false, '2017-10-10 10:10:10', '10:10:10', 3.333, NULL)" +
", (3, '3', '2017-10-10', true, false, '2017-10-10 10:10:10', '11:11:11', 4.333, NULL)" +
", (4, '4', '2017-10-10', true, false, '2017-10-10 10:10:10', '11:11:11', 4.333, NULL)" +
", (5, '5', '2017-10-10', true, false, '2017-10-10 10:10:10', '11:11:11', 4.333, NULL);";
List<SQLStatement> stmtList;
protected void setUp() throws Exception {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, JdbcConstants.MYSQL);
parser.config(SQLParserFeature.KeepInsertValueClauseOriginalString, true);
stmtList = parser.parseStatementList();
}
public void test_perf() throws Exception {
System.out.println(sql);
for (int i = 0; i < 5; ++i) {
// perf(); // 5043
perf_toString(); // 2101
// perf_toString_featured(); // 7493
}
}
public void perf() {
long startMillis = System.currentTimeMillis();
for (int i = 0; i < 1000 * 1000; ++i) {
List<SQLStatement> stmt = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
// stmt.toString();
}
long millis = System.currentTimeMillis() - startMillis;
System.out.println("millis : " + millis);
}
public void perf_keepInsertValueClauseStrinng() {
long startMillis = System.currentTimeMillis();
for (int i = 0; i < 1000 * 1000; ++i) {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, JdbcConstants.MYSQL);
parser.config(SQLParserFeature.KeepInsertValueClauseOriginalString, true);
List<SQLStatement> stmtList = parser.parseStatementList();
// stmt.toString();
}
long millis = System.currentTimeMillis() - startMillis;
System.out.println("millis : " + millis);
}
public void perf_toString() {
long startMillis = System.currentTimeMillis();
for (int i = 0; i < 1000 * 1000; ++i) {
SQLUtils.toMySqlString(stmtList.get(0));
}
long millis = System.currentTimeMillis() - startMillis;
System.out.println("millis : " + millis);
}
public void perf_toString_featured() {
long startMillis = System.currentTimeMillis();
for (int i = 0; i < 1000 * 1000 * 10; ++i) {
SQLUtils.toMySqlString(stmtList.get(0), VisitorFeature.OutputUseInsertValueClauseOriginalString);
}
long millis = System.currentTimeMillis() - startMillis;
System.out.println("millis : " + millis);
}
}
|
MySqlInsertBenchmark_2
|
java
|
apache__avro
|
lang/java/avro/src/test/java/org/apache/avro/data/TestTimeConversions.java
|
{
"start": 11679,
"end": 11782
}
|
class ____
Class<?> cls = Class.forName(className);
// get the reflected schema for the given
|
name
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/data/RawValueData.java
|
{
"start": 1217,
"end": 1268
}
|
class ____ the raw value
*/
@PublicEvolving
public
|
for
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/engine/RecoverySourcePruneMergePolicy.java
|
{
"start": 1720,
"end": 4119
}
|
class ____ extends OneMergeWrappingMergePolicy {
RecoverySourcePruneMergePolicy(
@Nullable String pruneStoredFieldName,
String pruneNumericDVFieldName,
boolean pruneIdField,
Supplier<Query> retainSourceQuerySupplier,
MergePolicy in
) {
super(in, toWrap -> new OneMerge(toWrap.segments) {
@Override
public CodecReader wrapForMerge(CodecReader reader) throws IOException {
CodecReader wrapped = toWrap.wrapForMerge(reader);
return wrapReader(pruneStoredFieldName, pruneNumericDVFieldName, pruneIdField, wrapped, retainSourceQuerySupplier);
}
});
}
private static CodecReader wrapReader(
String pruneStoredFieldName,
String pruneNumericDVFieldName,
boolean pruneIdField,
CodecReader reader,
Supplier<Query> retainSourceQuerySupplier
) throws IOException {
NumericDocValues recoverySource = reader.getNumericDocValues(pruneNumericDVFieldName);
if (recoverySource == null || recoverySource.nextDoc() == DocIdSetIterator.NO_MORE_DOCS) {
return reader; // early terminate - nothing to do here since non of the docs has a recovery source anymore.
}
IndexSearcher s = new IndexSearcher(reader);
s.setQueryCache(null);
Weight weight = s.createWeight(s.rewrite(retainSourceQuerySupplier.get()), ScoreMode.COMPLETE_NO_SCORES, 1.0f);
Scorer scorer = weight.scorer(reader.getContext());
if (scorer != null) {
BitSet recoverySourceToKeep = BitSet.of(scorer.iterator(), reader.maxDoc());
// calculating the cardinality is significantly cheaper than skipping all bulk-merging we might do
// if retentions are high we keep most of it
if (recoverySourceToKeep.cardinality() == reader.maxDoc()) {
return reader; // keep all source
}
return new SourcePruningFilterCodecReader(
pruneStoredFieldName,
pruneNumericDVFieldName,
pruneIdField,
reader,
recoverySourceToKeep
);
} else {
return new SourcePruningFilterCodecReader(pruneStoredFieldName, pruneNumericDVFieldName, pruneIdField, reader, null);
}
}
private static
|
RecoverySourcePruneMergePolicy
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/output/ComplexData.java
|
{
"start": 1547,
"end": 2077
}
|
class ____ the {@link ComplexData#getDynamicSet()}, {@link ComplexData#getDynamicList()} and
* {@link ComplexData#getDynamicMap()} methods to return the data received in the server in a implementation of the Collections
* framework. If a given implementation could not do the conversion in a meaningful way an {@link UnsupportedOperationException}
* would be thrown.
*
* @see ComplexOutput
* @see ArrayComplexData
* @see SetComplexData
* @see MapComplexData
* @author Tihomir Mateev
* @since 6.5
*/
public abstract
|
override
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/spi/CheckConstraintCollector.java
|
{
"start": 338,
"end": 463
}
|
interface ____ extends Annotation {
CheckConstraint[] check();
void check(CheckConstraint[] value);
}
|
CheckConstraintCollector
|
java
|
elastic__elasticsearch
|
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlBaseParser.java
|
{
"start": 277651,
"end": 280997
}
|
class ____ extends ParserRuleContext {
public TerminalNode YEAR() {
return getToken(SqlBaseParser.YEAR, 0);
}
public TerminalNode YEARS() {
return getToken(SqlBaseParser.YEARS, 0);
}
public TerminalNode MONTH() {
return getToken(SqlBaseParser.MONTH, 0);
}
public TerminalNode MONTHS() {
return getToken(SqlBaseParser.MONTHS, 0);
}
public TerminalNode DAY() {
return getToken(SqlBaseParser.DAY, 0);
}
public TerminalNode DAYS() {
return getToken(SqlBaseParser.DAYS, 0);
}
public TerminalNode HOUR() {
return getToken(SqlBaseParser.HOUR, 0);
}
public TerminalNode HOURS() {
return getToken(SqlBaseParser.HOURS, 0);
}
public TerminalNode MINUTE() {
return getToken(SqlBaseParser.MINUTE, 0);
}
public TerminalNode MINUTES() {
return getToken(SqlBaseParser.MINUTES, 0);
}
public TerminalNode SECOND() {
return getToken(SqlBaseParser.SECOND, 0);
}
public TerminalNode SECONDS() {
return getToken(SqlBaseParser.SECONDS, 0);
}
public IntervalFieldContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override
public int getRuleIndex() {
return RULE_intervalField;
}
@Override
public void enterRule(ParseTreeListener listener) {
if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).enterIntervalField(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).exitIntervalField(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if (visitor instanceof SqlBaseVisitor) return ((SqlBaseVisitor<? extends T>) visitor).visitIntervalField(this);
else return visitor.visitChildren(this);
}
}
public final IntervalFieldContext intervalField() throws RecognitionException {
IntervalFieldContext _localctx = new IntervalFieldContext(_ctx, getState());
enterRule(_localctx, 98, RULE_intervalField);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(814);
_la = _input.LA(1);
if (!((((_la) & ~0x3f) == 0 && ((1L << _la) & -2305420796723462144L) != 0)
|| ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & 412317646849L) != 0))) {
_errHandler.recoverInline(this);
} else {
if (_input.LA(1) == Token.EOF) matchedEOF = true;
_errHandler.reportMatch(this);
consume();
}
}
} catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
} finally {
exitRule();
}
return _localctx;
}
@SuppressWarnings("CheckReturnValue")
public static
|
IntervalFieldContext
|
java
|
apache__kafka
|
streams/src/test/java/org/apache/kafka/test/MockInitializer.java
|
{
"start": 936,
"end": 1155
}
|
class ____ implements Initializer<String> {
@Override
public String apply() {
return "0";
}
}
public static final Initializer<String> STRING_INIT = new StringInit();
}
|
StringInit
|
java
|
apache__kafka
|
storage/src/test/java/org/apache/kafka/tiered/storage/actions/StopBrokerAction.java
|
{
"start": 1021,
"end": 1436
}
|
class ____ implements TieredStorageTestAction {
private final int brokerId;
public StopBrokerAction(int brokerId) {
this.brokerId = brokerId;
}
@Override
public void doExecute(TieredStorageTestContext context) {
context.stop(brokerId);
}
@Override
public void describe(PrintStream output) {
output.println("stop-broker: " + brokerId);
}
}
|
StopBrokerAction
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/ast/stmt/SQLServerInsertStatement.java
|
{
"start": 1084,
"end": 3057
}
|
class ____ extends SQLInsertStatement implements SQLServerObject {
private boolean defaultValues;
private SQLTop top;
private SQLServerOutput output;
public SQLServerInsertStatement() {
dbType = DbType.sqlserver;
}
public void cloneTo(SQLServerInsertStatement x) {
super.cloneTo(x);
x.defaultValues = defaultValues;
if (top != null) {
x.setTop(top.clone());
}
if (output != null) {
x.setOutput(output.clone());
}
}
@Override
public void accept0(SQLASTVisitor v) {
if (v instanceof SQLServerASTVisitor) {
accept0((SQLServerASTVisitor) v);
} else {
super.accept0(v);
}
}
@Override
public void accept0(SQLServerASTVisitor visitor) {
if (visitor.visit(this)) {
this.acceptChild(visitor, getTop());
this.acceptChild(visitor, getTableSource());
this.acceptChild(visitor, getColumns());
this.acceptChild(visitor, getOutput());
this.acceptChild(visitor, getValuesList());
this.acceptChild(visitor, getQuery());
}
visitor.endVisit(this);
}
public boolean isDefaultValues() {
return defaultValues;
}
public void setDefaultValues(boolean defaultValues) {
this.defaultValues = defaultValues;
}
public SQLServerOutput getOutput() {
return output;
}
public void setOutput(SQLServerOutput output) {
this.output = output;
}
public SQLTop getTop() {
return top;
}
public void setTop(SQLTop top) {
if (top != null) {
top.setParent(this);
top.setParentheses(true);
}
this.top = top;
}
public SQLServerInsertStatement clone() {
SQLServerInsertStatement x = new SQLServerInsertStatement();
cloneTo(x);
return x;
}
}
|
SQLServerInsertStatement
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/classloading/jar/CheckpointedStreamingProgram.java
|
{
"start": 1561,
"end": 1620
}
|
class ____ the state.
*/
@SuppressWarnings("serial")
public
|
as
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/usertype/UserType.java
|
{
"start": 4627,
"end": 7696
}
|
class ____ implements UserType<BitSet> {
*
* @Override
* public int getSqlType() {
* return Types.VARCHAR;
* }
*
* @Override
* public Class<BitSet> returnedClass() {
* return BitSet.class;
* }
*
* @Override
* public boolean equals(BitSet x, BitSet y) {
* return Objects.equals(x, y);
* }
*
* @Override
* public int hashCode(BitSet x) {
* return x.hashCode();
* }
*
* @Override
* public BitSet nullSafeGet(ResultSet rs, int position, WrapperOptions options)
* throws SQLException {
* String string = rs.getString(position);
* return rs.wasNull()? null : parseBitSet(columnValue);
* }
*
* @Override
* public void nullSafeSet(PreparedStatement st, BitSet bitSet, int index, WrapperOptions options)
* throws SQLException {
* if (bitSet == null) {
* st.setNull(index, VARCHAR);
* }
* else {
* st.setString(index, formatBitSet(bitSet));
* }
* }
*
* @Override
* public BitSet deepCopy(BitSet value) {
* return bitSet == null ? null : (BitSet) bitSet.clone();
* }
*
* @Override
* public boolean isMutable() {
* return true;
* }
*
* @Override
* public Serializable disassemble(BitSet value) {
* return deepCopy(value);
* }
*
* @Override
* public BitSet assemble(Serializable cached, Object owner)
* throws HibernateException {
* return deepCopy((BitSet) cached);
* }
* }
* </pre>
* <p>
* Every implementor of {@code UserType} must be immutable and must
* declare a public default constructor.
* <p>
* A custom type implemented as a {@code UserType} is treated as a
* non-composite value, and does not have persistent attributes which
* may be used in queries. If a custom type does have attributes, and
* can be thought of as something more like an embeddable object, it
* might be better to implement {@link CompositeUserType}.
*
* @apiNote
* This interface:
* <ul>
* <li>abstracts user code away from changes to the internal interface
* {@link org.hibernate.type.Type},
* <li>simplifies the implementation of custom types, and
* <li>hides certain SPI interfaces from user code.
* </ul>
* <p>
* The class {@link org.hibernate.type.CustomType} automatically adapts
* between {@code UserType} and {@link org.hibernate.type.Type}.
* In principle, a custom type could implement {@code Type} directly,
* or extend one of the abstract classes in {@link org.hibernate.type}.
* But this approach risks breakage resulting from future incompatible
* changes to classes or interfaces in that package, and is therefore
* discouraged.
*
* @see org.hibernate.type.Type
* @see org.hibernate.type.CustomType
*
* @see org.hibernate.annotations.Type
* @see org.hibernate.annotations.TypeRegistration
*
* @author Gavin King
*/
public
|
BitSetUserType
|
java
|
apache__camel
|
components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/VertxPlatformHttpLargeMessageStreamingTest.java
|
{
"start": 1472,
"end": 3509
}
|
class ____ {
@Test
void testStreamingWithLargeRequestAndResponseBody() throws Exception {
final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
context.getStreamCachingStrategy().setSpoolEnabled(true);
Path input = createLargeFile();
Path output = Files.createTempFile("platform-http-output", "dat");
try {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("platform-http:/streaming?useStreaming=true")
.log("Done echoing back request body as response body");
}
});
context.start();
InputStream response = given()
.body(new FileInputStream(input.toFile()))
.post("/streaming")
.then()
.extract()
.asInputStream();
try (FileOutputStream fos = new FileOutputStream(output.toFile())) {
IOHelper.copy(response, fos);
}
assertEquals(input.toFile().length(), output.toFile().length());
} finally {
context.stop();
Files.deleteIfExists(input);
Files.deleteIfExists(output);
}
}
private Path createLargeFile() throws IOException {
// Create a 4GB file containing random data
Path path = Files.createTempFile("platform-http-input", "dat");
try (FileOutputStream fos = new FileOutputStream(path.toFile())) {
Random random = new Random();
long targetFileSize = (long) (4 * Math.pow(1024, 3));
long bytesWritten = 0L;
byte[] data = new byte[1024];
while (bytesWritten < targetFileSize) {
random.nextBytes(data);
fos.write(data);
bytesWritten += data.length;
}
}
return path;
}
}
|
VertxPlatformHttpLargeMessageStreamingTest
|
java
|
google__dagger
|
javatests/dagger/hilt/processor/internal/definecomponent/DefineComponentProcessorTest.java
|
{
"start": 9549,
"end": 10221
}
|
interface ____ {}");
HiltCompilerTests.hiltCompiler(component)
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
"@DefineComponent test.FooComponent is missing a parent "
+ "declaration.");
});
}
@Test
public void testDefineComponentBuilderClass_fails() {
Source builder =
HiltCompilerTests.javaSource(
"test.FooComponentBuilder",
"package test;",
"",
"import dagger.hilt.DefineComponent;",
"",
"@DefineComponent.Builder",
"abstract
|
FooComponent
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/main/java/org/springframework/boot/support/AnsiOutputApplicationListener.java
|
{
"start": 1360,
"end": 2051
}
|
class ____
implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
Binder.get(environment)
.bind("spring.output.ansi.enabled", AnsiOutput.Enabled.class)
.ifBound(AnsiOutput::setEnabled);
AnsiOutput.setConsoleAvailable(environment.getProperty("spring.output.ansi.console-available", Boolean.class));
}
@Override
public int getOrder() {
// Apply after EnvironmentPostProcessorApplicationListener
return EnvironmentPostProcessorApplicationListener.DEFAULT_ORDER + 1;
}
}
|
AnsiOutputApplicationListener
|
java
|
elastic__elasticsearch
|
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/Literals.java
|
{
"start": 847,
"end": 1087
}
|
class ____ {
private Literals() {
}
/**
* All custom types that are not serializable by default can be be serialized as a part of Cursor (i.e as constant in ConstantProcessor)
* should implement NamedWriteables
|
Literals
|
java
|
spring-projects__spring-boot
|
module/spring-boot-tomcat/src/test/java/org/springframework/boot/tomcat/servlet/TldPatternsTests.java
|
{
"start": 994,
"end": 2113
}
|
class ____ {
@Test
void tomcatSkipAlignsWithTomcatDefaults() throws IOException {
assertThat(TldPatterns.TOMCAT_SKIP).containsExactlyInAnyOrderElementsOf(getTomcatDefaultJarsToSkip());
}
@Test
void tomcatScanAlignsWithTomcatDefaults() throws IOException {
assertThat(TldPatterns.TOMCAT_SCAN).containsExactlyInAnyOrderElementsOf(getTomcatDefaultJarsToScan());
}
private Set<String> getTomcatDefaultJarsToSkip() throws IOException {
return getTomcatDefault("tomcat.util.scan.StandardJarScanFilter.jarsToSkip");
}
private Set<String> getTomcatDefaultJarsToScan() throws IOException {
return getTomcatDefault("tomcat.util.scan.StandardJarScanFilter.jarsToScan");
}
private Set<String> getTomcatDefault(String key) throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
try (InputStream inputStream = classLoader.getResource("catalina.properties").openStream()) {
Properties properties = new Properties();
properties.load(inputStream);
String jarsToSkip = properties.getProperty(key);
return StringUtils.commaDelimitedListToSet(jarsToSkip);
}
}
}
|
TldPatternsTests
|
java
|
grpc__grpc-java
|
xds/src/main/java/io/grpc/xds/RouterFilter.java
|
{
"start": 769,
"end": 1227
}
|
class ____ implements Filter {
private static final RouterFilter INSTANCE = new RouterFilter();
static final String TYPE_URL =
"type.googleapis.com/envoy.extensions.filters.http.router.v3.Router";
static final FilterConfig ROUTER_CONFIG = new FilterConfig() {
@Override
public String typeUrl() {
return TYPE_URL;
}
@Override
public String toString() {
return "ROUTER_CONFIG";
}
};
static final
|
RouterFilter
|
java
|
mockito__mockito
|
mockito-core/src/main/java/org/mockito/exceptions/misusing/CannotStubVoidMethodWithReturnValue.java
|
{
"start": 223,
"end": 389
}
|
class ____ extends MockitoException {
public CannotStubVoidMethodWithReturnValue(String message) {
super(message);
}
}
|
CannotStubVoidMethodWithReturnValue
|
java
|
assertj__assertj-core
|
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/fields/RecursiveComparisonAssert_for_optionals_Test.java
|
{
"start": 919,
"end": 1506
}
|
class ____ extends WithComparingFieldsIntrospectionStrategyBaseTest {
// verify we don't need to cast actual to an Object as before when only Object assertions provided usingRecursiveComparison()
@Test
void should_be_directly_usable_with_maps() {
// GIVEN
Optional<Person> person = Optional.of(new Person("Sheldon"));
Optional<PersonDto> personDto = Optional.of(new PersonDto("Sheldon"));
// WHEN/THEN
then(person).usingRecursiveComparison(recursiveComparisonConfiguration)
.isEqualTo(personDto);
}
}
|
RecursiveComparisonAssert_for_optionals_Test
|
java
|
apache__camel
|
components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/SegmentDecorator.java
|
{
"start": 1053,
"end": 1164
}
|
interface ____ a decorator specific to the component/endpoint being instrumented.
*/
@Deprecated
public
|
represents
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/internal/jdk8/FlowableFromOptionalTest.java
|
{
"start": 746,
"end": 1067
}
|
class ____ extends RxJavaTest {
@Test
public void hasValue() {
Flowable.fromOptional(Optional.of(1))
.test()
.assertResult(1);
}
@Test
public void empty() {
Flowable.fromOptional(Optional.empty())
.test()
.assertResult();
}
}
|
FlowableFromOptionalTest
|
java
|
google__guava
|
android/guava/src/com/google/common/net/InetAddresses.java
|
{
"start": 30110,
"end": 30543
}
|
class ____ encoded in various portions of the IPv6 address as part
* of the protocol. More protocols details can be found at: <a target="_parent"
* href="http://en.wikipedia.org/wiki/Teredo_tunneling">http://en.wikipedia.
* org/wiki/Teredo_tunneling</a>.
*
* <p>The RFC can be found here: <a target="_parent" href="http://tools.ietf.org/html/rfc4380">RFC
* 4380</a>.
*
* @since 5.0
*/
public static final
|
are
|
java
|
google__guava
|
guava-tests/test/com/google/common/reflect/ClassPathTest.java
|
{
"start": 20758,
"end": 26333
}
|
class ____ {}
public void testNulls() throws IOException {
new NullPointerTester().testAllPublicStaticMethods(ClassPath.class);
new NullPointerTester()
.testAllPublicInstanceMethods(ClassPath.from(getClass().getClassLoader()));
}
@AndroidIncompatible // ClassPath is documented as not supporting Android
public void testLocationsFrom_idempotentScan() throws IOException {
ImmutableSet<ClassPath.LocationInfo> locations =
ClassPath.locationsFrom(getClass().getClassLoader());
assertThat(locations).isNotEmpty();
for (ClassPath.LocationInfo location : locations) {
ImmutableSet<ResourceInfo> resources = location.scanResources();
assertThat(location.scanResources()).containsExactlyElementsIn(resources);
}
}
public void testLocationsFrom_idempotentLocations() {
ImmutableSet<ClassPath.LocationInfo> locations =
ClassPath.locationsFrom(getClass().getClassLoader());
assertThat(ClassPath.locationsFrom(getClass().getClassLoader()))
.containsExactlyElementsIn(locations);
}
public void testLocationEquals() {
ClassLoader child = getClass().getClassLoader();
ClassLoader parent = child.getParent();
new EqualsTester()
.addEqualityGroup(
new ClassPath.LocationInfo(new File("foo.jar"), child),
new ClassPath.LocationInfo(new File("foo.jar"), child))
.addEqualityGroup(new ClassPath.LocationInfo(new File("foo.jar"), parent))
.addEqualityGroup(new ClassPath.LocationInfo(new File("foo"), child))
.testEquals();
}
@AndroidIncompatible // ClassPath is documented as not supporting Android
public void testScanAllResources() throws IOException {
assertThat(scanResourceNames(ClassLoader.getSystemClassLoader()))
.contains("com/google/common/reflect/ClassPathTest.class");
}
private static ClassPath.ClassInfo findClass(
Iterable<ClassPath.ClassInfo> classes, Class<?> cls) {
for (ClassPath.ClassInfo classInfo : classes) {
if (classInfo.getName().equals(cls.getName())) {
return classInfo;
}
}
throw new AssertionError("failed to find " + cls);
}
private static ResourceInfo resourceInfo(Class<?> cls) {
String resource = cls.getName().replace('.', '/') + ".class";
ClassLoader loader = cls.getClassLoader();
return ResourceInfo.of(FILE, resource, loader);
}
private static ClassInfo classInfo(Class<?> cls) {
return classInfo(cls, cls.getClassLoader());
}
private static ClassInfo classInfo(Class<?> cls, ClassLoader classLoader) {
String resource = cls.getName().replace('.', '/') + ".class";
return new ClassInfo(FILE, resource, classLoader);
}
private static Manifest manifestClasspath(String classpath) throws IOException {
return manifest("Class-Path: " + classpath + "\n");
}
private static void writeSelfReferencingJarFile(File jarFile, String... entries)
throws IOException {
Manifest manifest = new Manifest();
// Without version, the manifest is silently ignored. Ugh!
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, jarFile.getName());
Closer closer = Closer.create();
try {
FileOutputStream fileOut = closer.register(new FileOutputStream(jarFile));
JarOutputStream jarOut = closer.register(new JarOutputStream(fileOut, manifest));
for (String entry : entries) {
jarOut.putNextEntry(new ZipEntry(entry));
Resources.copy(ClassPathTest.class.getResource(entry), jarOut);
jarOut.closeEntry();
}
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
private static Manifest manifest(String content) throws IOException {
InputStream in = new ByteArrayInputStream(content.getBytes(US_ASCII));
Manifest manifest = new Manifest();
manifest.read(in);
return manifest;
}
private static File fullpath(String path) {
return new File(new File(path).toURI());
}
private static URL makeJarUrlWithName(String name) throws IOException {
/*
* TODO: cpovirk - Use java.nio.file.Files.createTempDirectory instead of
* c.g.c.io.Files.createTempDir?
*/
File fullPath = new File(Files.createTempDir(), name);
File jarFile = pickAnyJarFile();
Files.copy(jarFile, fullPath);
return fullPath.toURI().toURL();
}
private static File pickAnyJarFile() throws IOException {
for (ClassPath.LocationInfo location :
ClassPath.locationsFrom(ClassPathTest.class.getClassLoader())) {
if (!location.file().isDirectory() && location.file().exists()) {
return location.file();
}
}
throw new AssertionError("Failed to find a jar file");
}
@AndroidIncompatible // Path (for symlink creation)
private static void deleteRecursivelyOrLog(Path path) {
try {
deleteRecursively(path);
} catch (IOException e) {
log.log(WARNING, "Failure cleaning up test directory", e);
}
}
private static ImmutableSet<String> scanResourceNames(ClassLoader loader) throws IOException {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
for (ClassPath.LocationInfo location : ClassPath.locationsFrom(loader)) {
for (ResourceInfo resource : location.scanResources()) {
builder.add(resource.getResourceName());
}
}
return builder.build();
}
private static boolean isWindows() {
return OS_NAME.value().startsWith("Windows");
}
}
|
Nested
|
java
|
spring-projects__spring-framework
|
spring-web/src/test/java/org/springframework/web/method/ControllerAdviceBeanTests.java
|
{
"start": 12342,
"end": 12492
}
|
class ____ {
}
@ControllerAdvice(annotations = ControllerAnnotation.class, assignableTypes = ControllerInterface.class)
static
|
BasePackageValueSupport
|
java
|
mapstruct__mapstruct
|
processor/src/main/java/org/mapstruct/ap/internal/model/SupportingConstructorFragment.java
|
{
"start": 540,
"end": 3476
}
|
class ____ extends ModelElement {
private final String variableName;
private final String templateName;
private final SupportingMappingMethod definingMethod;
public SupportingConstructorFragment(SupportingMappingMethod definingMethod,
ConstructorFragment constructorFragment, String variableName) {
this.templateName = getTemplateNameForClass( constructorFragment.getClass() );
this.definingMethod = definingMethod;
this.variableName = variableName;
}
@Override
public String getTemplateName() {
return templateName;
}
@Override
public Set<Type> getImportTypes() {
return Collections.emptySet();
}
public SupportingMappingMethod getDefiningMethod() {
return definingMethod;
}
public String getVariableName() {
return variableName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ( ( variableName == null ) ? 0 : variableName.hashCode() );
result = prime * result + ( ( templateName == null ) ? 0 : templateName.hashCode() );
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
SupportingConstructorFragment other = (SupportingConstructorFragment) obj;
if ( !Objects.equals( variableName, other.variableName ) ) {
return false;
}
if ( !Objects.equals( templateName, other.templateName ) ) {
return false;
}
return true;
}
public static void addAllFragmentsIn(Set<SupportingMappingMethod> supportingMappingMethods,
Set<SupportingConstructorFragment> targets) {
for ( SupportingMappingMethod supportingMappingMethod : supportingMappingMethods ) {
SupportingConstructorFragment fragment = supportingMappingMethod.getSupportingConstructorFragment();
if ( fragment != null ) {
targets.add( supportingMappingMethod.getSupportingConstructorFragment() );
}
}
}
public static SupportingConstructorFragment getSafeConstructorFragment(SupportingMappingMethod method,
ConstructorFragment fragment,
Field supportingField) {
if ( fragment == null ) {
return null;
}
return new SupportingConstructorFragment(
method,
fragment,
supportingField != null ? supportingField.getVariableName() : null );
}
}
|
SupportingConstructorFragment
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RedirectAttributesMethodArgumentResolver.java
|
{
"start": 1922,
"end": 2896
}
|
class ____ implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return RedirectAttributes.class.isAssignableFrom(parameter.getParameterType());
}
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
Assert.state(mavContainer != null, "RedirectAttributes argument only supported on regular handler methods");
ModelMap redirectAttributes;
if (binderFactory != null) {
DataBinder dataBinder = binderFactory.createBinder(webRequest, null, DataBinder.DEFAULT_OBJECT_NAME);
redirectAttributes = new RedirectAttributesModelMap(dataBinder);
}
else {
redirectAttributes = new RedirectAttributesModelMap();
}
mavContainer.setRedirectModel(redirectAttributes);
return redirectAttributes;
}
}
|
RedirectAttributesMethodArgumentResolver
|
java
|
apache__spark
|
sql/core/src/test/java/test/org/apache/spark/sql/MyDoubleAvg.java
|
{
"start": 1496,
"end": 4884
}
|
class ____ extends UserDefinedAggregateFunction {
private StructType _inputDataType;
private StructType _bufferSchema;
private DataType _returnDataType;
public MyDoubleAvg() {
List<StructField> inputFields = new ArrayList<>();
inputFields.add(DataTypes.createStructField("inputDouble", DataTypes.DoubleType, true));
_inputDataType = DataTypes.createStructType(inputFields);
// The buffer has two values, bufferSum for storing the current sum and
// bufferCount for storing the number of non-null input values that have been contributed
// to the current sum.
List<StructField> bufferFields = new ArrayList<>();
bufferFields.add(DataTypes.createStructField("bufferSum", DataTypes.DoubleType, true));
bufferFields.add(DataTypes.createStructField("bufferCount", DataTypes.LongType, true));
_bufferSchema = DataTypes.createStructType(bufferFields);
_returnDataType = DataTypes.DoubleType;
}
@Override public StructType inputSchema() {
return _inputDataType;
}
@Override public StructType bufferSchema() {
return _bufferSchema;
}
@Override public DataType dataType() {
return _returnDataType;
}
@Override public boolean deterministic() {
return true;
}
@Override public void initialize(MutableAggregationBuffer buffer) {
// The initial value of the sum is null.
buffer.update(0, null);
// The initial value of the count is 0.
buffer.update(1, 0L);
}
@Override public void update(MutableAggregationBuffer buffer, Row input) {
// This input Row only has a single column storing the input value in Double.
// We only update the buffer when the input value is not null.
if (!input.isNullAt(0)) {
// If the buffer value (the intermediate result of the sum) is still null,
// we set the input value to the buffer and set the bufferCount to 1.
if (buffer.isNullAt(0)) {
buffer.update(0, input.getDouble(0));
buffer.update(1, 1L);
} else {
// Otherwise, update the bufferSum and increment bufferCount.
Double newValue = input.getDouble(0) + buffer.getDouble(0);
buffer.update(0, newValue);
buffer.update(1, buffer.getLong(1) + 1L);
}
}
}
@Override public void merge(MutableAggregationBuffer buffer1, Row buffer2) {
// buffer1 and buffer2 have the same structure.
// We only update the buffer1 when the input buffer2's sum value is not null.
if (!buffer2.isNullAt(0)) {
if (buffer1.isNullAt(0)) {
// If the buffer value (intermediate result of the sum) is still null,
// we set the it as the input buffer's value.
buffer1.update(0, buffer2.getDouble(0));
buffer1.update(1, buffer2.getLong(1));
} else {
// Otherwise, we update the bufferSum and bufferCount.
Double newValue = buffer2.getDouble(0) + buffer1.getDouble(0);
buffer1.update(0, newValue);
buffer1.update(1, buffer1.getLong(1) + buffer2.getLong(1));
}
}
}
@Override public Object evaluate(Row buffer) {
if (buffer.isNullAt(0)) {
// If the bufferSum is still null, we return null because this function has not got
// any input row.
return null;
} else {
// Otherwise, we calculate the special average value.
return buffer.getDouble(0) / buffer.getLong(1) + 100.0;
}
}
}
|
MyDoubleAvg
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/checkpointing/AutoRescalingITCase.java
|
{
"start": 32307,
"end": 34014
}
|
class ____
extends RichFlatMapFunction<Integer, Tuple2<Integer, Integer>>
implements CheckpointedFunction {
private static final long serialVersionUID = 5273172591283191348L;
private static CountDownLatch workCompletedLatch = new CountDownLatch(1);
private transient ValueState<Integer> counter;
private transient ValueState<Integer> sum;
private final int numberElements;
SubtaskIndexFlatMapper(int numberElements) {
this.numberElements = numberElements;
}
@Override
public void flatMap(Integer value, Collector<Tuple2<Integer, Integer>> out)
throws Exception {
int count = counter.value() + 1;
counter.update(count);
int s = sum.value() + value;
sum.update(s);
if (count % numberElements == 0) {
out.collect(
Tuple2.of(getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(), s));
workCompletedLatch.countDown();
}
}
@Override
public void snapshotState(FunctionSnapshotContext context) {
// all managed, nothing to do.
}
@Override
public void initializeState(FunctionInitializationContext context) {
counter =
context.getKeyedStateStore()
.getState(new ValueStateDescriptor<>("counter", Integer.class, 0));
sum =
context.getKeyedStateStore()
.getState(new ValueStateDescriptor<>("sum", Integer.class, 0));
}
}
private static
|
SubtaskIndexFlatMapper
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java
|
{
"start": 118338,
"end": 119265
}
|
class ____
extends MyCommandProvidingFormController<String, TestBean, ITestBean> {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.initBeanPropertyAccess();
binder.setRequiredFields("sex");
LocalValidatorFactoryBean vf = new LocalValidatorFactoryBean();
vf.afterPropertiesSet();
binder.setValidator(vf);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
@Override
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") @Valid TestBean tb, BindingResult errors, ModelMap model) {
if (!errors.hasFieldErrors("sex")) {
throw new IllegalStateException("requiredFields not applied");
}
return super.myHandle(tb, errors, model);
}
}
@Controller
static
|
MyBinderInitializingCommandProvidingFormController
|
java
|
google__guice
|
extensions/testlib/test/com/google/inject/testing/fieldbinder/BoundFieldModuleTest.java
|
{
"start": 28201,
"end": 28654
}
|
class ____ {
@Bind(lazy = true)
@Nullable
Integer foo = 1;
}
public void testNullableFieldBound_lazy_allowNull() {
LazyClassNullable asProvider = new LazyClassNullable();
Injector injector = Guice.createInjector(BoundFieldModule.of(asProvider));
assertEquals(1, injector.getInstance(Integer.class).intValue());
asProvider.foo = null;
assertNull(injector.getInstance(Integer.class));
}
static final
|
LazyClassNullable
|
java
|
quarkusio__quarkus
|
extensions/smallrye-health/deployment/src/test/java/io/quarkus/smallrye/health/test/AsyncDispatchedThreadTest.java
|
{
"start": 2667,
"end": 3131
}
|
class ____ implements AsyncHealthCheck {
@Override
public Uni<HealthCheckResponse> call() {
return Uni.createFrom().item(HealthCheckResponse.named("my-readiness-check")
.up()
.withData("thread", Thread.currentThread().getName())
.withData("request", Arc.container().requestContext().isActive())
.build());
}
}
}
|
ReadinessHealthCheckCapturingThread
|
java
|
quarkusio__quarkus
|
integration-tests/opentelemetry-reactive-messaging/src/main/java/io/quarkus/it/opentelemetry/output/SpanDataSerializer.java
|
{
"start": 300,
"end": 2055
}
|
class ____ extends StdSerializer<SpanData> {
public SpanDataSerializer() {
this(null);
}
public SpanDataSerializer(Class<SpanData> type) {
super(type);
}
@Override
public void serialize(SpanData spanData, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("spanId", spanData.getSpanId());
jsonGenerator.writeStringField("traceId", spanData.getTraceId());
jsonGenerator.writeStringField("name", spanData.getName());
jsonGenerator.writeStringField("kind", spanData.getKind().name());
jsonGenerator.writeBooleanField("ended", spanData.hasEnded());
jsonGenerator.writeStringField("parent_spanId", spanData.getParentSpanContext().getSpanId());
jsonGenerator.writeStringField("parent_traceId", spanData.getParentSpanContext().getTraceId());
jsonGenerator.writeBooleanField("parent_remote", spanData.getParentSpanContext().isRemote());
jsonGenerator.writeBooleanField("parent_valid", spanData.getParentSpanContext().isValid());
spanData.getAttributes().forEach((k, v) -> {
try {
jsonGenerator.writeStringField("attr_" + k.getKey(), v.toString());
} catch (IOException e) {
e.printStackTrace();
}
});
spanData.getResource().getAttributes().forEach((k, v) -> {
try {
jsonGenerator.writeStringField("resource_" + k.getKey(), v.toString());
} catch (IOException e) {
e.printStackTrace();
}
});
jsonGenerator.writeEndObject();
}
}
|
SpanDataSerializer
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/nullness/NullablePrimitiveArrayTest.java
|
{
"start": 3021,
"end": 3584
}
|
class ____ {
@SuppressWarnings("SomeOtherChecker") // unrelated annotation
abstract byte @Nullable [] f();
}
""")
.doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH);
}
@Test
public void typeAnnotationWithOtherNullnessAnnotationDoesNotSuggestDoubleAnnotation() {
testHelper
.addInputLines(
"Test.java",
"""
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
abstract
|
Test
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-client-jaxrs/deployment/src/test/java/io/quarkus/jaxrs/client/reactive/deployment/test/AsyncRestClientFilterTestCase.java
|
{
"start": 3169,
"end": 3431
}
|
class ____ implements ClientRequestFilter {
@Override
public void filter(ClientRequestContext context) throws IOException {
context.getHeaders().add("sync", "foo");
}
}
@Provider
public static
|
SyncClientRequestFilter
|
java
|
quarkusio__quarkus
|
integration-tests/mtls-certificates/src/main/java/io/quarkus/it/vertx/CertificateRoleMappingResource.java
|
{
"start": 355,
"end": 1009
}
|
class ____ {
@Inject
SecurityIdentity identity;
@Authenticated
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/authenticated")
public String name() {
return identity.getPrincipal().getName();
}
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/authorized-user")
@RolesAllowed("user")
public String authorizedName() {
return identity.getPrincipal().getName();
}
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/authorized-admin")
@RolesAllowed("admin")
public String authorizedAdmin() {
return identity.getPrincipal().getName();
}
}
|
CertificateRoleMappingResource
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.